a3s-boot 0.1.1

Adapter-first modular Rust web framework for A3S inspired by Nest.js
Documentation
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
use super::application::BootApplication;
use super::lazy::LazyModuleLoader;
use super::registration::{ModuleRegistrationSink, ModuleRegistry};
use crate::pipeline::PipelineComponents;
#[cfg(feature = "auth")]
use crate::AuthGuard;
use crate::{
    ApiVersioning, BootError, BootErrorKind, BootResponse, ExceptionFilter, ExecutionInterceptor,
    Guard, Interceptor, MessagePatternDefinition, Middleware, Module, ModuleRef, OpenApiDocument,
    OpenApiInfo, Pipe, ProviderDefinition, ProviderToken, Result, RouteDefinition,
    SerializationInterceptor, WebSocketGatewayDefinition,
};
#[cfg(feature = "compression")]
use crate::{CompressionInterceptor, CompressionOptions};
#[cfg(feature = "security")]
use crate::{
    CorsMiddleware, CorsOptions, CorsPreflightRoute, CorsResponseInterceptor, CsrfGuard,
    CsrfOptions, RateLimitGuard, RateLimitOptions, SecurityHeadersInterceptor,
    SecurityHeadersOptions,
};
#[cfg(feature = "session")]
use crate::{SessionCookieInterceptor, SessionManager, SessionMiddleware, SessionModule};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

/// Builder for a [`BootApplication`].
#[derive(Default)]
pub struct BootApplicationBuilder {
    modules: Vec<Arc<dyn Module>>,
    routes: Vec<RouteDefinition>,
    gateways: Vec<WebSocketGatewayDefinition>,
    message_patterns: Vec<MessagePatternDefinition>,
    global_pipeline: PipelineComponents,
    global_execution_guards: Vec<Arc<dyn Guard>>,
    global_execution_interceptors: Vec<Arc<dyn ExecutionInterceptor>>,
    global_prefix: Option<String>,
    api_versioning: Option<ApiVersioning>,
    openapi_routes: Vec<(String, OpenApiInfo)>,
    provider_overrides: BTreeMap<ProviderToken, ProviderDefinition>,
    #[cfg(feature = "security")]
    cors_preflight: Option<CorsPreflightRoute>,
}

