plexus-macros 0.4.0

Procedural macros for Plexus RPC activations
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
# DX Inspiration from the Rust Ecosystem

This document explores patterns from successful Rust libraries that we can adapt for Plexus macros v2.

---

## 1. Clap - Doc Comments as First-Class Citizens

**What they do well:**
```rust
#[derive(Parser)]
struct Args {
    /// The command to execute
    #[arg(short, long)]
    command: String,

    /// Timeout in seconds
    #[arg(short, long, default_value = "30")]
    timeout: u64,
}
```

**Key insights:**
- Doc comments become help text automatically
- Attributes augment but don't replace docs
- Short and long flags derived from field names
- Defaults are inline and type-checked

---

### Adaptation for Plexus:

```rust
#[activation(namespace = "bash")]
impl BashActivation {
    /// Execute a bash command and stream output
    ///
    /// This method runs the provided command in a bash shell and streams
    /// the stdout/stderr output as it becomes available.
    ///
    /// # Examples
    ///
    /// ```json
    /// {
    ///   "command": "ls -la",
    ///   "timeout": 30
    /// }
    /// ```
    #[method(http = POST, stream = Multi)]
    async fn execute(
        &self,
        /// The bash command to execute
        command: String,

        /// Maximum execution time in seconds
        #[default(30)]
        timeout: u64,

        /// Working directory for command execution
        #[default("/tmp")]
        workdir: PathBuf,
    ) -> impl Stream<Item = BashEvent> { }
}
```

**What gets extracted:**
- Method description: First paragraph of doc comment
- Method long description: Rest of doc comment before examples
- Examples: Code blocks tagged with `json` become schema examples
- Parameter descriptions: Doc comments on parameters
- Parameter defaults: From `#[default(...)]` attribute

**Benefits:**
- Natural Rust documentation style
- cargo doc shows the same info as API docs
- Examples are inline and visible
- IDE hover shows full context

---

## 2. Serde - Smart Defaults and Attribute Composition

**What they do well:**
```rust
#[derive(Serialize, Deserialize)]
struct User {
    #[serde(rename = "userId")]
    user_id: String,

    #[serde(default)]
    active: bool,

    #[serde(skip_serializing_if = "Option::is_none")]
    email: Option<String>,

    #[serde(flatten)]
    metadata: HashMap<String, Value>,
}
```

**Key insights:**
- Attributes are composable (multiple per field work together)
- Smart defaults (`default` uses Default trait)
- Skip patterns are flexible
- Flattening for composition

---

### Adaptation for Plexus:

```rust
#[method]
async fn update_user(
    &self,

    /// User ID to update
    #[validate(uuid)]
    user_id: String,

    /// User email address
    #[validate(email)]
    #[example("user@example.com")]
    email: Option<String>,

    /// User status
    #[default(UserStatus::Active)]
    #[validate(oneof = ["active", "inactive", "banned"])]
    status: UserStatus,

    /// Additional metadata
    #[flatten]
    metadata: HashMap<String, Value>,

    #[skip]
    ctx: &RequestContext,
) -> Result<User> { }
```

**New attributes:**
- `#[validate(...)]` - Parameter validation (email, uuid, range, etc.)
- `#[example("...")]` - Example value for docs/testing
- `#[flatten]` - Merge nested structure into params
- Multiple attributes compose naturally

---

## 3. Axum - Type-Driven Extractors

**What they do well:**
```rust
async fn handler(
    Path(user_id): Path<String>,
    Query(params): Query<SearchParams>,
    Json(body): Json<CreateUser>,
    State(db): State<Database>,
) -> Result<Json<User>> { }
```

**Key insight:** Type signature drives behavior (no annotations needed).

---

### Adaptation for Plexus:

```rust
#[method]
async fn create_user(
    &self,

    // Normal parameters (from request body)
    name: String,
    email: String,

    // Extractors (special parameter types)
    Auth(token): Auth<BearerToken>,      // Extract from auth header
    RateLimit(limiter): RateLimit,       // Rate limiting state
    Trace(span): Trace,                  // Tracing context

    #[skip]
    db: &Database,                       // Injected dependency
) -> Result<User> { }
```

**Benefits:**
- Type-based behavior is clear
- No magic parameter name detection
- Easy to add new extractor types
- Composable with other attributes

**Implementation:** Could use newtype wrappers that get special treatment:
```rust
pub struct Auth<T>(pub T);
pub struct RateLimit(pub RateLimiter);
pub struct Trace(pub Span);
```

---

## 4. Utoipa - Rich OpenAPI Annotations

