-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.rs
More file actions
2611 lines (2312 loc) · 88.9 KB
/
app.rs
File metadata and controls
2611 lines (2312 loc) · 88.9 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
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! RustApi application builder
use crate::error::Result;
use crate::events::LifecycleHooks;
use crate::interceptor::{InterceptorChain, RequestInterceptor, ResponseInterceptor};
use crate::middleware::{BodyLimitLayer, LayerStack, MiddlewareLayer, DEFAULT_BODY_LIMIT};
use crate::response::IntoResponse;
use crate::router::{MethodRouter, Router};
use crate::server::Server;
use std::collections::BTreeMap;
use std::future::Future;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
/// Main application builder for RustAPI
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// RustApi::new()
/// .state(AppState::new())
/// .route("/", get(hello))
/// .route("/users/{id}", get(get_user))
/// .run("127.0.0.1:8080")
/// .await
/// }
/// ```
pub struct RustApi {
router: Router,
openapi_spec: rustapi_openapi::OpenApiSpec,
layers: LayerStack,
body_limit: Option<usize>,
interceptors: InterceptorChain,
lifecycle_hooks: LifecycleHooks,
hot_reload: bool,
#[cfg(feature = "http3")]
http3_config: Option<crate::http3::Http3Config>,
health_check: Option<crate::health::HealthCheck>,
health_endpoint_config: Option<crate::health::HealthEndpointConfig>,
status_config: Option<crate::status::StatusConfig>,
}
/// Configuration for RustAPI's built-in production baseline preset.
///
/// This preset bundles together the most common foundation pieces for a
/// production HTTP service:
/// - request IDs on every response
/// - structured tracing spans with service metadata
/// - standard `/health`, `/ready`, and `/live` probes
#[derive(Debug, Clone)]
pub struct ProductionDefaultsConfig {
service_name: String,
version: Option<String>,
tracing_level: tracing::Level,
health_endpoint_config: Option<crate::health::HealthEndpointConfig>,
enable_request_id: bool,
enable_tracing: bool,
enable_health_endpoints: bool,
}
impl ProductionDefaultsConfig {
/// Create a new production baseline configuration.
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into(),
version: None,
tracing_level: tracing::Level::INFO,
health_endpoint_config: None,
enable_request_id: true,
enable_tracing: true,
enable_health_endpoints: true,
}
}
/// Annotate tracing spans and default health payloads with an application version.
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
/// Set the tracing log level used by the preset tracing layer.
pub fn tracing_level(mut self, level: tracing::Level) -> Self {
self.tracing_level = level;
self
}
/// Override the default health endpoint paths.
pub fn health_endpoint_config(mut self, config: crate::health::HealthEndpointConfig) -> Self {
self.health_endpoint_config = Some(config);
self
}
/// Enable or disable request ID propagation.
pub fn request_id(mut self, enabled: bool) -> Self {
self.enable_request_id = enabled;
self
}
/// Enable or disable structured tracing middleware.
pub fn tracing(mut self, enabled: bool) -> Self {
self.enable_tracing = enabled;
self
}
/// Enable or disable built-in health endpoints.
pub fn health_endpoints(mut self, enabled: bool) -> Self {
self.enable_health_endpoints = enabled;
self
}
}
impl RustApi {
/// Create a new RustAPI application
pub fn new() -> Self {
// Initialize tracing if not already done
let _ = tracing_subscriber::registry()
.with(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,rustapi=debug")),
)
.with(tracing_subscriber::fmt::layer())
.try_init();
Self {
router: Router::new(),
openapi_spec: rustapi_openapi::OpenApiSpec::new("RustAPI Application", "1.0.0")
.register::<rustapi_openapi::ErrorSchema>()
.register::<rustapi_openapi::ErrorBodySchema>()
.register::<rustapi_openapi::ValidationErrorSchema>()
.register::<rustapi_openapi::ValidationErrorBodySchema>()
.register::<rustapi_openapi::FieldErrorSchema>(),
layers: LayerStack::new(),
body_limit: Some(DEFAULT_BODY_LIMIT), // Default 1MB limit
interceptors: InterceptorChain::new(),
lifecycle_hooks: LifecycleHooks::new(),
hot_reload: false,
#[cfg(feature = "http3")]
http3_config: None,
health_check: None,
health_endpoint_config: None,
status_config: None,
}
}
/// Create a zero-config RustAPI application.
///
/// All routes decorated with `#[rustapi::get]`, `#[rustapi::post]`, etc.
/// are automatically registered. Swagger UI is enabled at `/docs` by default.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi::get("/users")]
/// async fn list_users() -> Json<Vec<User>> {
/// Json(vec![])
/// }
///
/// #[rustapi::main]
/// async fn main() -> Result<()> {
/// // Zero config - routes are auto-registered!
/// RustApi::auto()
/// .run("0.0.0.0:8080")
/// .await
/// }
/// ```
#[cfg(feature = "swagger-ui")]
pub fn auto() -> Self {
// Build app with grouped auto-routes and auto-schemas, then enable docs.
Self::new().mount_auto_routes_grouped().docs("/docs")
}
/// Create a zero-config RustAPI application (without swagger-ui feature).
///
/// All routes decorated with `#[rustapi::get]`, `#[rustapi::post]`, etc.
/// are automatically registered.
#[cfg(not(feature = "swagger-ui"))]
pub fn auto() -> Self {
Self::new().mount_auto_routes_grouped()
}
/// Create a configurable RustAPI application with auto-routes.
///
/// Provides builder methods for customization while still
/// auto-registering all decorated routes.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::config()
/// .docs_path("/api-docs")
/// .body_limit(5 * 1024 * 1024) // 5MB
/// .openapi_info("My API", "2.0.0", Some("API Description"))
/// .run("0.0.0.0:8080")
/// .await?;
/// ```
pub fn config() -> RustApiConfig {
RustApiConfig::new()
}
/// Set the global body size limit for request bodies
///
/// This protects against denial-of-service attacks via large payloads.
/// The default limit is 1MB (1024 * 1024 bytes).
///
/// # Arguments
///
/// * `limit` - Maximum body size in bytes
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .body_limit(5 * 1024 * 1024) // 5MB limit
/// .route("/upload", post(upload_handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn body_limit(mut self, limit: usize) -> Self {
self.body_limit = Some(limit);
self
}
/// Disable the body size limit
///
/// Warning: This removes protection against large payload attacks.
/// Only use this if you have other mechanisms to limit request sizes.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .no_body_limit() // Disable body size limit
/// .route("/upload", post(upload_handler))
/// ```
pub fn no_body_limit(mut self) -> Self {
self.body_limit = None;
self
}
/// Add a middleware layer to the application
///
/// Layers are executed in the order they are added (outermost first).
/// The first layer added will be the first to process the request and
/// the last to process the response.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use rustapi_core::middleware::{RequestIdLayer, TracingLayer};
///
/// RustApi::new()
/// .layer(RequestIdLayer::new()) // First to process request
/// .layer(TracingLayer::new()) // Second to process request
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn layer<L>(mut self, layer: L) -> Self
where
L: MiddlewareLayer,
{
self.layers.push(Box::new(layer));
self
}
/// Add a request interceptor to the application
///
/// Request interceptors are executed in registration order before the route handler.
/// Each interceptor can modify the request before passing it to the next interceptor
/// or handler.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::{RustApi, interceptor::RequestInterceptor, Request};
///
/// #[derive(Clone)]
/// struct AddRequestId;
///
/// impl RequestInterceptor for AddRequestId {
/// fn intercept(&self, mut req: Request) -> Request {
/// req.extensions_mut().insert(uuid::Uuid::new_v4());
/// req
/// }
///
/// fn clone_box(&self) -> Box<dyn RequestInterceptor> {
/// Box::new(self.clone())
/// }
/// }
///
/// RustApi::new()
/// .request_interceptor(AddRequestId)
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn request_interceptor<I>(mut self, interceptor: I) -> Self
where
I: RequestInterceptor,
{
self.interceptors.add_request_interceptor(interceptor);
self
}
/// Add a response interceptor to the application
///
/// Response interceptors are executed in reverse registration order after the route
/// handler completes. Each interceptor can modify the response before passing it
/// to the previous interceptor or client.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::{RustApi, interceptor::ResponseInterceptor, Response};
///
/// #[derive(Clone)]
/// struct AddServerHeader;
///
/// impl ResponseInterceptor for AddServerHeader {
/// fn intercept(&self, mut res: Response) -> Response {
/// res.headers_mut().insert("X-Server", "RustAPI".parse().unwrap());
/// res
/// }
///
/// fn clone_box(&self) -> Box<dyn ResponseInterceptor> {
/// Box::new(self.clone())
/// }
/// }
///
/// RustApi::new()
/// .response_interceptor(AddServerHeader)
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn response_interceptor<I>(mut self, interceptor: I) -> Self
where
I: ResponseInterceptor,
{
self.interceptors.add_response_interceptor(interceptor);
self
}
/// Add application state
///
/// State is shared across all handlers and can be extracted using `State<T>`.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Clone)]
/// struct AppState {
/// db: DbPool,
/// }
///
/// RustApi::new()
/// .state(AppState::new())
/// ```
pub fn state<S>(self, _state: S) -> Self
where
S: Clone + Send + Sync + 'static,
{
// Store state in the router's shared Extensions so `State<T>` extractor can retrieve it.
let state = _state;
let mut app = self;
app.router = app.router.state(state);
app
}
/// Register an `on_start` lifecycle hook
///
/// The callback runs **after** route registration and **before** the server
/// begins accepting connections. Multiple hooks execute in registration order.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .on_start(|| async {
/// println!("🚀 Server starting...");
/// // e.g. run DB migrations, warm caches
/// })
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn on_start<F, Fut>(mut self, hook: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.lifecycle_hooks
.on_start
.push(Box::new(move || Box::pin(hook())));
self
}
/// Register an `on_shutdown` lifecycle hook
///
/// The callback runs **after** the shutdown signal is received and the server
/// stops accepting new connections. Multiple hooks execute in registration order.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .on_shutdown(|| async {
/// println!("👋 Server shutting down...");
/// // e.g. flush logs, close DB connections
/// })
/// .run_with_shutdown("127.0.0.1:8080", ctrl_c())
/// .await
/// ```
pub fn on_shutdown<F, Fut>(mut self, hook: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.lifecycle_hooks
.on_shutdown
.push(Box::new(move || Box::pin(hook())));
self
}
/// Enable hot-reload mode for development
///
/// When enabled:
/// - A dev-mode banner is printed at startup
/// - The `RUSTAPI_HOT_RELOAD` env var is set so that `cargo rustapi watch`
/// can detect the server is reload-aware
/// - If the server is **not** already running under the CLI watcher,
/// a helpful hint is printed suggesting `cargo rustapi run --watch`
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .hot_reload(true)
/// .route("/", get(hello))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn hot_reload(mut self, enabled: bool) -> Self {
self.hot_reload = enabled;
self
}
/// Register an OpenAPI schema
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Schema)]
/// struct User { ... }
///
/// RustApi::new()
/// .register_schema::<User>()
/// ```
pub fn register_schema<T: rustapi_openapi::schema::RustApiSchema>(mut self) -> Self {
self.openapi_spec = self.openapi_spec.register::<T>();
self
}
/// Configure OpenAPI info (title, version, description)
pub fn openapi_info(mut self, title: &str, version: &str, description: Option<&str>) -> Self {
// NOTE: Do not reset the spec here; doing so would drop collected paths/schemas.
// This is especially important for `RustApi::auto()` and `RustApi::config()`.
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
self.openapi_spec.info.description = description.map(|d| d.to_string());
self
}
/// Get the current OpenAPI spec (for advanced usage/testing).
pub fn openapi_spec(&self) -> &rustapi_openapi::OpenApiSpec {
&self.openapi_spec
}
fn mount_auto_routes_grouped(mut self) -> Self {
let routes = crate::auto_route::collect_auto_routes();
// Use BTreeMap for deterministic route registration order
let mut by_path: BTreeMap<String, MethodRouter> = BTreeMap::new();
for route in routes {
let crate::handler::Route {
path: route_path,
method,
handler,
operation,
component_registrar,
..
} = route;
let method_enum = match method {
"GET" => http::Method::GET,
"POST" => http::Method::POST,
"PUT" => http::Method::PUT,
"DELETE" => http::Method::DELETE,
"PATCH" => http::Method::PATCH,
_ => http::Method::GET,
};
let path = if route_path.starts_with('/') {
route_path.to_string()
} else {
format!("/{}", route_path)
};
let entry = by_path.entry(path).or_default();
entry.insert_boxed_with_operation(method_enum, handler, operation, component_registrar);
}
#[cfg(feature = "tracing")]
let route_count: usize = by_path.values().map(|mr| mr.allowed_methods().len()).sum();
#[cfg(feature = "tracing")]
let path_count = by_path.len();
for (path, method_router) in by_path {
self = self.route(&path, method_router);
}
crate::trace_info!(
paths = path_count,
routes = route_count,
"Auto-registered routes"
);
// Apply any auto-registered schemas.
crate::auto_schema::apply_auto_schemas(&mut self.openapi_spec);
self
}
/// Add a route
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(index))
/// .route("/users", get(list_users).post(create_user))
/// .route("/users/{id}", get(get_user).delete(delete_user))
/// ```
pub fn route(mut self, path: &str, method_router: MethodRouter) -> Self {
for register_components in &method_router.component_registrars {
register_components(&mut self.openapi_spec);
}
// Register operations in OpenAPI spec
for (method, op) in &method_router.operations {
let mut op = op.clone();
add_path_params_to_operation(path, &mut op, &BTreeMap::new());
self.openapi_spec = self.openapi_spec.path(path, method.as_str(), op);
}
self.router = self.router.route(path, method_router);
self
}
/// Add a typed route
pub fn typed<P: crate::typed_path::TypedPath>(self, method_router: MethodRouter) -> Self {
self.route(P::PATH, method_router)
}
/// Mount a handler (convenience method)
///
/// Alias for `.route(path, method_router)` for a single handler.
#[deprecated(note = "Use route() directly or mount_route() for macro-based routing")]
pub fn mount(self, path: &str, method_router: MethodRouter) -> Self {
self.route(path, method_router)
}
/// Mount a route created with `#[rustapi::get]`, `#[rustapi::post]`, etc.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi::get("/users")]
/// async fn list_users() -> Json<Vec<User>> {
/// Json(vec![])
/// }
///
/// RustApi::new()
/// .mount_route(route!(list_users))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn mount_route(mut self, route: crate::handler::Route) -> Self {
let method_enum = match route.method {
"GET" => http::Method::GET,
"POST" => http::Method::POST,
"PUT" => http::Method::PUT,
"DELETE" => http::Method::DELETE,
"PATCH" => http::Method::PATCH,
_ => http::Method::GET,
};
(route.component_registrar)(&mut self.openapi_spec);
// Register operation in OpenAPI spec
let mut op = route.operation;
add_path_params_to_operation(route.path, &mut op, &route.param_schemas);
self.openapi_spec = self.openapi_spec.path(route.path, route.method, op);
self.route_with_method(route.path, method_enum, route.handler)
}
/// Helper to mount a single method handler
fn route_with_method(
self,
path: &str,
method: http::Method,
handler: crate::handler::BoxedHandler,
) -> Self {
use crate::router::MethodRouter;
// use http::Method; // Removed
// This is simplified. In a real implementation we'd merge with existing router at this path
// For now we assume one handler per path or we simply allow overwriting for this MVP step
// (matchit router doesn't allow easy merging/updating existing entries without rebuilding)
//
// TOOD: Enhance Router to support method merging
let path = if !path.starts_with('/') {
format!("/{}", path)
} else {
path.to_string()
};
// Check if we already have this path?
// For MVP, valid assumption: user calls .route() or .mount() once per path-method-combo
// But we need to handle multiple methods on same path.
// Our Router wrapper currently just inserts.
// Since we can't easily query matchit, we'll just insert.
// Limitations: strictly sequential mounting for now.
let mut handlers = std::collections::HashMap::new();
handlers.insert(method, handler);
let method_router = MethodRouter::from_boxed(handlers);
self.route(&path, method_router)
}
/// Nest a router under a prefix
///
/// All routes from the nested router will be registered with the prefix
/// prepended to their paths. OpenAPI operations from the nested router
/// are also propagated to the parent's OpenAPI spec with prefixed paths.
///
/// # Example
///
/// ```rust,ignore
/// let api_v1 = Router::new()
/// .route("/users", get(list_users));
///
/// RustApi::new()
/// .nest("/api/v1", api_v1)
/// ```
pub fn nest(mut self, prefix: &str, router: Router) -> Self {
// Normalize the prefix for OpenAPI paths
let normalized_prefix = normalize_prefix_for_openapi(prefix);
// Propagate OpenAPI operations from nested router with prefixed paths
// We need to do this before calling router.nest() because it consumes the router
for (matchit_path, method_router) in router.method_routers() {
for register_components in &method_router.component_registrars {
register_components(&mut self.openapi_spec);
}
// Get the display path from registered_routes (has {param} format)
let display_path = router
.registered_routes()
.get(matchit_path)
.map(|info| info.path.clone())
.unwrap_or_else(|| matchit_path.clone());
// Build the prefixed display path for OpenAPI
let prefixed_path = if display_path == "/" {
normalized_prefix.clone()
} else {
format!("{}{}", normalized_prefix, display_path)
};
// Register each operation in the OpenAPI spec
for (method, op) in &method_router.operations {
let mut op = op.clone();
add_path_params_to_operation(&prefixed_path, &mut op, &BTreeMap::new());
self.openapi_spec = self.openapi_spec.path(&prefixed_path, method.as_str(), op);
}
}
// Delegate to Router::nest for actual route registration
self.router = self.router.nest(prefix, router);
self
}
/// Serve static files from a directory
///
/// Maps a URL path prefix to a filesystem directory. Requests to paths under
/// the prefix will serve files from the corresponding location in the directory.
///
/// # Arguments
///
/// * `prefix` - URL path prefix (e.g., "/static", "/assets")
/// * `root` - Filesystem directory path
///
/// # Features
///
/// - Automatic MIME type detection
/// - ETag and Last-Modified headers for caching
/// - Index file serving for directories
/// - Path traversal prevention
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .serve_static("/assets", "./public")
/// .serve_static("/uploads", "./uploads")
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn serve_static(self, prefix: &str, root: impl Into<std::path::PathBuf>) -> Self {
self.serve_static_with_config(crate::static_files::StaticFileConfig::new(root, prefix))
}
/// Serve static files with custom configuration
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::static_files::StaticFileConfig;
///
/// let config = StaticFileConfig::new("./public", "/assets")
/// .max_age(86400) // Cache for 1 day
/// .fallback("index.html"); // SPA fallback
///
/// RustApi::new()
/// .serve_static_with_config(config)
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn serve_static_with_config(self, config: crate::static_files::StaticFileConfig) -> Self {
use crate::router::MethodRouter;
use std::collections::HashMap;
let prefix = config.prefix.clone();
let catch_all_path = format!("{}/*path", prefix.trim_end_matches('/'));
// Create the static file handler
let handler: crate::handler::BoxedHandler =
std::sync::Arc::new(move |req: crate::Request| {
let config = config.clone();
let path = req.uri().path().to_string();
Box::pin(async move {
let relative_path = path.strip_prefix(&config.prefix).unwrap_or(&path);
match crate::static_files::StaticFile::serve(relative_path, &config).await {
Ok(response) => response,
Err(err) => err.into_response(),
}
})
as std::pin::Pin<Box<dyn std::future::Future<Output = crate::Response> + Send>>
});
let mut handlers = HashMap::new();
handlers.insert(http::Method::GET, handler);
let method_router = MethodRouter::from_boxed(handlers);
self.route(&catch_all_path, method_router)
}
/// Enable response compression
///
/// Adds gzip/deflate compression for response bodies. The compression
/// is based on the client's Accept-Encoding header.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .compression()
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
#[cfg(feature = "compression")]
pub fn compression(self) -> Self {
self.layer(crate::middleware::CompressionLayer::new())
}
/// Enable response compression with custom configuration
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::middleware::CompressionConfig;
///
/// RustApi::new()
/// .compression_with_config(
/// CompressionConfig::new()
/// .min_size(512)
/// .level(9)
/// )
/// .route("/", get(handler))
/// ```
#[cfg(feature = "compression")]
pub fn compression_with_config(self, config: crate::middleware::CompressionConfig) -> Self {
self.layer(crate::middleware::CompressionLayer::with_config(config))
}
/// Enable Swagger UI documentation
///
/// This adds two endpoints:
/// - `{path}` - Swagger UI interface
/// - `{path}/openapi.json` - OpenAPI JSON specification
///
/// **Important:** Call `.docs()` AFTER registering all routes. The OpenAPI
/// specification is captured at the time `.docs()` is called, so routes
/// added afterwards will not appear in the documentation.
///
/// # Example
///
/// ```text
/// RustApi::new()
/// .route("/users", get(list_users)) // Add routes first
/// .route("/posts", get(list_posts)) // Add more routes
/// .docs("/docs") // Then enable docs - captures all routes above
/// .run("127.0.0.1:8080")
/// .await
/// ```
///
/// For `RustApi::auto()`, routes are collected before `.docs()` is called,
/// so this is handled automatically.
#[cfg(feature = "swagger-ui")]
pub fn docs(self, path: &str) -> Self {
let title = self.openapi_spec.info.title.clone();
let version = self.openapi_spec.info.version.clone();
let description = self.openapi_spec.info.description.clone();
self.docs_with_info(path, &title, &version, description.as_deref())
}
/// Enable Swagger UI documentation with custom API info
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .docs_with_info("/docs", "My API", "2.0.0", Some("API for managing users"))
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_info(
mut self,
path: &str,
title: &str,
version: &str,
description: Option<&str>,
) -> Self {
use crate::router::get;
// Update spec info
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
if let Some(desc) = description {
self.openapi_spec.info.description = Some(desc.to_string());
}
let path = path.trim_end_matches('/');
let openapi_path = format!("{}/openapi.json", path);
// Clone values for closures
let spec_value = self.openapi_spec.to_json();
let spec_json = serde_json::to_string_pretty(&spec_value).unwrap_or_else(|e| {
// Safe fallback if JSON serialization fails (though unlikely for Value)
tracing::error!("Failed to serialize OpenAPI spec: {}", e);
"{}".to_string()
});
let openapi_url = openapi_path.clone();
// Add OpenAPI JSON endpoint
let spec_handler = move || {
let json = spec_json.clone();
async move {
http::Response::builder()
.status(http::StatusCode::OK)
.header(http::header::CONTENT_TYPE, "application/json")
.body(crate::response::Body::from(json))
.unwrap_or_else(|e| {
tracing::error!("Failed to build response: {}", e);
http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.body(crate::response::Body::from("Internal Server Error"))
.unwrap()
})
}
};
// Add Swagger UI endpoint
let docs_handler = move || {
let url = openapi_url.clone();
async move {
let response = rustapi_openapi::swagger_ui_html(&url);
response.map(crate::response::Body::Full)
}
};
self.route(&openapi_path, get(spec_handler))
.route(path, get(docs_handler))
}
/// Enable Swagger UI documentation with Basic Auth protection
///
/// When username and password are provided, the docs endpoint will require
/// Basic Authentication. This is useful for protecting API documentation
/// in production environments.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/users", get(list_users))
/// .docs_with_auth("/docs", "admin", "secret123")
/// .run("127.0.0.1:8080")
/// .await
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_auth(self, path: &str, username: &str, password: &str) -> Self {
let title = self.openapi_spec.info.title.clone();
let version = self.openapi_spec.info.version.clone();
let description = self.openapi_spec.info.description.clone();
self.docs_with_auth_and_info(
path,
username,
password,
&title,
&version,
description.as_deref(),
)
}
/// Enable Swagger UI documentation with Basic Auth and custom API info
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .docs_with_auth_and_info(
/// "/docs",
/// "admin",
/// "secret",
/// "My API",
/// "2.0.0",
/// Some("Protected API documentation")
/// )
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_auth_and_info(
mut self,
path: &str,
username: &str,
password: &str,
title: &str,
version: &str,
description: Option<&str>,
) -> Self {
use crate::router::MethodRouter;
use base64::{engine::general_purpose::STANDARD, Engine};
use std::collections::HashMap;
// Update spec info
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
if let Some(desc) = description {
self.openapi_spec.info.description = Some(desc.to_string());
}
let path = path.trim_end_matches('/');
let openapi_path = format!("{}/openapi.json", path);
// Create expected auth header value
let credentials = format!("{}:{}", username, password);
let encoded = STANDARD.encode(credentials.as_bytes());