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
//! [](https://summer-rs.github.io)
use TokenStream;
use DeriveInput;
/// Creates resource handler.
///
/// # Syntax
/// ```plain
/// #[route("path", method="HTTP_METHOD"[, attributes])]
/// ```
///
/// # Attributes
/// - `"path"`: Raw literal string with path for which to register handler.
/// - `method = "HTTP_METHOD"`: Registers HTTP method to provide guard for. Upper-case string,
/// "GET", "POST" for example.
///
/// # Examples
/// ```
/// # use summer_web::axum::response::IntoResponse;
/// # use summer_macros::route;
/// #[route("/test", method = "GET", method = "HEAD")]
/// async fn example() -> impl IntoResponse {
/// "hello world"
/// }
/// ```
/// Creates openapi resource handler.
///
/// # Syntax
/// ```plain
/// #[api_route("path", method="HTTP_METHOD"[, attributes])]
/// ```
///
/// # Attributes
/// - `"path"`: Raw literal string with path for which to register handler.
/// - `method = "HTTP_METHOD"`: Registers HTTP method. Upper-case string,
/// "GET", "POST" for example.
///
/// # Examples
/// ```
/// # use summer_web::axum::response::IntoResponse;
/// # use summer_macros::api_route;
/// #[api_route("/test", method = "GET", method = "HEAD")]
/// async fn example() -> impl IntoResponse {
/// "hello world"
/// }
/// ```
/// Creates resource handler.
///
/// # Syntax
/// ```plain
/// #[routes]
/// #[<method>("path", ...)]
/// #[<method>("path", ...)]
/// ...
/// ```
///
/// # Attributes
/// The `routes` macro itself has no parameters, but allows specifying the attribute macros for
/// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post).
///
/// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler).
///
/// # Examples
/// ```
/// # use summer_web::axum::response::IntoResponse;
/// # use summer_macros::routes;
/// #[routes]
/// #[get("/test")]
/// #[get("/test2")]
/// #[delete("/test")]
/// async fn example() -> impl IntoResponse {
/// "hello world"
/// }
/// ```
/// Creates openapi resource handler.
///
/// # Syntax
/// ```plain
/// #[api_routes]
/// #[<method>("path", ...)]
/// #[<method>("path", ...)]
/// ...
/// ```
///
/// # Attributes
/// The `api_routes` macro itself has no parameters, but allows specifying the attribute macros for
/// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post).
///
/// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler).
///
/// # Examples
/// ```
/// # use summer_web::axum::response::IntoResponse;
/// # use summer_macros::api_routes;
/// #[api_routes]
/// #[get("/test")]
/// #[get("/test2")]
/// #[delete("/test")]
/// async fn example() -> impl IntoResponse {
/// "hello world"
/// }
/// ```
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
method_macro!;
/// Prepends a path prefix to all handlers using routing macros inside the attached module.
///
/// # Syntax
///
/// ```
/// # use summer_macros::nest;
/// #[nest("/prefix")]
/// mod api {
/// // ...
/// }
/// ```
///
/// # Arguments
///
/// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths.
///
/// # Example
///
/// ```
/// # use summer_macros::{nest, get};
/// # use summer_web::axum::response::IntoResponse;
/// #[nest("/api")]
/// mod api {
/// # use super::*;
/// #[get("/hello")]
/// pub async fn hello() -> impl IntoResponse {
/// // this has path /api/hello
/// "Hello, world!"
/// }
/// }
/// # fn main() {}
/// ```
/// Applies middleware layers to all route handlers within a module.
///
/// # Syntax
/// ```plain
/// #[middlewares(middleware1, middleware2, ...)]
/// mod module_name {
/// // route handlers
/// }
/// ```
///
/// # Arguments
/// - `middleware1`, `middleware2`, etc. - Middleware expressions that will be applied to all routes in the module
///
/// This macro generates a router function that applies the specified middleware
/// to all route handlers defined within the module.
/// Job
///
job_macro!;
job_macro!;
job_macro!;
job_macro!;
/// Auto config
/// ```diff
/// use summer_macros::auto_config;
/// use summer_web::{WebPlugin, WebConfigurator};
/// use summer_job::{JobPlugin, JobConfigurator};
/// use summer_pubsub::{pubsub_listener, PubSubPlugin, PubSubConfigurator};
/// use summer_boot::app::App;
/// +#[auto_config(WebConfigurator, JobConfigurator, PubSubConfigurator)]
/// #[tokio::main]
/// async fn main() {
/// App::new()
/// .add_plugin(WebPlugin)
/// .add_plugin(JobPlugin)
/// - .add_router(router())
/// - .add_jobs(jobs())
/// .run()
/// .await
/// }
/// ```
///
/// stream macro
/// Configurable
/// Injectable Servcie
/// Component macro for declarative component registration
///
/// This macro allows you to register components to the summer-rs application
/// container in a declarative way, without manually implementing the Plugin trait.
///
/// # Syntax
/// ```plain
/// #[component]
/// fn create_component(
/// Config(config): Config<MyConfig>,
/// Component(dep): Component<Dependency>,
/// ) -> MyComponent {
/// MyComponent::new(config, dep)
/// }
/// Declarative component registration macro for summer-rs applications.
///
/// The `#[component]` macro automatically generates a Plugin implementation that registers
/// a component in the application. It handles dependency injection, configuration loading,
/// and proper initialization order.
///
/// # How It Works
///
/// The macro transforms a component creation function into a Plugin that:
/// 1. Extracts dependencies from function parameters
/// 2. Generates a unique Plugin name based on the return type
/// 3. Declares dependencies to ensure correct initialization order
/// 4. Registers the component in the application registry
/// 5. Automatically registers the Plugin via the `inventory` crate
///
/// # Syntax
/// ```plain
/// #[component(name = "CustomName")] // Optional custom name
/// fn create_component(
/// Config(config): Config<ConfigType>, // Configuration injection
/// Component(dep): Component<DependencyType>, // Component injection
/// ) -> ComponentType {
/// // Component creation logic
/// }
/// ```
///
/// # Attributes
/// - `name = "PluginName"` - **Optional**: Custom Plugin name. If not specified, the name
/// is automatically generated as `__Create{TypeName}Plugin`.
///
/// # Parameters
/// - `Config<T>` - Inject configuration of type `T` (must implement `Configurable`)
/// - `Component<T>` - Inject another component of type `T`
/// - Can use `#[inject("PluginName")]` attribute to specify explicit dependency
/// - Without `#[inject]`, dependency is inferred as `__Create{T}Plugin`
///
/// # Return Type
/// - Must implement `Clone + Send + Sync + 'static`
/// - Can return `Result<T, E>` for fallible initialization (will panic on error)
/// - Each component type can only be registered once
///
/// # Dependency Resolution
///
/// The macro automatically analyzes dependencies and generates a `dependencies()` method
/// that returns the list of required Plugin names. The application will initialize plugins
/// in the correct order based on these dependencies.
///
/// **Circular dependencies are not allowed** and will cause a panic at runtime.
///
/// # Examples
///
/// ## Basic Usage
/// ```rust,ignore
/// use summer::config::Configurable;
/// use summer::extractor::Config;
/// use summer_macros::component;
/// use serde::Deserialize;
///
/// #[derive(Clone, Configurable, Deserialize)]
/// #[config_prefix = "database"]
/// struct DbConfig {
/// host: String,
/// port: u16,
/// }
///
/// #[derive(Clone)]
/// struct DbConnection {
/// url: String,
/// }
///
/// #[component]
/// fn create_db_connection(
/// Config(config): Config<DbConfig>,
/// ) -> DbConnection {
/// DbConnection {
/// url: format!("{}:{}", config.host, config.port),
/// }
/// }
/// ```
///
/// ## With Dependencies
/// ```rust,ignore
/// #[derive(Clone)]
/// struct UserRepository {
/// db: DbConnection,
/// }
///
/// #[component]
/// fn create_user_repository(
/// Component(db): Component<DbConnection>,
/// ) -> UserRepository {
/// UserRepository { db }
/// }
/// ```
///
/// ## Multi-Level Dependencies
/// ```rust,ignore
/// #[derive(Clone)]
/// struct UserService {
/// repo: UserRepository,
/// }
///
/// #[component]
/// fn create_user_service(
/// Component(repo): Component<UserRepository>,
/// ) -> UserService {
/// UserService { repo }
/// }
/// ```
///
/// ## Async Initialization
/// ```rust,ignore
/// #[component]
/// async fn create_db_connection(
/// Config(config): Config<DbConfig>,
/// ) -> Result<DbConnection, anyhow::Error> {
/// let pool = sqlx::PgPool::connect(&config.url).await?;
/// Ok(DbConnection { pool })
/// }
/// ```
///
/// ## Custom Plugin Name
///
/// Use custom names when you need multiple components of the same type (NewType pattern):
/// ```rust,ignore
/// #[derive(Clone)]
/// struct PrimaryDb(DbConnection);
///
/// #[derive(Clone)]
/// struct SecondaryDb(DbConnection);
///
/// #[component(name = "PrimaryDatabase")]
/// fn create_primary_db(
/// Config(config): Config<PrimaryDbConfig>,
/// ) -> PrimaryDb {
/// PrimaryDb(DbConnection::new(&config))
/// }
///
/// #[component(name = "SecondaryDatabase")]
/// fn create_secondary_db(
/// Config(config): Config<SecondaryDbConfig>,
/// ) -> SecondaryDb {
/// SecondaryDb(DbConnection::new(&config))
/// }
/// ```
///
/// ## Explicit Dependency
///
/// Use `#[inject("PluginName")]` when the dependency name cannot be inferred:
/// ```rust,ignore
/// #[component]
/// fn create_repository(
/// #[inject("PrimaryDatabase")] Component(db): Component<PrimaryDb>,
/// ) -> UserRepository {
/// UserRepository::new(db.0)
/// }
/// ```
///
/// # Usage in Application
///
/// Components defined with `#[component]` are automatically registered when the app is built:
///
/// ```rust,ignore
/// use summer::App;
///
/// #[tokio::main]
/// async fn main() {
/// let app = App::new()
/// .build() // Auto plugins are registered automatically
/// .await
/// .expect("Failed to build app");
///
/// // Use components
/// let db = app.get_component::<DbConnection>().unwrap();
/// }
/// ```
///
/// # Best Practices
///
/// 1. **Keep component functions simple** - They should only create and configure the component
/// 2. **Use NewType pattern for multiple instances** - Wrap the same type in different structs
/// 3. **Prefer configuration over hardcoding** - Use `Config<T>` for all configurable values
/// 4. **Use `Arc<T>` for large components** - Reduces clone overhead
/// 5. **Avoid circular dependencies** - Refactor your design if you encounter them
/// 6. **Use explicit names for clarity** - When the auto-generated name is not clear enough
///
/// # Limitations
///
/// - Each component type can only be registered once (use NewType pattern for multiple instances)
/// - Circular dependencies are not supported
/// - Component types must implement `Clone + Send + Sync + 'static`
/// - Configuration types must implement `Configurable + Deserialize`
///
/// # See Also
///
/// - [`Config`](summer::extractor::Config) - Configuration injection wrapper
/// - [`Component`](summer::extractor::Component) - Component injection wrapper
/// - [`Configurable`](summer::config::Configurable) - Trait for configuration types
/// ProblemDetails derive macro
///
/// Derives the `From<T> for ProblemDetails` trait for error enums.
/// This macro automatically generates implementations for converting error variants
/// to RFC 7807 Problem Details responses.
///
/// Each variant must have a `#[status_code(code)]` attribute.
///
/// ## Supported Attributes
///
/// - `#[status_code(code)]` - **Required**: HTTP status code (e.g., 400, 404, 500)
/// - `#[problem_type("uri")]` - **Optional**: Custom problem type URI
/// - `#[title("title")]` - **Optional**: Custom problem title
/// - `#[detail("detail")]` - **Optional**: Custom problem detail message
/// - `#[instance("uri")]` - **Optional**: Problem instance URI
///
/// ## Title Compatibility
///
/// The `title` field can be automatically derived from the `#[error("...")]` attribute
/// if no explicit `#[title("...")]` is provided. This provides compatibility with
/// `thiserror::Error` and reduces duplication.
///
/// ## Basic Example
/// ```rust,ignore
/// use summer_web::ProblemDetails;
///
/// #[derive(ProblemDetails)]
/// pub enum ApiError {
/// #[status_code(400)]
/// ValidationError,
/// #[status_code(404)]
/// NotFound,
/// #[status_code(500)]
/// InternalError,
/// }
/// ```
///
/// ## Advanced Example with Custom Attributes
/// ```rust,ignore
/// #[derive(ProblemDetails)]
/// pub enum ApiError {
/// // Explicit title
/// #[status_code(400)]
/// #[title("Input Validation Failed")]
/// #[detail("The provided input data is invalid")]
/// #[error("Validation error")]
/// ValidationError,
///
/// // Title derived from error attribute
/// #[status_code(422)]
/// #[detail("Request data failed validation")]
/// #[error("Validation Failed")] // This becomes the title
/// ValidationFailed,
///
/// // Full customization
/// #[status_code(404)]
/// #[problem_type("https://api.example.com/problems/not-found")]
/// #[title("Resource Not Found")]
/// #[detail("The requested resource could not be found")]
/// #[instance("/users/123")]
/// #[error("Not found")]
/// NotFound,
/// }
/// ```
///
/// This will automatically implement:
/// - `From<T> for ProblemDetails` trait for converting to Problem Details responses
/// - `IntoResponse` trait for direct use in Axum handlers
/// - OpenAPI integration for documentation generation
/// `#[cache]` - Transparent Redis-based caching for async functions.
///
/// This macro wraps an async function to automatically cache its result
/// in Redis. It checks for a cached value before executing the function.
/// If a cached result is found, it is deserialized and returned directly.
/// Otherwise, the function runs normally and its result is stored in Redis.
///
/// # Syntax
/// ```plain
/// #[cache("key_pattern", expire = <seconds>, condition = <bool_expr>, unless = <bool_expr>)]
/// ```
///
/// # Attributes
/// - `"key_pattern"` (**required**):
/// A format string used to generate the cache key. Function arguments can be interpolated using standard `format!` syntax.
/// - `expire = <integer>` (**optional**):
/// The number of seconds before the cached value expires. If omitted, the key will be stored without expiration.
/// - `condition = <expression>` (**optional**):
/// A boolean expression evaluated **before** executing the function.
/// If this evaluates to `false`, caching is completely bypassed — no lookup and no insertion.
/// The expression can access function parameters directly.
/// - `unless = <expression>` (**optional**):
/// A boolean expression evaluated **after** executing the function.
/// If this evaluates to `true`, the result will **not** be written to the cache.
/// The expression can access both parameters and a `result` variable (the return value).
/// NOTE: If your function returns Result<T, E>, the `result` variable in unless refers to the inner Ok value (T), not the entire Result.
/// This allows you to write expressions like result.is_none() for Result<Option<_>, _> functions.
///
/// # Function Requirements
/// - Must be an `async fn`
/// - Can return either a `Result<T, E>` or a plain value `T`
/// - The return type must implement `serde::Serialize` and `serde::Deserialize`
/// - Generics, attributes, and visibility will be preserved
///
/// # Example
/// ```rust
/// use summer_macros::cache;
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct User {
/// id: u64,
/// name: String,
/// }
///
/// struct MyError;
///
/// #[cache("user:{user_id}", expire = 600, condition = user_id % 2 == 0, unless = result.is_none())]
/// async fn get_user(user_id: u64) -> Result<Option<User>, MyError> {
/// // Fetch user from database
/// unimplemented!("do something")
/// }
/// ```
/// Marks a function as a SocketIO connection handler
///
/// # Examples
/// ```
/// # use summer_web::socketioxide::extract::{SocketRef, Data};
/// # use summer_web::rmpv::Value;
/// # use summer_macros::on_connection;
/// #[on_connection]
/// async fn on_connection(socket: SocketRef, Data(data): Data<Value>) {
/// // Handle connection
/// }
/// ```
/// Marks a function as a SocketIO disconnection handler
///
/// # Examples
/// ```
/// # use summer_web::socketioxide::extract::SocketRef;
/// # use summer_macros::on_disconnect;
/// #[on_disconnect]
/// async fn on_disconnect(socket: SocketRef) {
/// // Handle disconnection
/// }
/// ```
/// Marks a function as a SocketIO message subscription handler
///
/// # Examples
/// ```
/// # use summer_web::socketioxide::extract::{SocketRef, Data};
/// # use summer_macros::subscribe_message;
/// # use summer_web::rmpv::Value;
/// #[subscribe_message("message")]
/// async fn message(socket: SocketRef, Data(data): Data<Value>) {
/// // Handle message
/// }
/// ```
/// Marks a function as a SocketIO fallback handler
///
/// # Examples
/// ```
/// # use summer_web::socketioxide::extract::{SocketRef, Data};
/// # use summer_web::rmpv::Value;
/// # use summer_macros::on_fallback;
/// #[on_fallback]
/// async fn on_fallback(socket: SocketRef, Data(data): Data<Value>) {
/// // Handle fallback
/// }
/// ```