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
use TokenStream;
use quote;
use ;
/// This macro is an alias for defining HTTP controllers.
/// Defines an HTTP controller with a base path, and should be used in combination
/// with the `#[routes]` macro for route implementation.
///
/// ### Parameters
/// - `base_path`: The base path for the controller, e.g., "/api
///
/// ### Usage
/// ```rust,ignore
/// #[controller("/base_path")]
/// struct MyController {}
///
/// #[routes]
/// impl MyController {
/// #[get("/sub_path")]
/// async fn my_handler(&self) -> HttpResult {
/// Ok(JsonResponse::Ok().message("Hello from MyController"))
/// }
/// }
/// ```
/// 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 adapter type (e. g. OnRequest, OnConnect.)
/// Applies the interceptor to the current scope.
/// This macro can be used to apply an `Interceptor` to different `Adapter` types,
/// such as REST controllers or Socket.IO adapters.
/// 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
/// #[derive(Deserialize)]
/// #[config(key = "my-section")]
/// 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
///
/// Each variant must have `#[http(...)]` with one of:
///
/// **For direct responses:**
/// - `code = <u16>`: HTTP status code (required)
/// - `message = "<string>"`: Custom message (optional, defaults to canonical reason)
/// - `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)]`: Adds structured logging when the error occurs (optional)
/// - `level`: One of `trace`, `debug`, `info`, `warn`, `error`
/// - Generates `tracing::*!(...)` calls with error details
/// - Compatible with `RUST_LOG` for filtering
/// - Not allowed with `transparent` variants
///
/// ### Tracing Output
/// The generated logs include:
/// - `error_type`: The variant name as string
/// - `status_code`: The HTTP status code
/// - For unnamed variants (single field): `error = ?field` (debug format)
/// - For named variants: Each field as `field_name = ?field_value`
/// - Unit variants: Only `error_type` and `status_code`
///
/// # Example
///
/// ```rust,ignore
/// use sword::prelude::*;
/// use thiserror::Error;
///
/// #[derive(Debug, Error, HttpError)]
/// pub enum ApiError {
/// #[error("Not found")]
/// #[http(code = 404)]
/// #[tracing(info)] // Log: error_type="NotFound", status_code=404
/// NotFound,
///
/// #[error("Forbidden: requires {role}")]
/// #[http(code = 403, error = role)]
/// #[tracing(warn)] // Log: error_type="Forbidden", status_code=403, role=?role
/// Forbidden { role: String },
///
/// #[error("IO Error: {0}")]
/// #[http(code = 500)]
/// #[tracing(error)] // Log: error_type="Io", status_code=500, error=?_inner
/// Io(#[from] std::io::Error),
///
/// #[error("Auth Error: {0}")]
/// #[http(transparent)] // Delegates to other "HttpError" derivation
/// Auth(#[from] AuthError),
/// }
/// ```
/// ### 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
/// Marks a struct as a Socket.IO adapter.
/// This macro should be used in combination with the `#[on]`
/// macro for handler implementation.
///
/// ### Usage
/// ```rust,ignore
/// #[socketio_adapter("/chat")]
/// struct ChatSocket;
///
/// impl ChatSocket {
/// #[on("connection")]
/// async fn on_connect(&self, socket: SocketRef) {
/// println!("Client connected");
/// }
/// }
/// ```
/// Defines Socket.IO handlers for its associated adapter.
/// This macro should be used inside an `impl` block of a struct annotated with the `#[socketio_adapter]` macro.
///
/// ### Parameters
/// - `path`: The path for the Socket.IO endpoint, e.g., `"/socket"`
///
/// ### Usage
/// ```rust,ignore
/// #[socketio_adapter("/socket")]
/// struct SocketController;
///
/// #[handlers]
/// impl SocketController {
/// #[on_connection]
/// async fn on_connect(&self, socket: SocketRef) {
/// println!("Client connected");
/// }
///
/// #[on_message("message")]
/// async fn on_message(&self, socket: SocketRef, Data(msg): Data<String>) {
/// println!("Received: {}", msg);
/// }
///
/// #[on_disconnect]
/// async fn on_disconnect(&self, socket: SocketRef) {
/// println!("Client disconnected");
/// }
/// }
/// ```
/// 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.socket`
/// - Message data via `ctx.try_data::<T>()`
/// - Event name via `ctx.event()`
/// - Acknowledgments via `ctx.ack()`
///
/// ### Usage
/// ```rust,ignore
/// #[socketio_adapter("/chat")]
/// pub struct ChatAdapter { ... }
///
/// impl ChatAdapter {
/// #[on("connection")]
/// async fn on_connect(&self, ctx: SocketContext) {
/// println!("Client connected: {}", ctx.socket.id);
/// }
///
/// #[on("message")]
/// async fn handle_message(&self, ctx: SocketContext) {
/// let msg: String = ctx.try_data().unwrap();
/// println!("Received: {}", msg);
/// }
/// }
/// ```