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
//! Component Location Security Example
//!
//! This example demonstrates how to use `#[in_component]` with role-based security
//! to control which file paths appear in public vs internal documentation.
//!
//! ## Key Features
//!
//! 1. **Secure by Default**: Component locations default to Internal role
//! 2. **Explicit Public Marking**: Must explicitly mark examples as public
//! 3. **Documentation Filtering**: Different docs for different audiences
//! 4. **Automatic Registration**: Macro generates registration functions with roles
//!
//! ## Run
//!
//! ```bash
//! cargo run --example component_location_security --features metadata,doc-gen
//! ```

// 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 component_location_security --features metadata,doc-gen\n\
    \n\
    Or use --all-features to enable everything:\n\
    \n\
    cargo run --example component_location_security --all-features\n\
    "
);

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

    component! {
        Auth {
            docs: "Authentication system with JWT tokens and OAuth2",
            tags: ["security", "authentication"],
        },

        Db {
            docs: "PostgreSQL database operations",
            tags: ["persistence", "sql"],
        },
    }
}

#[cfg(not(feature = "metadata"))]
pub mod components {}

// ============================================================================
// Define Primaries
// ============================================================================

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

    primary! {
        Token {
            docs: "JWT token operations",
        },

        Connection {
            docs: "Database connection operations",
        },

        Query {
            docs: "SQL query operations",
        },

        Signature {
            docs: "Cryptographic signature operations",
        },

        Secret {
            docs: "Secret key management",
        },

        Pool {
            docs: "Connection pool management",
        },

        Migration {
            docs: "Database schema migrations",
        },
    }
}

#[cfg(not(feature = "metadata"))]
pub mod primaries {}

// ============================================================================
// Define Sequences
// ============================================================================

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

    sequence! {
        EXPIRED(1) {
            description: "Resource has expired",
            typical_severity: "Error",
        },

        FAILED(2) {
            description: "Operation failed",
            typical_severity: "Error",
        },

        CLAIMS_INVALID(3) {
            description: "Claims validation failed",
            typical_severity: "Warning",
        },

        SLOW(4) {
            description: "Operation is slow",
            typical_severity: "Warning",
        },

        VERIFICATION_FAILED(5) {
            description: "Verification failed",
            typical_severity: "Error",
        },

        ROTATION_FAILED(6) {
            description: "Rotation operation failed",
            typical_severity: "Critical",
        },

        EXHAUSTED(7) {
            description: "Resource exhausted",
            typical_severity: "Critical",
        },
    }
}

#[cfg(not(feature = "metadata"))]
pub mod sequences {}

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

// ============================================================================
// Public Documentation Examples (Safe to Show Everyone)
// ============================================================================

/// Public documentation example - SAFE for public docs
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Auth, role = public)]
mod auth_public_example {

    /// Example showing basic JWT usage for public documentation
    pub fn demonstrate_jwt_usage() {
        println!("📘 Public Example: JWT token validation");
        println!("   Location: examples/auth_public_example.rs");
        println!("   Role: PUBLIC - visible to everyone");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        E.Auth.Token.EXPIRED: {
            message: "JWT token has expired",
            hints: ["Request a new token", "Use refresh token endpoint"],
        },
    }
}

/// Public database example - SAFE for public docs
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Db, role = public)]
mod db_public_example {

    /// Example showing connection pool usage for public documentation
    pub fn demonstrate_connection_pool() {
        println!("📘 Public Example: Database connection pooling");
        println!("   Location: examples/db_public_example.rs");
        println!("   Role: PUBLIC - visible to everyone");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        E.Db.Connection.FAILED: {
            message: "Failed to establish database connection",
            hints: ["Check DATABASE_URL", "Verify database is running"],
        },
    }
}

// ============================================================================
// Developer Utilities (Visible to Developers + Internal)
// ============================================================================

/// Developer debugging utilities - visible to developers and internal team
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Auth, role = developer)]
mod auth_debug {

    /// Debugging utilities for JWT token inspection
    pub fn debug_token_claims() {
        println!("🔧 Developer Utility: Token claim inspector");
        println!("   Location: src/auth/debug.rs");
        println!("   Role: DEVELOPER - visible to developers and internal");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        W.Auth.Token.CLAIMS_INVALID: {
            message: "JWT token claims are malformed",
            'CR 'Dev hints: [
                "Check token serialization logic",
                "Verify claim structure matches schema",
            ],
        },
    }
}

/// Developer database profiling - visible to developers and internal team
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Db, role = developer)]
mod db_profiler {