impl BootApplicationBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Import a root module.
    pub fn import<M>(mut self, module: M) -> Self
    where
        M: Module,
    {
        self.modules.push(Arc::new(module));
        self
    }

    /// Import a shared root module.
    pub fn import_arc(mut self, module: Arc<dyn Module>) -> Self {
        self.modules.push(module);
        self
    }

    /// Add a framework-neutral route directly to the application shell.
    pub fn route(mut self, route: RouteDefinition) -> Self {
        self.routes.push(route);
        self
    }

    /// Add a framework-neutral WebSocket gateway directly to the application shell.
    pub fn gateway(mut self, gateway: WebSocketGatewayDefinition) -> Self {
        self.gateways.push(gateway);
        self
    }

    /// Add a framework-neutral microservice message pattern directly to the application shell.
    pub fn message_pattern(mut self, pattern: MessagePatternDefinition) -> Self {
        self.message_patterns.push(pattern);
        self
    }

    /// Serve a generated OpenAPI document at the given path.
    pub fn serve_openapi(mut self, path: impl Into<String>, info: OpenApiInfo) -> Self {
        self.openapi_routes.push((path.into(), info));
        self
    }

    /// Prefix every route in the built application, for example `/api/v1`.
    pub fn global_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.global_prefix = Some(prefix.into());
        self
    }

    /// Enable adapter-neutral API version matching for HTTP routes.
    pub fn enable_api_versioning(mut self, versioning: ApiVersioning) -> Self {
        self.api_versioning = Some(versioning);
        self
    }

    /// Add application-wide middleware, similar to Nest middleware.
    pub fn use_global_middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware,
    {
        self.global_pipeline.push_middleware(middleware);
        self
    }

    /// Add an application-wide pipe, similar to Nest's global pipes.
    pub fn use_global_pipe<P>(mut self, pipe: P) -> Self
    where
        P: Pipe,
    {
        self.global_pipeline.push_pipe(pipe);
        self
    }

    /// Add an application-wide guard, similar to Nest's global guards.
    pub fn use_global_guard<G>(mut self, guard: G) -> Self
    where
        G: Guard,
    {
        self.global_pipeline.push_guard(guard);
        self
    }

    /// Add an application-wide protocol-neutral guard.
    pub fn use_global_execution_guard<G>(mut self, guard: G) -> Self
    where
        G: Guard,
    {
        let guard: Arc<dyn Guard> = Arc::new(guard);
        self.global_pipeline.push_guard_arc(Arc::clone(&guard));
        self.global_execution_guards.push(guard);
        self
    }

    /// Add a provider-backed authentication guard using the default auth strategy.
    #[cfg(feature = "auth")]
    pub fn use_global_auth(mut self) -> Self {
        self.global_pipeline.push_guard(AuthGuard::new());
        self
    }

    /// Add a provider-backed authentication guard using a named auth strategy.
    #[cfg(feature = "auth")]
    pub fn use_global_auth_strategy(mut self, strategy: impl Into<String>) -> Self {
        self.global_pipeline
            .push_guard(AuthGuard::new().strategy(strategy));
        self
    }

    /// Add an application-wide interceptor, similar to Nest's global interceptors.
    pub fn use_global_interceptor<I>(mut self, interceptor: I) -> Self
    where
        I: Interceptor,
    {
        self.global_pipeline.push_interceptor(interceptor);
        self
    }

    /// Add an application-wide protocol-neutral interceptor.
    pub fn use_global_execution_interceptor<I>(mut self, interceptor: I) -> Self
    where
        I: ExecutionInterceptor,
    {
        let interceptor: Arc<dyn ExecutionInterceptor> = Arc::new(interceptor);
        self.global_pipeline
            .push_execution_interceptor_arc(Arc::clone(&interceptor));
        self.global_execution_interceptors.push(interceptor);
        self
    }

    /// Add the default JSON response serialization interceptor.
    pub fn use_global_serialization(mut self) -> Self {
        self.global_pipeline
            .push_interceptor(SerializationInterceptor::new());
        self
    }

    /// Add gzip response compression for clients that send `Accept-Encoding: gzip`.
    #[cfg(feature = "compression")]
    pub fn use_global_compression(mut self, options: CompressionOptions) -> Self {
        self.global_pipeline
            .push_interceptor(CompressionInterceptor::with_options(options));
        self
    }

    /// Add CORS handling for preflight and normal responses.
    #[cfg(feature = "security")]
    pub fn use_global_cors(mut self, options: CorsOptions) -> Self {
        self.global_pipeline
            .push_middleware(CorsMiddleware::with_options(options.clone()));
        self.global_pipeline
            .push_interceptor(CorsResponseInterceptor::with_options(options.clone()));
        self.cors_preflight = Some(CorsPreflightRoute::with_options(options));
        self
    }

    /// Add common security response headers, similar to a small Helmet setup.
    #[cfg(feature = "security")]
    pub fn use_global_security_headers(mut self, options: SecurityHeadersOptions) -> Self {
        self.global_pipeline
            .push_interceptor(SecurityHeadersInterceptor::with_options(options));
        self
    }

    /// Add an application-wide CSRF guard for unsafe HTTP methods.
    #[cfg(feature = "security")]
    pub fn use_global_csrf(mut self, options: CsrfOptions) -> Self {
        self.global_pipeline
            .push_guard(CsrfGuard::with_options(options));
        self
    }

    /// Add an in-memory application-wide rate limit guard.
    #[cfg(feature = "security")]
    pub fn use_global_rate_limit(mut self, options: RateLimitOptions) -> Self {
        self.global_pipeline
            .push_guard(RateLimitGuard::with_options(options));
        self
    }

    /// Add global session middleware and cookie persistence.
    #[cfg(feature = "session")]
    pub fn use_global_sessions(mut self, manager: SessionManager) -> Self {
        self.global_pipeline
            .push_middleware(SessionMiddleware::new(manager.clone()));
        self.global_pipeline
            .push_interceptor(SessionCookieInterceptor::new(manager));
        self
    }

    /// Import a session module and apply its middleware/interceptor globally.
    #[cfg(feature = "session")]
    pub fn use_global_session_module(mut self, module: SessionModule) -> Self {
        let manager = module.manager();
        self = self.use_global_sessions(manager);
        self.modules.push(Arc::new(module));
        self
    }

    /// Add an application-wide exception filter, similar to Nest's global filters.
    pub fn use_global_filter<F>(mut self, filter: F) -> Self
    where
        F: ExceptionFilter,
    {
        self.global_pipeline.push_filter(filter);
        self
    }

    /// Add an application-wide exception filter for selected error kinds.
    pub fn use_global_catch_filter<I, F>(mut self, kinds: I, filter: F) -> Self
    where
        I: IntoIterator<Item = BootErrorKind>,
        F: ExceptionFilter,
    {
        self.global_pipeline.push_catch_filter(kinds, filter);
        self
    }

    /// Enable DTO validation for routes that carry validation metadata.
    pub fn use_global_validation(mut self) -> Self {
        self.global_pipeline.enable_validation();
        self
    }

    /// Replace matching module providers before modules build controllers.
    ///
    /// This is primarily used by testing utilities to swap provider
    /// implementations while preserving the application module graph.
    pub fn override_provider(mut self, provider: ProviderDefinition) -> Self {
        self.provider_overrides
            .insert(provider.token().clone(), provider);
        self
    }

    /// Resolve module imports, providers, controllers, and routes.
    pub fn build(self) -> Result<BootApplication> {
        let module_ref = ModuleRef::new();
        let global_ref = ModuleRef::new();
        let lazy_module_loader = LazyModuleLoader::new(global_ref.clone());
        global_ref.insert_arc(Arc::new(lazy_module_loader.clone()))?;
        module_ref.add_visible_scope(global_ref.clone())?;
        let mut registry = ModuleRegistry::new(global_ref, self.provider_overrides);
        let mut modules = Vec::new();
        let mut module_instances = Vec::new();
        let mut routes = self
            .routes
            .into_iter()
            .map(|route| route.with_pipeline_prefix(&self.global_pipeline))
            .collect::<Vec<_>>();
        let mut gateways = self.gateways;
        let mut message_patterns = self.message_patterns;

        {
            let mut sink = ModuleRegistrationSink {
                modules: &mut modules,
                module_instances: &mut module_instances,
                routes: &mut routes,
                gateways: &mut gateways,
                message_patterns: &mut message_patterns,
            };

            for module in &self.modules {
                let registered = registry.register_module(
                    Arc::clone(module),
                    &self.global_pipeline,
                    &mut sink,
                )?;
                module_ref.add_visible_scope(registered.module_ref)?;
            }
        }
        for (name, registered) in registry.registered_modules() {
            lazy_module_loader.seed_module(name, registered.module_ref, registered.exports)?;
        }

        let mut routes = apply_global_prefix(routes, self.global_prefix.as_deref())?;
        let gateways = apply_global_gateway_prefix(gateways, self.global_prefix.as_deref())?
            .into_iter()
            .map(|gateway| {
                gateway.with_execution_pipeline_prefix(
                    &self.global_execution_guards,
                    &self.global_execution_interceptors,
                )
            })
            .collect::<Vec<_>>();
        let message_patterns = message_patterns
            .into_iter()
            .map(|pattern| {
                pattern.with_execution_pipeline_prefix(
                    &self.global_execution_guards,
                    &self.global_execution_interceptors,
                )
            })
            .collect::<Vec<_>>();
        let documented_routes = routes.clone();

        for (path, info) in self.openapi_routes {
            let document = OpenApiDocument::from_routes(info, &documented_routes);
            let route =
                openapi_json_route(path, document)?.with_pipeline_prefix(&self.global_pipeline);
            let route = match self.global_prefix.as_deref() {
                Some(prefix) => route.with_path_prefix(prefix)?,
                None => route,
            };
            routes.push(route);
        }

        #[cfg(feature = "security")]
        if let Some(cors_preflight) = &self.cors_preflight {
            add_cors_preflight_routes(&mut routes, cors_preflight, &self.global_pipeline)?;
        }

        routes = routes
            .into_iter()
            .map(|route| route.with_default_module_ref(module_ref.clone()))
            .collect();

        validate_unique_routes(&routes, self.api_versioning.as_ref())?;
        validate_unique_gateways(&gateways)?;
        validate_unique_message_patterns(&message_patterns)?;
        validate_gateway_route_conflicts(&routes, &gateways)?;

        Ok(BootApplication {
            routes,
            gateways,
            message_patterns,
            modules,
            module_ref,
            module_instances,
            api_versioning: self.api_versioning,
        })
    }

    /// Resolve modules with async provider factories, then build the application.
    pub async fn build_async(self) -> Result<BootApplication> {
        let module_ref = ModuleRef::new();
        let global_ref = ModuleRef::new();
        let lazy_module_loader = LazyModuleLoader::new(global_ref.clone());
        global_ref.insert_arc(Arc::new(lazy_module_loader.clone()))?;
        module_ref.add_visible_scope(global_ref.clone())?;
        let mut registry = ModuleRegistry::new(global_ref, self.provider_overrides);
        let mut modules = Vec::new();
        let mut module_instances = Vec::new();
        let mut routes = self
            .routes
            .into_iter()
            .map(|route| route.with_pipeline_prefix(&self.global_pipeline))
            .collect::<Vec<_>>();
        let mut gateways = self.gateways;
        let mut message_patterns = self.message_patterns;

        {
            let mut sink = ModuleRegistrationSink {
                modules: &mut modules,
                module_instances: &mut module_instances,
                routes: &mut routes,
                gateways: &mut gateways,
                message_patterns: &mut message_patterns,
            };

            for module in &self.modules {
                let registered = registry
                    .register_module_async(Arc::clone(module), &self.global_pipeline, &mut sink)
                    .await?;
                module_ref.add_visible_scope(registered.module_ref)?;
            }
        }
        for (name, registered) in registry.registered_modules() {
            lazy_module_loader.seed_module(name, registered.module_ref, registered.exports)?;
        }

        let mut routes = apply_global_prefix(routes, self.global_prefix.as_deref())?;
        let gateways = apply_global_gateway_prefix(gateways, self.global_prefix.as_deref())?
            .into_iter()
            .map(|gateway| {
                gateway.with_execution_pipeline_prefix(
                    &self.global_execution_guards,
                    &self.global_execution_interceptors,
                )
            })
            .collect::<Vec<_>>();
        let message_patterns = message_patterns
            .into_iter()
            .map(|pattern| {
                pattern.with_execution_pipeline_prefix(
                    &self.global_execution_guards,
                    &self.global_execution_interceptors,
                )
            })
            .collect::<Vec<_>>();
        let documented_routes = routes.clone();

        for (path, info) in self.openapi_routes {
            let document = OpenApiDocument::from_routes(info, &documented_routes);
            let route =
                openapi_json_route(path, document)?.with_pipeline_prefix(&self.global_pipeline);
            let route = match self.global_prefix.as_deref() {
                Some(prefix) => route.with_path_prefix(prefix)?,
                None => route,
            };
            routes.push(route);
        }

        #[cfg(feature = "security")]
        if let Some(cors_preflight) = &self.cors_preflight {
            add_cors_preflight_routes(&mut routes, cors_preflight, &self.global_pipeline)?;
        }

        routes = routes
            .into_iter()
            .map(|route| route.with_default_module_ref(module_ref.clone()))
            .collect();

        validate_unique_routes(&routes, self.api_versioning.as_ref())?;
        validate_unique_gateways(&gateways)?;
        validate_unique_message_patterns(&message_patterns)?;
        validate_gateway_route_conflicts(&routes, &gateways)?;

        Ok(BootApplication {
            routes,
            gateways,
            message_patterns,
            modules,
            module_ref,
            module_instances,
            api_versioning: self.api_versioning,
        })
    }
}

