-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhandler.rs
More file actions
583 lines (525 loc) · 17.6 KB
/
handler.rs
File metadata and controls
583 lines (525 loc) · 17.6 KB
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
//! Handler trait and utilities
//!
//! This module provides the [`Handler`] trait and related types for defining
//! HTTP request handlers in RustAPI.
//!
//! # Handler Functions
//!
//! Any async function that takes extractors as parameters and returns a type
//! implementing [`IntoResponse`] can be used as a handler:
//!
//! ```rust,ignore
//! use rustapi_core::{Json, Path, IntoResponse};
//! use serde::{Deserialize, Serialize};
//!
//! // No parameters
//! async fn hello() -> &'static str {
//! "Hello, World!"
//! }
//!
//! // With extractors
//! async fn get_user(Path(id): Path<i64>) -> Json<User> {
//! Json(User { id, name: "Alice".to_string() })
//! }
//!
//! // Multiple extractors (up to 5 supported)
//! async fn create_user(
//! State(db): State<DbPool>,
//! Json(body): Json<CreateUser>,
//! ) -> Result<Created<User>, ApiError> {
//! // ...
//! }
//! ```
//!
//! # Route Helpers
//!
//! The module provides helper functions for creating routes with metadata:
//!
//! ```rust,ignore
//! use rustapi_core::handler::{get_route, post_route};
//!
//! let get = get_route("/users", list_users);
//! let post = post_route("/users", create_user);
//! ```
//!
//! # Macro-Based Routing
//!
//! For more ergonomic routing, use the `#[rustapi::get]`, `#[rustapi::post]`, etc.
//! macros from `rustapi-macros`:
//!
//! ```rust,ignore
//! #[rustapi::get("/users/{id}")]
//! async fn get_user(Path(id): Path<i64>) -> Json<User> {
//! // ...
//! }
//! ```
use crate::extract::FromRequest;
use crate::request::Request;
use crate::response::{IntoResponse, Response};
use rustapi_openapi::{Operation, OperationModifier, ResponseModifier};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
mod sealed {
pub trait Sealed {}
impl<T> Sealed for T where T: Clone + Send + Sync + Sized + 'static {}
}
/// Trait representing an async handler function
pub trait Handler<T>: sealed::Sealed + Clone + Send + Sync + Sized + 'static {
/// The response type
type Future: Future<Output = Response> + Send + 'static;
/// Call the handler with the request
fn call(self, req: Request) -> Self::Future;
/// Update the OpenAPI operation
fn update_operation(op: &mut Operation);
/// Register any OpenAPI components referenced by this handler.
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec);
}
/// Wrapper to convert a Handler into a tower Service
pub struct HandlerService<H, T> {
handler: H,
_marker: PhantomData<fn() -> T>,
}
impl<H, T> HandlerService<H, T> {
pub fn new(handler: H) -> Self {
Self {
handler,
_marker: PhantomData,
}
}
}
impl<H: Clone, T> Clone for HandlerService<H, T> {
fn clone(&self) -> Self {
Self {
handler: self.handler.clone(),
_marker: PhantomData,
}
}
}
// Implement Handler for async functions with 0-6 extractors
// 0 args
impl<F, Fut, Res> Handler<()> for F
where
F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, _req: Request) -> Self::Future {
Box::pin(async move { self().await.into_response() })
}
fn update_operation(op: &mut Operation) {
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
Res::register_components(spec);
}
}
// 1 arg
impl<F, Fut, Res, T1> Handler<(T1,)> for F
where
F: FnOnce(T1) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
T1: FromRequest + OperationModifier + Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, mut req: Request) -> Self::Future {
Box::pin(async move {
let t1 = match T1::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
self(t1).await.into_response()
})
}
fn update_operation(op: &mut Operation) {
T1::update_operation(op);
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
T1::register_components(spec);
Res::register_components(spec);
}
}
// 2 args
impl<F, Fut, Res, T1, T2> Handler<(T1, T2)> for F
where
F: FnOnce(T1, T2) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
T1: FromRequest + OperationModifier + Send + 'static,
T2: FromRequest + OperationModifier + Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, mut req: Request) -> Self::Future {
Box::pin(async move {
let t1 = match T1::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t2 = match T2::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
self(t1, t2).await.into_response()
})
}
fn update_operation(op: &mut Operation) {
T1::update_operation(op);
T2::update_operation(op);
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
T1::register_components(spec);
T2::register_components(spec);
Res::register_components(spec);
}
}
// 3 args
impl<F, Fut, Res, T1, T2, T3> Handler<(T1, T2, T3)> for F
where
F: FnOnce(T1, T2, T3) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
T1: FromRequest + OperationModifier + Send + 'static,
T2: FromRequest + OperationModifier + Send + 'static,
T3: FromRequest + OperationModifier + Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, mut req: Request) -> Self::Future {
Box::pin(async move {
let t1 = match T1::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t2 = match T2::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t3 = match T3::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
self(t1, t2, t3).await.into_response()
})
}
fn update_operation(op: &mut Operation) {
T1::update_operation(op);
T2::update_operation(op);
T3::update_operation(op);
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
T1::register_components(spec);
T2::register_components(spec);
T3::register_components(spec);
Res::register_components(spec);
}
}
// 4 args
impl<F, Fut, Res, T1, T2, T3, T4> Handler<(T1, T2, T3, T4)> for F
where
F: FnOnce(T1, T2, T3, T4) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
T1: FromRequest + OperationModifier + Send + 'static,
T2: FromRequest + OperationModifier + Send + 'static,
T3: FromRequest + OperationModifier + Send + 'static,
T4: FromRequest + OperationModifier + Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, mut req: Request) -> Self::Future {
Box::pin(async move {
let t1 = match T1::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t2 = match T2::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t3 = match T3::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t4 = match T4::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
self(t1, t2, t3, t4).await.into_response()
})
}
fn update_operation(op: &mut Operation) {
T1::update_operation(op);
T2::update_operation(op);
T3::update_operation(op);
T4::update_operation(op);
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
T1::register_components(spec);
T2::register_components(spec);
T3::register_components(spec);
T4::register_components(spec);
Res::register_components(spec);
}
}
// 5 args
impl<F, Fut, Res, T1, T2, T3, T4, T5> Handler<(T1, T2, T3, T4, T5)> for F
where
F: FnOnce(T1, T2, T3, T4, T5) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send + 'static,
Res: IntoResponse + ResponseModifier,
T1: FromRequest + OperationModifier + Send + 'static,
T2: FromRequest + OperationModifier + Send + 'static,
T3: FromRequest + OperationModifier + Send + 'static,
T4: FromRequest + OperationModifier + Send + 'static,
T5: FromRequest + OperationModifier + Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, mut req: Request) -> Self::Future {
Box::pin(async move {
let t1 = match T1::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t2 = match T2::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t3 = match T3::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t4 = match T4::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let t5 = match T5::from_request(&mut req).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
self(t1, t2, t3, t4, t5).await.into_response()
})
}
fn update_operation(op: &mut Operation) {
T1::update_operation(op);
T2::update_operation(op);
T3::update_operation(op);
T4::update_operation(op);
T5::update_operation(op);
Res::update_response(op);
}
fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
T1::register_components(spec);
T2::register_components(spec);
T3::register_components(spec);
T4::register_components(spec);
T5::register_components(spec);
Res::register_components(spec);
}
}
// Type-erased handler for storage in router
pub(crate) type BoxedHandler =
std::sync::Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send>> + Send + Sync>;
/// Create a boxed handler from any Handler
pub(crate) fn into_boxed_handler<H, T>(handler: H) -> BoxedHandler
where
H: Handler<T>,
T: 'static,
{
std::sync::Arc::new(move |req| {
let handler = handler.clone();
Box::pin(async move { handler.call(req).await })
})
}
/// Trait for handlers with route metadata (generated by `#[rustapi::get]`, etc.)
///
/// This trait provides the path and method information for a handler,
/// allowing `.mount(handler)` to automatically register the route.
pub trait RouteHandler<T>: Handler<T> {
/// The path pattern for this route (e.g., "/users/{id}")
const PATH: &'static str;
/// The HTTP method for this route (e.g., "GET")
const METHOD: &'static str;
}
/// Represents a route definition that can be registered with .mount()
pub struct Route {
pub(crate) path: &'static str,
pub(crate) method: &'static str,
pub(crate) handler: BoxedHandler,
pub(crate) operation: Operation,
pub(crate) component_registrar: fn(&mut rustapi_openapi::OpenApiSpec),
/// Custom parameter schemas for OpenAPI (param_name -> schema_type)
/// Supported types: "uuid", "integer", "string", "boolean", "number"
pub(crate) param_schemas: std::collections::BTreeMap<String, String>,
/// Custom error responses for OpenAPI (status_code -> description)
pub(crate) error_responses: Vec<(u16, String)>,
}
impl Route {
/// Create a new route from a handler with path and method
pub fn new<H, T>(path: &'static str, method: &'static str, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut operation = Operation::new();
H::update_operation(&mut operation);
Self {
path,
method,
handler: into_boxed_handler(handler),
operation,
component_registrar: <H as Handler<T>>::register_components,
param_schemas: std::collections::BTreeMap::new(),
error_responses: Vec::new(),
}
}
/// Set the operation summary
pub fn summary(mut self, summary: impl Into<String>) -> Self {
self.operation = self.operation.summary(summary);
self
}
/// Set the operation description
pub fn description(mut self, description: impl Into<String>) -> Self {
self.operation = self.operation.description(description);
self
}
/// Add a tag to the operation
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.operation.tags.push(tag.into());
self
}
/// Get the route path
pub fn path(&self) -> &str {
self.path
}
/// Get the route method
pub fn method(&self) -> &str {
self.method
}
/// Set a custom OpenAPI schema type for a path parameter
///
/// This is useful for overriding the auto-inferred type, e.g., when
/// a parameter named `id` is actually a UUID instead of an integer.
///
/// # Supported schema types
/// - `"uuid"` - String with UUID format
/// - `"integer"` or `"int"` - Integer with int64 format
/// - `"string"` - Plain string
/// - `"boolean"` or `"bool"` - Boolean
/// - `"number"` - Number (float)
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users/{id}")]
/// async fn get_user(Path(id): Path<Uuid>) -> Json<User> {
/// // ...
/// }
///
/// // In route registration:
/// get_route("/users/{id}", get_user).param("id", "uuid")
/// ```
pub fn param(mut self, name: impl Into<String>, schema_type: impl Into<String>) -> Self {
self.param_schemas.insert(name.into(), schema_type.into());
self
}
/// Get the custom parameter schemas
pub fn param_schemas(&self) -> &std::collections::BTreeMap<String, String> {
&self.param_schemas
}
/// Add a typed error response to the OpenAPI specification for this route
///
/// This adds an error response entry to the operation's responses map,
/// referencing the standard `ErrorSchema` component.
///
/// # Arguments
///
/// * `status` - HTTP status code (e.g., 404, 403, 409)
/// * `description` - Human-readable description of when this error occurs
///
/// # Example
///
/// ```rust,ignore
/// get_route("/users/{id}", get_user)
/// .error_response(404, "User not found")
/// .error_response(403, "Forbidden - insufficient permissions")
/// ```
pub fn error_response(mut self, status: u16, description: impl Into<String>) -> Self {
let desc = description.into();
self.error_responses.push((status, desc.clone()));
// Also add directly to the operation's responses
let mut content = std::collections::BTreeMap::new();
content.insert(
"application/json".to_string(),
rustapi_openapi::MediaType {
schema: Some(rustapi_openapi::SchemaRef::Ref {
reference: "#/components/schemas/ErrorSchema".to_string(),
}),
example: None,
},
);
self.operation.responses.insert(
status.to_string(),
rustapi_openapi::ResponseSpec {
description: desc,
content,
headers: std::collections::BTreeMap::new(),
},
);
self
}
/// Get the custom error responses
pub fn error_responses(&self) -> &[(u16, String)] {
&self.error_responses
}
}
/// Helper macro to create a Route from a handler with RouteHandler trait
#[macro_export]
macro_rules! route {
($handler:ident) => {{
$crate::Route::new($handler::PATH, $handler::METHOD, $handler)
}};
}
/// Create a GET route
pub fn get_route<H, T>(path: &'static str, handler: H) -> Route
where
H: Handler<T>,
T: 'static,
{
Route::new(path, "GET", handler)
}
/// Create a POST route
pub fn post_route<H, T>(path: &'static str, handler: H) -> Route
where
H: Handler<T>,
T: 'static,
{
Route::new(path, "POST", handler)
}
/// Create a PUT route
pub fn put_route<H, T>(path: &'static str, handler: H) -> Route
where
H: Handler<T>,
T: 'static,
{
Route::new(path, "PUT", handler)
}
/// Create a PATCH route
pub fn patch_route<H, T>(path: &'static str, handler: H) -> Route
where
H: Handler<T>,
T: 'static,
{
Route::new(path, "PATCH", handler)
}
/// Create a DELETE route
pub fn delete_route<H, T>(path: &'static str, handler: H) -> Route
where
H: Handler<T>,
T: 'static,
{
Route::new(path, "DELETE", handler)
}