    /// Query performance profiling utilities
    pub fn profile_slow_queries() {
        println!("🔧 Developer Utility: Query profiler");
        println!("   Location: src/db/profiler.rs");
        println!("   Role: DEVELOPER - visible to developers and internal");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        W.Db.Query.SLOW: {
            message: "Query execution time exceeded threshold",
            'CR 'Dev hints: [
                "Add indexes for query optimization",
                "Review EXPLAIN ANALYZE output",
            ],
        },
    }
}

// ============================================================================
// Internal Implementation (SECURE - Internal Team Only)
// ============================================================================

/// Internal authentication implementation - DEFAULT SECURE
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Auth)]
mod auth_internal {

    /// JWT signature verification (internal implementation)
    pub fn verify_signature() {
        println!("🔒 Internal Implementation: JWT signature verification");
        println!("   Location: src/auth/jwt_signer.rs");
        println!("   Role: INTERNAL (default) - team only");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        E.Auth.Signature.VERIFICATION_FAILED: {
            message: "JWT signature verification failed",
            'CR 'Int hints: [
                "Check JWT_SECRET environment variable",
                "Verify key rotation hasn't broken old tokens",
                "Check token signing algorithm matches",
            ],
        },
    }
}

/// Internal secret rotation logic - EXPLICIT INTERNAL
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Auth, role = internal)]
mod auth_secrets {

    /// Secret key rotation logic (highly sensitive!)
    pub fn rotate_signing_keys() {
        println!("🔒 Internal Implementation: Secret key rotation");
        println!("   Location: src/auth/secret_rotation.rs");
        println!("   Role: INTERNAL - highly sensitive!");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        E.Auth.Secret.ROTATION_FAILED: {
            message: "Secret key rotation failed",
            'CR 'Int hints: [
                "Check HSM/KMS connectivity",
                "Verify key backup was successful",
                "Review rotation procedure logs",
            ],
        },
    }
}

/// Internal database connection pool implementation - DEFAULT SECURE
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Db)]
mod db_pool {

    /// Connection pool management (internal)
    pub fn manage_pool() {
        println!("🔒 Internal Implementation: Connection pool management");
        println!("   Location: src/db/pool.rs");
        println!("   Role: INTERNAL (default) - team only");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        C.Db.Pool.EXHAUSTED: {
            message: "Connection pool completely exhausted",
            'CR 'Int hints: [
                "Scale up pool size immediately",
                "Check for connection leaks",
                "Review long-running transactions",
            ],
        },
    }
}

/// Internal database migration logic - EXPLICIT INTERNAL
#[cfg(feature = "metadata")]
#[waddling_errors_macros::in_component(Db, role = internal)]
mod db_migrations {

    /// Schema migration logic (sensitive!)
    pub fn run_migrations() {
        println!("🔒 Internal Implementation: Database migrations");
        println!("   Location: src/db/migrations.rs");
        println!("   Role: INTERNAL - schema changes are sensitive");
    }

    waddling_errors_macros::diag! {
        strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
        E.Db.Migration.FAILED: {
            message: "Database migration failed",
            'CR 'Int hints: [
                "Check migration rollback procedure",
                "Verify schema compatibility",
                "Review migration transaction logs",
            ],
        },
    }
}

// ============================================================================
// Main Example
// ============================================================================

#[cfg(feature = "metadata")]
fn main() {
    println!("🦆 Component Location Security Example");
    println!("========================================\n");

    println!("This example shows how #[in_component] with role parameters");
    println!("controls which file paths appear in different documentation.\n");

    // Demonstrate all modules
    println!("📋 Executing all modules:\n");

    println!("PUBLIC modules (safe for everyone):");
    auth_public_example::demonstrate_jwt_usage();
    db_public_example::demonstrate_connection_pool();

    println!("\nDEVELOPER modules (for contributors):");
    auth_debug::debug_token_claims();
    db_profiler::profile_slow_queries();

    println!("\nINTERNAL modules (team only):");
    auth_internal::verify_signature();
    auth_secrets::rotate_signing_keys();
    db_pool::manage_pool();
    db_migrations::run_migrations();

    // Show generated metadata
    println!("\n\n🔍 Generated Metadata Inspection:");
    println!("==================================\n");

    println!("Auth Component Locations:\n");

    println!("  1. {}", auth_public_example::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← PUBLIC",
        auth_public_example::__COMPONENT_ROLE
    );

    println!("\n  2. {}", auth_debug::__COMPONENT_FILE);
    println!("     Role: {:?} ← DEVELOPER", auth_debug::__COMPONENT_ROLE);

    println!("\n  3. {}", auth_internal::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← INTERNAL (default)",
        auth_internal::__COMPONENT_ROLE
    );

    println!("\n  4. {}", auth_secrets::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← INTERNAL (explicit)",
        auth_secrets::__COMPONENT_ROLE
    );

    println!("\n\nDatabase Component Locations:\n");

    println!("  1. {}", db_public_example::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← PUBLIC",
        db_public_example::__COMPONENT_ROLE
    );

    println!("\n  2. {}", db_profiler::__COMPONENT_FILE);
    println!("     Role: {:?} ← DEVELOPER", db_profiler::__COMPONENT_ROLE);

    println!("\n  3. {}", db_pool::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← INTERNAL (default)",
        db_pool::__COMPONENT_ROLE
    );

    println!("\n  4. {}", db_migrations::__COMPONENT_FILE);
    println!(
        "     Role: {:?} ← INTERNAL (explicit)",
        db_migrations::__COMPONENT_ROLE
    );

    // Documentation generation demo
    #[cfg(feature = "doc-gen")]
    generate_documentation();

    println!("\n\n✨ Security Benefits:");
    println!("====================");
    println!("✅ Public docs don't leak internal file paths");
    println!("✅ Secure by default - must opt-in to public");
    println!("✅ Developer docs show debugging utilities");
    println!("✅ Internal docs show complete implementation");
    println!("✅ Prevents information disclosure attacks");
}