**What they do well:**
```rust
#[utoipa::path(
    get,
    path = "/users/{id}",
    responses(
        (status = 200, description = "User found", body = User),
        (status = 404, description = "User not found"),
    ),
    params(
        ("id" = String, Path, description = "User ID")
    ),
    security(
        ("bearer_auth" = [])
    )
)]
async fn get_user(path: Path<String>) -> Result<Json<User>> { }
```

**Key insights:**
- Rich response documentation
- Multiple response types
- Security requirements
- Path parameter documentation

---

### Adaptation for Plexus:

```rust
#[method(
    http = GET,
    responses(
        ok(User, "User found successfully"),
        not_found("User not found"),
        unauthorized("Invalid authentication token"),
    ),
    security = bearer,
    tags = ["users", "public"],
)]
async fn get_user(
    &self,

    /// User ID to retrieve
    #[validate(uuid)]
    user_id: String,
) -> Result<User> { }
```

**New features:**
- `responses(...)` - Document possible response types
- `security = ...` - Authentication requirements
- `tags = [...]` - OpenAPI tags for grouping
- Better error documentation

---

## 5. Validator - Declarative Validation

**What they do well:**
```rust
#[derive(Validate)]
struct User {
    #[validate(email)]
    email: String,

    #[validate(length(min = 8, max = 100))]
    password: String,

    #[validate(range(min = 18, max = 120))]
    age: u8,

    #[validate(url)]
    website: Option<String>,

    #[validate(custom = "validate_username")]
    username: String,
}
```

**Key insights:**
- Validation is declarative, not imperative
- Common validators built-in
- Custom validators supported
- Validation happens automatically

---

### Adaptation for Plexus:

```rust
#[method]
async fn register_user(
    &self,

    /// User's email address
    #[validate(email)]
    email: String,

    /// Password (8-100 characters)
    #[validate(length(min = 8, max = 100))]
    password: String,

    /// User's age
    #[validate(range(min = 18, max = 120))]
    age: u8,

    /// Username (alphanumeric only)
    #[validate(regex = r"^[a-zA-Z0-9_]+$")]
    username: String,

    /// Profile URL
    #[validate(url)]
    website: Option<String>,
) -> Result<User> { }
```

**Built-in validators:**
- `email` - Valid email format
- `url` - Valid URL format
- `uuid` - Valid UUID format
- `length(min, max)` - String length
- `range(min, max)` - Numeric range
- `regex = "..."` - Pattern matching
- `oneof = [...]` - Enum validation
- `custom = "fn_name"` - Custom validator function

**Benefits:**
- Validation happens before method is called
- Clear error messages with field-level details
- Schema includes validation constraints
- Self-documenting (validation rules visible in code)

---

## 6. Rocket - Route Attributes

**What they do well:**
```rust
#[get("/users/<id>?<limit>&<offset>")]
fn get_user(id: String, limit: Option<usize>, offset: Option<usize>) -> Json<User> { }

#[post("/users", data = "<user>")]
fn create_user(user: Json<CreateUser>) -> Status { }
```

**Key insight:** Path and query params are extracted from URL pattern.

---

### Adaptation for Plexus:

While we don't need URL routing (REST bridge handles that), we could support:

```rust
#[method(
    http = GET,
    path = "/users/{user_id}/posts/{post_id}",  // Explicit path template
)]
async fn get_post(
    &self,

    /// User ID (from path)
    #[path]
    user_id: String,

    /// Post ID (from path)
    #[path]
    post_id: String,

    /// Maximum results (from query)
    #[query]
    limit: Option<usize>,
) -> Result<Post> { }
```

**Or keep it simpler:**
- All non-annotated params → JSON body
- `#[path]` params → URL path segments
- `#[query]` params → URL query string

---

## 7. Tokio - Convention Over Configuration

**What they do well:**
```rust
#[tokio::main]
async fn main() { }

#[tokio::test]
async fn test_something() { }
```

**Key insight:** Minimal syntax for common cases.

---

### Adaptation for Plexus:

```rust
// Minimal case: just use doc comments
#[activation(namespace = "simple")]
impl SimpleActivation {
    /// Get user by ID
    async fn get_user(&self, id: String) -> User { }

    // No attributes needed!
    // - Method name: get_user
    // - HTTP method: POST (default)
    // - Streaming: auto-detected from return type
    // - Description: from doc comment
}

// Complex case: explicit configuration
#[activation(namespace = "complex")]
impl ComplexActivation {
    /// Get user by ID
    #[method(
        http = GET,
        stream = Single,
        cache = 60,
        rate_limit = (100, per_minute),
    )]
    async fn get_user(
        &self,
        #[validate(uuid)] id: String,
    ) -> User { }
}
```

**Progressive disclosure:** Start simple, add attributes as needed.

---

## 8. SQLx - Compile-Time Verification