fn apply_global_gateway_prefix(
    gateways: Vec<WebSocketGatewayDefinition>,
    prefix: Option<&str>,
) -> Result<Vec<WebSocketGatewayDefinition>> {
    match prefix {
        Some(prefix) => gateways
            .into_iter()
            .map(|gateway| gateway.with_path_prefix(prefix))
            .collect(),
        None => Ok(gateways),
    }
}

fn openapi_json_route(path: String, document: OpenApiDocument) -> Result<RouteDefinition> {
    RouteDefinition::get(path, move |_| {
        let document = document.clone();
        async move { BootResponse::json(&document) }
    })
    .map(RouteDefinition::hide_from_openapi)
}

#[cfg(feature = "security")]
fn add_cors_preflight_routes(
    routes: &mut Vec<RouteDefinition>,
    cors_preflight: &CorsPreflightRoute,
    pipeline: &PipelineComponents,
) -> Result<()> {
    let existing_options = routes
        .iter()
        .filter(|route| route.method() == crate::HttpMethod::Options)
        .map(RouteDefinition::path_shape)
        .collect::<BTreeSet<_>>();
    let mut generated = BTreeSet::new();
    let source_routes = routes.clone();

    for route in source_routes {
        if route.method() == crate::HttpMethod::Options {
            continue;
        }

        let path_shape = route.path_shape();
        if existing_options.contains(&path_shape) || !generated.insert(path_shape) {
            continue;
        }

        let preflight = RouteDefinition::options(route.path().to_string(), cors_preflight.clone())?
            .hide_from_openapi()
            .with_pipeline_prefix(pipeline);
        routes.push(preflight);
    }

    Ok(())
}

