vantus 0.2.0

Macro-first async Rust web platform with typed extraction, DI, and configuration binding.
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
use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::runtime::Runtime;
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use crate::app::module::RuntimeModule;
use crate::app::modules::WebPlatformModule;
use crate::app::state::{ServiceCollection, ServiceContainer, ServiceError};
use crate::config::{
    AppConfig, ConfigError, Configuration, ConfigurationBuilder, FromConfiguration,
};
use crate::core::errors::FrameworkError;
use crate::core::http::{Request, Response};
use crate::middleware::MiddlewareStack;
use crate::routing::{RequestContext, RouteDefinition, RouteRegistrar, RouteRegistration, Router};
use crate::runtime::{RuntimeSettings, ServerHandle, serve};

type ConfigBinder =
    Box<dyn Fn(&Configuration, &mut ServiceCollection) -> Result<(), HostBuildError> + Send + Sync>;

#[derive(Clone)]
pub struct BackgroundTasks {
    cancellation: CancellationToken,
    handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
}

impl BackgroundTasks {
    pub fn new(cancellation: CancellationToken) -> Self {
        Self {
            cancellation,
            handles: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub fn cancellation_token(&self) -> CancellationToken {
        self.cancellation.clone()
    }

    pub async fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        self.handles.lock().await.push(tokio::spawn(future));
    }

    pub async fn shutdown(&self) {
        self.cancellation.cancel();
        let handles = {
            let mut guard = self.handles.lock().await;
            std::mem::take(&mut *guard)
        };
        for handle in handles {
            let _ = handle.await;
        }
    }
}

#[derive(Clone)]
pub struct HostContext {
    services: Arc<ServiceContainer>,
    configuration: Arc<Configuration>,
    background_tasks: BackgroundTasks,
}

impl HostContext {
    pub fn configuration(&self) -> &Configuration {
        self.configuration.as_ref()
    }

    pub fn services(&self) -> Arc<ServiceContainer> {
        Arc::clone(&self.services)
    }

    pub fn service_scope(&self) -> crate::app::state::ServiceScope {
        self.services.create_scope()
    }

    pub fn background_tasks(&self) -> &BackgroundTasks {
        &self.background_tasks
    }
}

pub struct ApplicationHost {
    router: Arc<Router>,
    middleware: Arc<MiddlewareStack>,
    services: Arc<ServiceContainer>,
    modules: Vec<Arc<dyn RuntimeModule>>,
    configuration: Arc<Configuration>,
    runtime_settings: RuntimeSettings,
}

impl ApplicationHost {
    pub fn context(&self) -> HostContext {
        HostContext {
            services: Arc::clone(&self.services),
            configuration: Arc::clone(&self.configuration),
            background_tasks: BackgroundTasks::new(CancellationToken::new()),
        }
    }

    pub async fn serve(self) -> Result<ServerHandle, HostError> {
        let cancellation = CancellationToken::new();
        let background_tasks = BackgroundTasks::new(cancellation.clone());
        let context = HostContext {
            services: Arc::clone(&self.services),
            configuration: Arc::clone(&self.configuration),
            background_tasks: background_tasks.clone(),
        };

        for module in &self.modules {
            module
                .on_start(&context)
                .await
                .map_err(HostError::Framework)?;
        }

        serve(
            self.router,
            self.middleware,
            self.services,
            self.modules,
            self.configuration,
            self.runtime_settings,
            context,
        )
        .await
    }

    pub async fn run(self) -> Result<(), HostError> {
        self.serve().await?.wait().await
    }

    pub async fn handle(&self, request: Request) -> Response {
        let Some(route) = self.router.route(&request.method, &request.path) else {
            return Response::not_found();
        };

        let ctx = RequestContext::new(
            request,
            route.path_params,
            Arc::clone(&self.services),
            Arc::clone(&self.configuration),
        );
        match self
            .middleware
            .execute(&route.middleware, ctx, route.handler)
            .await
        {
            Ok(response) => response,
            Err(error) => error.to_response(),
        }
    }