#[cfg(feature = "doc-gen")]
fn generate_documentation() {
    use waddling_errors::doc_generator::{DocRegistry, HtmlRenderer, JsonRenderer};

    println!("\n\n📚 Documentation Generation:");
    println!("============================\n");

    let mut registry = DocRegistry::new("Component Location Security Demo", "1.0.0");

    // Register errors from each module
    registry.register_diagnostic_runtime(&auth_public_example::E_AUTH_TOKEN_EXPIRED);
    registry.register_diagnostic_runtime(&db_public_example::E_DB_CONNECTION_FAILED);
    registry.register_diagnostic_runtime(&auth_debug::W_AUTH_TOKEN_CLAIMS_INVALID);
    registry.register_diagnostic_runtime(&db_profiler::W_DB_QUERY_SLOW);
    registry.register_diagnostic_runtime(&auth_internal::E_AUTH_SIGNATURE_VERIFICATION_FAILED);
    registry.register_diagnostic_runtime(&auth_secrets::E_AUTH_SECRET_ROTATION_FAILED);
    registry.register_diagnostic_runtime(&db_pool::C_DB_POOL_EXHAUSTED);
    registry.register_diagnostic_runtime(&db_migrations::E_DB_MIGRATION_FAILED);

    // Register component locations with automatic role handling
    println!("Registering component locations with roles...");

    auth_public_example::__register_component_location(&mut registry);
    auth_debug::__register_component_location(&mut registry);
    auth_internal::__register_component_location(&mut registry);
    auth_secrets::__register_component_location(&mut registry);

    db_public_example::__register_component_location(&mut registry);
    db_profiler::__register_component_location(&mut registry);
    db_pool::__register_component_location(&mut registry);
    db_migrations::__register_component_location(&mut registry);

    println!("✓ Registered 8 component locations (4 Auth, 4 Database)");

    // Generate role-filtered documentation
    println!("\nGenerating role-filtered documentation...");

    match registry.render_all_roles(
        vec![Box::new(HtmlRenderer::new()), Box::new(JsonRenderer)],
        "target/doc/component_security",
    ) {
        Ok(_) => {
            println!("\n✅ Documentation generated successfully!\n");
            println!("Generated files:");
            println!(
                "  📘 target/doc/component_security/Component Location Security Demo-pub.html"
            );
            println!(
                "  📘 target/doc/component_security/Component Location Security Demo-pub.json"
            );
            println!("     ↳ Shows only: auth_public_example.rs, db_public_example.rs");
            println!();
            println!(
                "  🔧 target/doc/component_security/Component Location Security Demo-dev.html"
            );
            println!(
                "  🔧 target/doc/component_security/Component Location Security Demo-dev.json"
            );
            println!("     ↳ Shows: public + auth_debug.rs, db_profiler.rs");
            println!();
            println!(
                "  🔒 target/doc/component_security/Component Location Security Demo-int.html"
            );
            println!(
                "  🔒 target/doc/component_security/Component Location Security Demo-int.json"
            );
            println!("     ↳ Shows: ALL locations (public + developer + internal)");
            println!();
            println!("🛡️  Security achieved: Internal file paths are protected!");
        }
        Err(e) => eprintln!("❌ Documentation generation failed: {}", e),
    }
}

#[cfg(not(feature = "doc-gen"))]
fn generate_documentation() {
    println!("\n\n⚠️  Documentation generation skipped");
    println!("====================================");
    println!(
        "Run with: cargo run --example component_location_security --features metadata,doc-gen"
    );
}

// Dummy main when metadata feature is not enabled (compile_error! will show first)
#[cfg(not(feature = "metadata"))]
fn main() {}