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
use TokenStream;
use quote;
use ;
/// Defines a Sword controller.
/// Route handlers are declared directly inside the `impl` block using method attributes
/// such as `#[get]`, `#[post]`, `#[put]`, `#[patch]`, `#[delete]`, `#[head]`, `#[options]`, `#[trace]`, and `#[connect]`.
///
/// ### Parameters
/// - `kind`: Controller kind. Use `Controller::Web`, `Controller::SocketIo`, `Controller::Grpc`, or `Controller::EventHandler`.
/// - `path`: Required when `kind = Controller::Web`.
/// - `namespace`: Required when `kind = Controller::SocketIo`.
/// - `service`: Required when `kind = Controller::Grpc`.
/// - `source`: Required when `kind = Controller::EventHandler`. Use `EventSource::Memory`.
///
/// ### Usage
/// ```rust,ignore
/// #[controller(kind = Controller::Web, path = "/base_path")]
/// struct MyController {}
///
/// impl MyController {
/// #[get("/sub_path")]
/// async fn my_handler(&self) -> WebResult {
/// Ok(JsonResponse::Ok().message("Hello from MyController"))
/// }
/// }
/// ```
///
/// ```rust,ignore
/// #[controller(kind = Controller::SocketIo, namespace = "/chat")]
/// struct ChatController;
///
/// impl ChatController {
/// #[on("connection")]
/// async fn on_connect(&self, _ctx: SocketContext) {}
/// }
/// ```
/// Derive macro for creating interceptors.
///
/// Generates implementations for the `Interceptor` trait.
///
/// # Usage
/// ```rust,ignore
/// use sword::prelude::*;
///
/// #[derive(Interceptor)]
/// struct MyInterceptor;
///
/// // then implement some Interceptor trait variants
/// // depending on the controller kind (e.g. OnRequest, OnConnect.)
/// ```
/// Marks a route or controller with one or more interceptors.
/// This macro can be used to apply an `Interceptor` to different controller kinds,
/// such as web controllers or Socket.IO controllers.
/// Defines a configuration struct for the application.
/// This macro generates the necessary code to deserialize the struct from
/// the configuration toml file.
///
/// The struct must derive `Deserialize` from `serde`.
///
/// ### Parameters
/// - `key`: The key in the configuration file where the struct is located.
///
/// ### Usage
///
/// ```rust,ignore
/// #[config(key = "my-section")]
/// #[derive(Debug, Deserialize)]
/// struct MyConfig {
/// my_key: String,
/// }
/// ```
/// Marks a struct as injectable.
///
/// This macro generates the necessary code to register the struct
/// in the dependency injection container. It can be used with or without
/// parameters.
///
/// ### Parameters
///
/// - `kind`: (Optional) Specifies the kind of injectable.
/// It can be either `provider` or `component`.
///
/// `provider`: The struct that has to be instantiated manually and
/// registered in the container. The struct will be treated as a singleton by default.
///
/// `component`: The struct will be instantiated automatically by the container
/// based on its dependencies. It's also treated as a singleton by default.
///
/// By default, if no kind is provided, it will be treated as `component`.
///
/// - `no_derive_clone`: (Optional) If provided, the struct will not derive the `Clone` automatically.
/// By default, the struct will derive `Clone` if all its fields implement `Clone`.
///
/// ### Usage of `#[injectable]` without parameters (same as #[injectable(component)])
///
/// ```rust,ignore
/// #[injectable]
/// pub struct TaskRepository {
/// db: Database,
/// }
///
/// impl TaskRepository {
/// pub async fn create(&self, task: Value) {
/// self.db.insert("tasks", task).await;
/// }
///
/// pub async fn find_all(&self) -> Option<Vec<Value>> {
/// self.db.get_all("tasks").await
/// }
/// }
/// ```
///
/// ### Usage of `#[injectable(provider)]` with parameters
///
/// ```rust,ignore
/// #[injectable(provider)]
/// pub struct Database {
/// db: Store,
/// }
///
/// impl Database {
/// pub async fn new(db_conf: DatabaseConfig) -> Self {
/// let db = Arc::new(RwLock::new(HashMap::new()));
///
/// db.write().await.insert(db_conf.collection_name, Vec::new());
///
/// Self { db }
/// }
///
/// pub async fn insert(&self, table: &'static str, record: Value) {
/// let mut db = self.db.write().await;
///
/// if let Some(table_data) = db.get_mut(table) {
/// table_data.push(record);
/// }
/// }
///
/// pub async fn get_all(&self, table: &'static str) -> Option<Vec<Value>> {
/// let db = self.db.read().await;
///
/// db.get(table).cloned()
/// }
/// }
/// ```
/// Derive macro for HTTP error enums.
///
/// Generates implementations for:
/// - `From<Self> for JsonResponse` - Converts error to JSON response
/// - `IntoResponse` - Allows returning error directly from handlers
///
/// **Note**: Use with `thiserror::Error` for `Display`, `Error`, and `#[from]`.
///
/// # Attributes
///
/// Enum-level defaults can be declared with `#[http_error(...)]` and overridden per
/// variant with `#[http(...)]`.
///
/// **For direct responses:**
/// - `code = <u16>`: HTTP status code (required)
/// - `message = "<string>"`: Static client message (optional)
/// - `message = <field>`: Uses a named field as the client message (optional)
/// - `error = <field>`: Single error field to include (optional, named fields only)
/// - `errors = <field>`: Multiple errors field to include (optional, named fields only)
///
/// **For delegation:**
/// - `transparent`: Delegate to inner type's `From<T> for Json` (for wrapping other `HttpError` types)
///
/// **Tracing:**
/// - `tracing = <level>` inside `#[http_error(...)]` or `#[http(...)]`
/// - `#[tracing(level)]`: Backward-compatible shorthand at variant level
/// - `level`: One of `trace`, `debug`, `info`, `warn`, `error`
/// - Uses the internal `thiserror::Error` display for the `error` log field
/// - Logs variant fields as structured tracing fields when available
/// - Compatible with `RUST_LOG` for filtering
/// - Not allowed with `transparent` variants
///
/// ### Tracing Output
/// The generated logs include:
/// - `error`: The internal `thiserror` display string
/// - `error_type`: The variant name as string
/// - `status_code`: The HTTP status code
/// - For named variants: Each field as `field_name = ?field_value`
/// - For unnamed variants (single field): `inner = ?field`
/// - Unit variants: `error`, `error_type`, and `status_code`
///
/// # Example
///
/// ```rust,ignore
/// use sword::prelude::*;
/// use thiserror::Error;
///
/// #[derive(Debug, Error, HttpError)]
/// #[http_error(code = 500, tracing = error, message = "Internal server error")]
/// pub enum ApiError {
/// #[error("Not found")]
/// #[http(code = 404, message = "Not found", tracing = info)]
/// NotFound,
///
/// #[error("Conflict on field {field}: {value}")]
/// #[http(code = 409, message = client_message, error = detail)]
/// Conflict {
/// client_message: String,
/// field: String,
/// value: String,
/// detail: serde_json::Value,
/// },
///
/// #[error("IO Error: {0}")]
/// Io(#[from] std::io::Error),
///
/// #[error("Auth Error: {0}")]
/// #[http(transparent)] // Delegates to other "HttpError" derivation
/// Auth(#[from] AuthError),
/// }
/// ```
/// Derive macro for gRPC error enums.
///
/// Generates:
/// - `From<Self> for tonic::Status`
///
/// Enum-level defaults can be declared with `#[grpc_error(...)]` and overridden per
/// variant with `#[grpc(...)]`.
///
/// Supported attributes:
/// - `code = "invalid_argument"`
/// - `message = "custom text"`
/// - `message = field_name`
/// - `transparent` (variant-only)
/// - `tracing = <level>` inside `#[grpc_error(...)]` or `#[grpc(...)]`
/// - `#[tracing(level)]`: backward-compatible shorthand at variant level
///
/// gRPC code values accepted by `#[grpc(code = "...")]`:
///
/// - `ok`
/// - `cancelled`
/// - `unknown`
/// - `invalid_argument`
/// - `deadline_exceeded`
/// - `not_found`
/// - `already_exists`
/// - `permission_denied`
/// - `resource_exhausted`
/// - `failed_precondition`
/// - `aborted`
/// - `out_of_range`
/// - `unimplemented`
/// - `internal`
/// - `unavailable`
/// - `data_loss`
/// - `unauthenticated`
///
/// # Example
///
/// ```rust,ignore
/// use sword::prelude::*;
/// use thiserror::Error;
///
/// #[derive(Debug, Error, GrpcError)]
/// #[grpc_error(code = "internal", tracing = error)]
/// enum UserError {
/// #[grpc(code = "not_found", tracing = info)]
/// #[error("User not found: {id}")]
/// NotFound { id: String },
///
/// #[grpc(code = "invalid_argument", message = client_message)]
/// #[error("Validation error: {internal}")]
/// Validation {
/// client_message: String,
/// internal: String,
/// },
///
/// #[grpc(transparent)]
/// #[error("Database error: {0}")]
/// Database(#[from] anyhow::Error),
/// }
/// ```
/// ### This is just a re-export of `tokio::main` to simplify the initial setup of
/// ### Sword, you can use your own version of tokio adding it to your
/// ### `Cargo.toml`, we are providing this initial base by default
///
/// ---
///
/// Marks async function to be executed by the selected runtime. This macro
/// helps set up a `Runtime` without requiring the user to use
/// [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.Builder.html) directly.
///
/// Note: This macro is designed to be simplistic and targets applications that
/// do not require a complex setup. If the provided functionality is not
/// sufficient, you may be interested in using
/// [Builder](../tokio/runtime/struct.Builder.html), which provides a more
/// powerful interface.
///
/// Note: This macro can be used on any function and not just the `main`
/// function. Using it on a non-main function makes the function behave as if it
/// was synchronous by starting a new runtime each time it is called. If the
/// function is called often, it is preferable to create the runtime using the
/// runtime builder so the runtime can be reused across calls.
///
/// # Non-worker async function
///
/// Note that the async function marked with this macro does not run as a
/// worker. The expectation is that other tasks are spawned by the function here.
/// Awaiting on other futures from the function provided here will not
/// perform as fast as those spawned as workers.
///
/// # Multi-threaded runtime
///
/// To use the multi-threaded runtime, the macro can be configured using
///
/// ```rust,ignore
/// #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
/// # async fn main() {}
/// ```
///
/// The `worker_threads` option configures the number of worker threads, and
/// defaults to the number of cpus on the system. This is the default flavor.
///
/// Note: The multi-threaded runtime requires the `rt-multi-thread` feature
/// flag.
///
/// # Current thread runtime
///
/// To use the single-threaded runtime known as the `current_thread` runtime,
/// the macro can be configured using
///
/// ```rust,ignore
/// #[tokio::main(flavor = "current_thread")]
/// # async fn main() {}
/// ```
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using the multi-thread runtime
///
/// ```ignore
/// #[tokio::main]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```ignore
/// fn main() {
/// tokio::runtime::Builder::new_multi_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Using current thread runtime
///
/// The basic scheduler is single-threaded.
///
/// ```ignore
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```ignore
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Set number of worker threads
///
/// ```ignore
/// #[tokio::main(worker_threads = 2)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```ignore
/// fn main() {
/// tokio::runtime::Builder::new_multi_thread()
/// .worker_threads(2)
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Configure the runtime to start with time paused
///
/// ```ignore
/// #[tokio::main(flavor = "current_thread", start_paused = true)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```ignore
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .start_paused(true)
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// Note that `start_paused` requires the `test-util` feature to be enabled.
///
/// ### Rename package
///
/// ```ignore
/// use tokio as tokio1;
///
/// #[tokio1::main(crate = "tokio1")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```ignore
/// use tokio as tokio1;
///
/// fn main() {
/// tokio1::runtime::Builder::new_multi_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Configure unhandled panic behavior
///
/// Available options are `shutdown_runtime` and `ignore`. For more details, see
/// [`Builder::unhandled_panic`].
///
/// This option is only compatible with the `current_thread` runtime.
///
/// ```no_run, ignore
/// # #![allow(unknown_lints, unexpected_cfgs)]
/// #[cfg(tokio_unstable)]
/// #[tokio::main(flavor = "current_thread", unhandled_panic = "shutdown_runtime")]
/// async fn main() {
/// let _ = tokio::spawn(async {
/// panic!("This panic will shutdown the runtime.");
/// }).await;
/// }
/// # #[cfg(not(tokio_unstable))]
/// # fn main() { }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```no_run, ignore
/// # #![allow(unknown_lints, unexpected_cfgs)]
/// #[cfg(tokio_unstable)]
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap()
/// .block_on(async {
/// let _ = tokio::spawn(async {
/// panic!("This panic will shutdown the runtime.");
/// }).await;
/// })
/// }
/// # #[cfg(not(tokio_unstable))]
/// # fn main() { }
/// ```
///
/// **Note**: This option depends on Tokio's [unstable API][unstable]. See [the
/// documentation on unstable features][unstable] for details on how to enable
/// Tokio's unstable features.
///
/// [`Builder::unhandled_panic`]: ../tokio/runtime/struct.Builder.html#method.unhandled_panic
/// [unstable]: ../tokio/index.html#unstable-features
/// Defines an event struct for use with the event queue.
///
/// Generates the `Event` trait implementation and derives `Clone`.
///
/// # Example
///
/// ```rust,ignore
/// #[event(key = "mail.send.failed")]
/// struct MailFailedEvent {
/// to: String,
/// error: String,
/// }
/// ```
/// Registers an event handler method for an `EventHandler` controller.
///
/// The attribute takes the full event key as argument, which must match
/// the `key` of the event being published via `EventPublisher`.
///
/// # Example
///
/// ```rust,ignore
/// #[event(key = "mail.send.failed")]
/// struct MailFailedEvent {
/// to: String,
/// error: String,
/// }
///
/// #[controller(kind = Controller::EventHandler, source = EventSource::Memory)]
/// struct MailHandler {
/// mailer: Arc<Mailer>,
/// }
///
/// impl MailHandler {
/// #[handle("mail.send.failed")]
/// async fn on_failed(&self, event: MailFailedEvent) -> Result<()> {
/// self.mailer.resend(&event.to).await?;
/// Ok(())
/// }
/// }
/// ```
/// Unified handler attribute for Socket.IO events.
///
/// ### Event Types
/// - `#[on("connection")]` - Called when a client connects
/// - `#[on("disconnection")]` - Called when a client disconnects
/// - `#[on("fallback")]` - Called for unhandled events
/// - `#[on("custom_event")]` - Called for custom event names
///
/// ### Parameters
/// All handlers receive `&self` and `ctx: SocketContext` which provides access to:
/// - Socket operations via `ctx`
/// - Message data via `ctx.try_data::<T>()`
/// - Event name via `ctx.event()`
/// - Acknowledgments via `ctx.ack()`
///
/// ### Usage
/// ```rust,ignore
/// #[controller(kind = Controller::SocketIo, namespace = "/chat")]
/// pub struct ChatController { ... }
///
/// impl ChatController {
/// #[on("connection")]
/// async fn on_connect(&self, ctx: SocketContext) {
/// println!("Client connected: {}", ctx.id());
/// }
///
/// #[on("message")]
/// async fn handle_message(&self, ctx: SocketContext) {
/// let msg: String = ctx.try_data().unwrap();
/// println!("Received: {}", msg);
/// }
/// }
/// ```