    pub fn blocking_run(self) -> Result<(), HostError> {
        Runtime::new()
            .map_err(HostError::Io)?
            .block_on(async move { self.run().await })
    }
}

pub struct HostBuilder {
    router: Router,
    middleware: MiddlewareStack,
    modules: Vec<Arc<dyn RuntimeModule>>,
    services: ServiceCollection,
    configuration: ConfigurationBuilder,
    binders: Vec<ConfigBinder>,
}

impl HostBuilder {
    pub fn new() -> Self {
        let mut builder = Self {
            router: Router::new(),
            middleware: MiddlewareStack::new(),
            modules: Vec::new(),
            services: ServiceCollection::new(),
            configuration: ConfigurationBuilder::new(),
            binders: Vec::new(),
        };
        builder.bind_config::<AppConfig>();
        builder
    }

    pub fn config_file(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.configuration.config_file(path);
        self
    }

    pub fn environment(&mut self, name: impl Into<String>) -> &mut Self {
        self.configuration.environment(name);
        self
    }

    pub fn profile(&mut self, profile: impl Into<String>) -> &mut Self {
        self.configuration.profile(profile);
        self
    }

    pub fn env_prefix(&mut self, prefix: impl Into<String>) -> &mut Self {
        self.configuration.env_prefix(prefix);
        self
    }

    pub fn service_singleton<T>(&mut self, value: T) -> &mut Self
    where
        T: Send + Sync + 'static,
    {
        self.services.add_singleton(value);
        self
    }

    pub fn service_singleton_with<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&crate::app::state::ServiceScope) -> Result<T, ServiceError> + Send + Sync + 'static,
    {
        self.services.add_singleton_with(factory);
        self
    }

    pub fn service_scoped<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&crate::app::state::ServiceScope) -> Result<T, ServiceError> + Send + Sync + 'static,
    {
        self.services.add_scoped(factory);
        self
    }

    pub fn service_transient<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&crate::app::state::ServiceScope) -> Result<T, ServiceError> + Send + Sync + 'static,
    {
        self.services.add_transient(factory);
        self
    }

    pub fn bind_config<T>(&mut self) -> &mut Self
    where
        T: FromConfiguration + Send + Sync + 'static,
    {
        self.binders.push(Box::new(|config, services| {
            services.add_singleton(T::from_configuration(config).map_err(HostBuildError::Config)?);
            Ok(())
        }));
        self
    }

    pub fn module<M>(&mut self, module: M) -> &mut Self
    where
        M: RuntimeModule + 'static,
    {
        let module = Arc::new(module);
        module
            .configure_services(&mut self.services)
            .expect("module service configuration failed");
        module.configure_middleware(&mut self.middleware);
        module
            .configure_routes(self)
            .expect("module route configuration failed");
        self.modules.push(module);
        self
    }

    pub fn group<F>(&mut self, prefix: impl Into<String>, f: F) -> &mut Self
    where
        F: FnOnce(&mut RouteGroup<'_>),
    {
        let mut group = RouteGroup::new(self, prefix.into());
        f(&mut group);
        self
    }

    pub fn with_web_platform(&mut self) -> &mut Self {
        self.module(WebPlatformModule::default())
    }

    pub fn build(mut self) -> Result<ApplicationHost, HostBuildError> {
        let configuration = Arc::new(self.configuration.build().map_err(HostBuildError::Config)?);
        for binder in &self.binders {
            binder(configuration.as_ref(), &mut self.services)?;
        }

        let services = Arc::new(self.services.build());
        let root_scope = services.root_scope();
        let app_config = root_scope
            .resolve::<AppConfig>()
            .map_err(HostBuildError::Service)?;
        let runtime_settings = RuntimeSettings::default().merge_from(app_config.as_ref());

        Ok(ApplicationHost {
            router: Arc::new(self.router),
            middleware: Arc::new(self.middleware),
            services,
            modules: self.modules,
            configuration,
            runtime_settings,
        })
    }
}