**What they do well:**
```rust
let user = sqlx::query_as!(
    User,
    "SELECT id, name, email FROM users WHERE id = $1",
    user_id
)
.fetch_one(&pool)
.await?;
```

**Key insight:** Compile-time checking of SQL queries against real database.

---

### Adaptation for Plexus:

```rust
#[method]
async fn execute_query(
    &self,

    /// SQL query to execute
    #[validate(sql)]  // ← Compile-time validation against schema
    query: String,
) -> Result<QueryResult> { }
```

**Future possibility:**
- Validate parameter types against MethodSchema at compile time
- Validate return types match declared schema
- Catch type mismatches before runtime

---

## Complete Example: Combining All Patterns

Here's what a fully-featured Plexus activation could look like:

```rust
use plexus::prelude::*;

/// User management service
///
/// Provides CRUD operations for user accounts with authentication,
/// validation, and rate limiting.
#[activation(
    namespace = "users",
    version = "2.0.0",
    description = "User management service",
    methods_enum = "UserMethods",
    schema_method = true,
)]
impl UserService {
    /// Get a user by ID
    ///
    /// Retrieves detailed information about a specific user account.
    /// Requires authentication.
    ///
    /// # Examples
    ///
    /// ```json
    /// {
    ///   "user_id": "550e8400-e29b-41d4-a716-446655440000"
    /// }
    /// ```
    ///
    /// # Returns
    ///
    /// User object with all fields populated.
    #[method(
        http = GET,
        stream = Single,
        responses(
            ok(User, "User found"),
            not_found("User does not exist"),
            unauthorized("Invalid authentication"),
        ),
        security = bearer,
        tags = ["users", "read"],
        cache = 60,  // Cache for 60 seconds
    )]
    async fn get_user(
        &self,

        /// User ID to retrieve
        #[validate(uuid)]
        #[example("550e8400-e29b-41d4-a716-446655440000")]
        user_id: String,

        /// Include deleted users in search
        #[default(false)]
        include_deleted: bool,

        Auth(token): Auth<BearerToken>,
        RateLimit(limiter): RateLimit,

        #[skip]
        db: &Database,
    ) -> Result<User, UserError> {
        // Implementation
    }

    /// Create a new user
    ///
    /// Creates a new user account with validation.
    ///
    /// # Examples
    ///
    /// ```json
    /// {
    ///   "email": "user@example.com",
    ///   "name": "John Doe",
    ///   "age": 25
    /// }
    /// ```
    #[method(
        http = POST,
        stream = Single,
        responses(
            created(User, "User created successfully"),
            bad_request("Invalid user data"),
            conflict("User already exists"),
        ),
        tags = ["users", "write"],
        rate_limit = (10, per_minute),
    )]
    async fn create_user(
        &self,

        /// User's email address
        #[validate(email)]
        #[example("user@example.com")]
        email: String,

        /// Full name
        #[validate(length(min = 2, max = 100))]
        name: String,

        /// User's age (must be 18+)
        #[validate(range(min = 18, max = 120))]
        age: u8,

        /// Password (8-100 characters, alphanumeric + special chars)
        #[validate(length(min = 8, max = 100))]
        #[validate(regex = r"^[a-zA-Z0-9!@#$%^&*]+$")]
        #[sensitive]  // Don't log this parameter
        password: String,

        /// Additional user metadata
        #[flatten]
        metadata: HashMap<String, Value>,

        Auth(token): Auth<AdminToken>,

        #[skip]
        db: &Database,
    ) -> Result<User, UserError> {
        // Implementation
    }

    /// Watch user activity in real-time
    ///
    /// Streams user activity events as they occur. This is an infinite
    /// stream that continues until the client disconnects.
    #[method(
        http = POST,
        stream = Infinite,
        responses(
            ok(UserEvent, "Activity event stream"),
            unauthorized("Invalid authentication"),
        ),
        security = bearer,
        tags = ["users", "streaming"],
    )]
    async fn watch_activity(
        &self,

        /// User ID to watch
        #[validate(uuid)]
        user_id: String,

        /// Event types to include
        #[validate(oneof = ["login", "logout", "update", "delete"])]
        event_types: Vec<String>,

        Auth(token): Auth<BearerToken>,

        #[skip]
        event_bus: &EventBus,
    ) -> impl Stream<Item = UserEvent> {
        // Implementation
    }

    /// Interactive chat with AI assistant
    ///
    /// Bidirectional communication for AI-powered user assistance.
    #[method(
        stream = Multi,
        bidir = Custom {
            request: ChatMessage,
            response: ChatReply,
        },
        responses(
            ok(AssistantEvent, "Chat session established"),
        ),
        tags = ["ai", "interactive"],
    )]
    async fn ai_chat(
        &self,

        /// Initial user message
        initial_message: String,

        /// Conversation context
        #[flatten]
        context: ConversationContext,

        #[bidir]
        channel: &BidirChannel<ChatMessage, ChatReply>,

        Auth(token): Auth<BearerToken>,

        #[skip]
        ai_service: &AIService,
    ) -> impl Stream<Item = AssistantEvent> {
        // Implementation
    }

    /// Internal helper (not exposed via RPC)
    #[method(internal = true)]
    async fn validate_user_data(&self, data: &UserData) -> Result<()> {
        // Validation logic
    }

    /// Deprecated method (still works but warns)
    #[method(http = GET)]
    #[deprecated(since = "2.0.0", note = "Use `get_user` instead")]
    async fn fetch_user(&self, id: String) -> User {
        self.get_user(id, false).await
    }
}
```

---

## Summary: New Attributes and Features

### Activation-Level Attributes

```rust
#[activation(
    namespace = "...",          // Required: activation namespace
    version = "...",            // Optional: version string
    description = "...",        // Optional: short description

    // Optional features
    children = true,            // Has child activations
    methods_enum = "...",       // Custom enum name
    schema_method = true,       // Auto-generate schema method

    // Advanced
    crate_path = "...",         // Import path
    plugin_id = "...",          // Explicit UUID
)]
```

### Method-Level Attributes

```rust
#[method(
    // HTTP configuration
    http = GET,                 // HTTP method (enum)
    path = "/users/{id}",       // URL path template

    // Streaming configuration
    stream = Multi,             // Streaming mode (Single/Multi/Infinite)

    // Documentation
    responses(
        ok(Type, "desc"),       // Success response
        error(Code, "desc"),    // Error responses
    ),
    tags = ["tag1", "tag2"],    // OpenAPI tags

    // Security
    security = bearer,          // Auth requirement

    // Performance
    cache = 60,                 // Cache TTL in seconds
    rate_limit = (100, per_minute),  // Rate limiting

    // Advanced
    internal = true,            // Not exposed via RPC
    deprecated = "...",         // Deprecation message
    custom_dispatch = true,     // Custom dispatch logic
)]
```

### Parameter-Level Attributes

```rust
async fn method(
    &self,

    // Documentation
    /// Doc comment becomes description

    // Validation
    #[validate(email)]          // Email validation
    #[validate(uuid)]           // UUID validation
    #[validate(url)]            // URL validation
    #[validate(length(min, max))]  // Length validation
    #[validate(range(min, max))]   // Numeric range
    #[validate(regex = "...")]  // Pattern matching
    #[validate(oneof = [...])]  // Enum validation
    #[validate(custom = "fn")]  // Custom validator

    // Configuration
    #[default(value)]           // Default value
    #[example("...")]           // Example for docs
    #[flatten]                  // Merge nested structure
    #[skip]                     // Exclude from schema
    #[sensitive]                // Don't log this param

    // Special parameter types
    #[path]                     // From URL path
    #[query]                    // From query string
    #[bidir]                    // Bidirectional channel

    param: Type,
) { }
```

### Type-Based Extractors

```rust
Auth(token): Auth<BearerToken>      // Authentication
RateLimit(limiter): RateLimit       // Rate limiting
Trace(span): Trace                  // Tracing context
Cache(cache): Cache                 // Cache handle
```

---

## Implementation Priority

1. **Phase 1: Core DX** (Must-have)
   - Doc comments → descriptions
   - `#[desc("...")]` on parameters
   - `#[validate(...)]` basic validators
   - `#[default(...)]` with type checking
   - `#[skip]` explicit parameter exclusion

2. **Phase 2: Rich Metadata** (Should-have)
   - `#[example("...")]` for documentation
   - `responses(...)` documentation
   - `tags = [...]` for grouping
   - Better error messages
   - Deprecation warnings

3. **Phase 3: Advanced Features** (Nice-to-have)
   - Type-based extractors (Auth, RateLimit, etc.)
   - Cache TTL configuration
   - Rate limiting attributes
   - Custom validation functions
   - OpenAPI/JSON Schema enhancements

4. **Phase 4: Compile-Time Validation** (Future)
   - Validate schemas at compile time
   - Type checking for validation rules
   - Dead code detection (unused methods)
   - Breaking change detection

---

## Next Steps

1. Prototype Phase 1 features
2. Test with real-world activations
3. Gather feedback on ergonomics
4. Iterate on syntax
5. Implement Phase 2-3 features
6. Write comprehensive documentation
7. Build migration tooling

The goal: Make Plexus macros feel as polished and thoughtful as clap, serde, and axum.