fn apply_global_prefix(
    routes: Vec<RouteDefinition>,
    prefix: Option<&str>,
) -> Result<Vec<RouteDefinition>> {
    match prefix {
        Some(prefix) => routes
            .into_iter()
            .map(|route| route.with_path_prefix(prefix))
            .collect(),
        None => Ok(routes),
    }
}

fn validate_unique_routes(
    routes: &[RouteDefinition],
    versioning: Option<&ApiVersioning>,
) -> Result<()> {
    for (index, route) in routes.iter().enumerate() {
        for existing in routes.iter().take(index) {
            if existing.method() != route.method()
                || existing.path_shape_key() != route.path_shape_key()
                || existing.host_shape_key() != route.host_shape_key()
            {
                continue;
            }

            let duplicate = match versioning {
                Some(versioning) => existing
                    .versioning()
                    .overlaps(route.versioning(), versioning.default_version()),
                None => true,
            };
            if !duplicate {
                continue;
            }

            let host = route
                .host()
                .map(|host| format!(" host {host}"))
                .unwrap_or_default();
            return Err(BootError::DuplicateRoute(format!(
                "{} {}{} version {}",
                route.method().as_str(),
                route.path(),
                host,
                route.versioning()
            )));
        }
    }

    Ok(())
}

fn validate_unique_gateways(gateways: &[WebSocketGatewayDefinition]) -> Result<()> {
    let mut seen = BTreeSet::new();

    for gateway in gateways {
        if !seen.insert(gateway.path_shape()) {
            return Err(BootError::DuplicateRoute(format!("WS {}", gateway.path())));
        }
    }

    Ok(())
}

fn validate_gateway_route_conflicts(
    routes: &[RouteDefinition],
    gateways: &[WebSocketGatewayDefinition],
) -> Result<()> {
    let get_routes = routes
        .iter()
        .filter(|route| route.method().matches(crate::HttpMethod::Get))
        .map(RouteDefinition::path_shape)
        .collect::<BTreeSet<_>>();

    for gateway in gateways {
        if get_routes.contains(&gateway.path_shape()) {
            return Err(BootError::DuplicateRoute(format!("GET {}", gateway.path())));
        }
    }

    Ok(())
}

fn validate_unique_message_patterns(patterns: &[MessagePatternDefinition]) -> Result<()> {
    let mut seen = BTreeSet::new();

    for pattern in patterns {
        if !seen.insert(pattern.pattern()) {
            return Err(BootError::DuplicateRoute(format!(
                "message pattern {}",
                pattern.pattern()
            )));
        }
    }

    Ok(())
}