impl Default for HostBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RouteRegistration for HostBuilder {
    fn register_definition(&mut self, definition: RouteDefinition) -> &mut Self {
        self.router.add_definition(definition);
        self
    }
}

impl RouteRegistrar for HostBuilder {
    fn add_route(&mut self, definition: RouteDefinition) -> Result<(), FrameworkError> {
        self.router.add_definition(definition);
        Ok(())
    }
}

#[doc(hidden)]
pub struct RouteGroup<'a> {
    builder: &'a mut HostBuilder,
    prefix: String,
    middleware: Vec<Arc<dyn crate::middleware::Middleware>>,
}

impl<'a> RouteGroup<'a> {
    fn new(builder: &'a mut HostBuilder, prefix: String) -> Self {
        Self {
            builder,
            prefix: normalize_prefix(&prefix),
            middleware: Vec::new(),
        }
    }

    pub fn group<F>(&mut self, prefix: impl Into<String>, f: F) -> &mut Self
    where
        F: FnOnce(&mut RouteGroup<'_>),
    {
        let prefix = join_paths(&self.prefix, &prefix.into());
        let middleware = self.middleware.clone();
        let mut group = RouteGroup {
            builder: self.builder,
            prefix,
            middleware,
        };
        f(&mut group);
        self
    }

    pub fn module<M>(&mut self, module: M) -> &mut Self
    where
        M: RuntimeModule + 'static,
    {
        let module = Arc::new(module);
        module
            .configure_services(&mut self.builder.services)
            .expect("module service configuration failed");
        module.configure_middleware(&mut self.builder.middleware);
        module
            .configure_routes(self)
            .expect("module route configuration failed");
        self.builder.modules.push(module);
        self
    }
}

impl RouteRegistration for RouteGroup<'_> {
    fn register_definition(&mut self, mut definition: RouteDefinition) -> &mut Self {
        definition.path = join_paths(&self.prefix, &definition.path);
        let mut middleware = self.middleware.clone();
        middleware.extend(definition.middleware);
        definition.middleware = middleware;
        self.builder.router.add_definition(definition);
        self
    }
}

impl RouteRegistrar for RouteGroup<'_> {
    fn add_route(&mut self, definition: RouteDefinition) -> Result<(), FrameworkError> {
        self.register_definition(definition);
        Ok(())
    }
}

#[derive(Debug)]
pub enum HostBuildError {
    Config(ConfigError),
    Service(ServiceError),
    Framework(FrameworkError),
}

impl fmt::Display for HostBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HostBuildError::Config(error) => write!(f, "{error}"),
            HostBuildError::Service(error) => write!(f, "{error}"),
            HostBuildError::Framework(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for HostBuildError {}

#[derive(Debug)]
pub enum HostError {
    Build(HostBuildError),
    Framework(FrameworkError),
    Io(std::io::Error),
}

impl fmt::Display for HostError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HostError::Build(error) => write!(f, "{error}"),
            HostError::Framework(error) => write!(f, "{error}"),
            HostError::Io(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for HostError {}

impl From<HostBuildError> for HostError {
    fn from(value: HostBuildError) -> Self {
        Self::Build(value)
    }
}

fn normalize_prefix(prefix: &str) -> String {
    if prefix.is_empty() || prefix == "/" {
        String::new()
    } else {
        format!("/{}", prefix.trim_matches('/'))
    }
}

fn join_paths(prefix: &str, path: &str) -> String {
    let prefix = normalize_prefix(prefix);
    let path = path.trim_matches('/');
    match (prefix.is_empty(), path.is_empty()) {
        (true, true) => "/".to_string(),
        (true, false) => format!("/{}", path),
        (false, true) => prefix,
        (false, false) => format!("{}/{}", prefix, path),
    }
}