roadster 0.9.0-alpha.5

A "Batteries Included" web framework for rust designed to get you moving fast.
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
#[cfg(feature = "cli")]
use crate::api::cli::parse_cli;
#[cfg(feature = "cli")]
use crate::api::cli::roadster::RoadsterCli;
use crate::app::App;
use crate::app::context::AppContext;
use crate::config::environment::Environment;
use crate::config::{AppConfig, AppConfigOptions, ConfigOverrideSource};
#[cfg(feature = "db-sql")]
use crate::db::migration::registry::MigratorRegistry;
use crate::error::RoadsterResult;
use crate::health::check::registry::HealthCheckRegistry;
use crate::lifecycle::registry::LifecycleHandlerRegistry;
use crate::service::registry::ServiceRegistry;
use axum_core::extract::FromRef;
use std::marker::PhantomData;
use std::path::PathBuf;

/// Contains all the objects needed to run the [`App`]. Useful if a consumer needs access to some
/// of the prepared state before running the app.
///
/// Created by [`prepare`]. Pass to [`crate::app::run_prepared`] to run the [`App`].
#[non_exhaustive]
pub struct PreparedApp<A, S>
where
    A: 'static + App<S>,
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
{
    #[cfg(feature = "cli")]
    pub cli: Option<PreparedAppCli<A, S>>,
    pub app: A,
    pub state: S,
    #[cfg(feature = "db-sql")]
    pub migrator_registry: MigratorRegistry<S>,
    pub service_registry: ServiceRegistry<S>,
    pub lifecycle_handler_registry: LifecycleHandlerRegistry<A, S>,
}

#[non_exhaustive]
pub struct PreparedAppCli<A, S>
where
    A: 'static + App<S>,
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
{
    #[cfg(feature = "cli")]
    pub roadster_cli: RoadsterCli,
    #[cfg(feature = "cli")]
    pub app_cli: A::Cli,
    pub(crate) _app: PhantomData<A>,
    pub(crate) _state: PhantomData<S>,
}

/// Options to use when preparing the app. Normally these values can be provided via env vars
/// or CLI arguments when running the [`crate::app::run`] method. However, if [`prepare`] is called
/// directly, especially from somewhere without an env or CLI, then this can be used to configure
/// the prepared app.
#[derive(Default, Debug, bon::Builder)]
#[non_exhaustive]
pub struct PrepareOptions {
    /// Manually provide custom config sources. This is mostly intended to allow overriding
    /// specific app config fields for tests (e.g., using the [`ConfigOverrideSource`]), but it
    /// can also be used to provide other custom config sources outside of tests.
    #[builder(field)]
    pub config_sources: Vec<Box<dyn Send + Sync + config::Source>>,

    pub env: Option<Environment>,

    #[builder(default = true)]
    pub parse_cli: bool,

    pub config_dir: Option<PathBuf>,

    /// Explicitly override the entire [`AppConfig`] to run the app with. If provided, the other
    /// config-related fields in this struct will not be used.
    pub config: Option<AppConfig>,
}

impl<S: prepare_options_builder::State> PrepareOptionsBuilder<S> {
    pub fn config_sources(
        mut self,
        config_sources: Vec<Box<dyn Send + Sync + config::Source>>,
    ) -> Self {
        self.config_sources.extend(config_sources);
        self
    }

    pub fn add_config_source(
        mut self,
        source: impl 'static + Send + Sync + config::Source,
    ) -> Self {
        self.config_sources.push(Box::new(source));
        self
    }

    pub fn add_config_source_boxed(
        mut self,
        source: Box<dyn Send + Sync + config::Source>,
    ) -> Self {
        self.config_sources.push(source);
        self
    }
}

impl PrepareOptions {
    /// The default recommended [`PrepareOptions`] to use in tests.
    pub fn test() -> Self {
        PrepareOptions::builder()
            .env(Environment::Test)
            .parse_cli(false)
            .build()
    }

    /// Provide an override for a specific config field.
    pub fn with_config_override(mut self, name: String, value: config::Value) -> Self {
        self.config_sources.push(Box::new(
            ConfigOverrideSource::builder()
                .name(name)
                .value(value)
                .build(),
        ));
        self
    }

    /// Override the entire [`AppConfig`].
    pub fn with_config(mut self, config: AppConfig) -> Self {
        self.config = Some(config);
        self
    }
}

/// Prepare the app. Sets up everything needed to start the app, but does not execute anything.
/// Specifically, the following are skipped:
///
/// 1. Handling CLI commands
/// 2. Health checks
/// 3. Lifecycle Handlers
/// 4. Starting any services
pub async fn prepare<A, S>(app: A, options: PrepareOptions) -> RoadsterResult<PreparedApp<A, S>>
where
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
    A: 'static + Send + Sync + App<S>,
{
    prepare_from_cli_and_state(build_cli_and_state(app, options).await?).await
}

// This runs before tracing is initialized, so we need to use `println` in order to
// log from this method.
#[allow(clippy::disallowed_macros)]
pub(crate) async fn build_cli_and_state<A, S>(
    app: A,
    options: PrepareOptions,
) -> RoadsterResult<CliAndState<A, S>>
where
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
    A: 'static + Send + Sync + App<S>,
{
    #[cfg(feature = "cli")]
    let (roadster_cli, app_cli) = if options.parse_cli {
        let (roadster_cli, app_cli) = parse_cli::<A, S, _, _>(std::env::args_os())?;
        (Some(roadster_cli), Some(app_cli))
    } else {
        (None, None)
    };

    #[cfg(feature = "cli")]
    let environment = roadster_cli
        .as_ref()
        .and_then(|cli| cli.environment.clone())
        .or(options.env);
    #[cfg(not(feature = "cli"))]
    let environment: Option<Environment> = options.env;

    let environment = if let Some(environment) = environment {
        println!("Using environment: {environment:?}");
        environment
    } else {
        Environment::new()?
    };

    #[cfg(feature = "cli")]
    let config_dir = roadster_cli
        .as_ref()
        .and_then(|cli| cli.config_dir.clone())
        .or(options.config_dir);
    #[cfg(not(feature = "cli"))]
    let config_dir: Option<std::path::PathBuf> = options.config_dir;

    let async_config_sources = app
        .async_config_sources(&environment)
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    let app_config_options = AppConfigOptions::builder()
        .environment(environment)
        .maybe_config_dir(config_dir)
        .config_sources(options.config_sources);
    let app_config_options = async_config_sources
        .into_iter()
        .fold(app_config_options, |app_config_options, source| {
            app_config_options.add_async_source_boxed(source)
        })
        .build();
    let config = if let Some(config) = options.config {
        config
    } else {
        AppConfig::new_with_options(app_config_options).await?
    };

    app.init_tracing(&config)
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    #[cfg(not(feature = "cli"))]
    config.validate(true)?;
    #[cfg(feature = "cli")]
    config.validate(
        !roadster_cli
            .as_ref()
            .map(|cli| cli.skip_validate_config)
            .unwrap_or_default(),
    )?;

    let state = build_state(&app, config).await?;

    Ok(CliAndState {
        app,
        #[cfg(feature = "cli")]
        roadster_cli,
        #[cfg(feature = "cli")]
        app_cli,
        state,
    })
}

/// Utility method to build the app's state object.
pub(crate) async fn build_state<A, S>(app: &A, config: AppConfig) -> RoadsterResult<S>
where
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
    A: 'static + Send + Sync + App<S>,
{
    #[cfg(not(test))]
    let metadata = app
        .metadata(&config)
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    let mut extension_registry = Default::default();
    app.provide_context_extensions(&config, &mut extension_registry)
        .await
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    // The `config.clone()` here is technically not necessary. However, without it, RustRover
    // is giving a "value used after move" error when creating an actual `AppContext` below.
    #[cfg(test)]
    let context = AppContext::test(Some(config.clone()), None, None)?;
    #[cfg(not(test))]
    let context = AppContext::new::<A, S>(app, config, metadata, extension_registry).await?;

    let result = app
        .provide_state(context)
        .await
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    Ok(result)
}

pub(crate) async fn prepare_from_cli_and_state<A, S>(
    cli_and_state: CliAndState<A, S>,
) -> RoadsterResult<PreparedApp<A, S>>
where
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
    A: 'static + Send + Sync + App<S>,
{
    let CliAndState {
        app,
        #[cfg(feature = "cli")]
        roadster_cli,
        #[cfg(feature = "cli")]
        app_cli,
        state,
    } = cli_and_state;

    let PreparedAppWithoutCli {
        app,
        state,
        #[cfg(feature = "db-sql")]
        migrator_registry,
        service_registry,
        lifecycle_handler_registry,
    } = prepare_without_cli(app, state).await?;

    #[cfg(feature = "cli")]
    let cli = if let Some((roadster_cli, app_cli)) = roadster_cli.zip(app_cli) {
        Some(PreparedAppCli {
            roadster_cli,
            app_cli,
            _app: Default::default(),
            _state: Default::default(),
        })
    } else {
        None
    };

    Ok(PreparedApp {
        #[cfg(feature = "cli")]
        cli,
        app,
        #[cfg(feature = "db-sql")]
        migrator_registry,
        state,
        service_registry,
        lifecycle_handler_registry,
    })
}

#[non_exhaustive]
pub struct PreparedAppWithoutCli<A, S>
where
    A: 'static + App<S>,
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
{
    pub app: A,
    pub state: S,
    #[cfg(feature = "db-sql")]
    pub migrator_registry: MigratorRegistry<S>,
    pub service_registry: ServiceRegistry<S>,
    pub lifecycle_handler_registry: LifecycleHandlerRegistry<A, S>,
}

pub(crate) async fn prepare_without_cli<A, S>(
    app: A,
    state: S,
) -> RoadsterResult<PreparedAppWithoutCli<A, S>>
where
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
    A: 'static + Send + Sync + App<S>,
{
    let context = AppContext::from_ref(&state);

    #[cfg(feature = "db-sql")]
    let migrator_registry = {
        let mut migrator_registry = MigratorRegistry::new();
        app.migrators(&state, &mut migrator_registry)
            .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;
        migrator_registry
    };

    let mut lifecycle_handler_registry = LifecycleHandlerRegistry::new(&state);
    app.lifecycle_handlers(&state, &mut lifecycle_handler_registry)
        .await
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    let mut health_check_registry = HealthCheckRegistry::new(&context);
    app.health_checks(&state, &mut health_check_registry)
        .await
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;
    context.set_health_checks(health_check_registry)?;

    let mut service_registry = ServiceRegistry::new(&state);
    app.services(&state, &mut service_registry)
        .await
        .map_err(|err| crate::error::other::OtherError::Other(Box::new(err)))?;

    Ok(PreparedAppWithoutCli {
        app,
        state,
        #[cfg(feature = "db-sql")]
        migrator_registry,
        service_registry,
        lifecycle_handler_registry,
    })
}

#[non_exhaustive]
pub(crate) struct CliAndState<A, S>
where
    A: 'static + App<S>,
    S: 'static + Send + Sync + Clone,
    AppContext: FromRef<S>,
{
    pub app: A,
    #[cfg(feature = "cli")]
    pub roadster_cli: Option<RoadsterCli>,
    #[cfg(feature = "cli")]
    pub app_cli: Option<A::Cli>,
    pub state: S,
}

#[cfg(test)]
mod tests {
    use crate::app::prepare::PrepareOptions;
    use insta::assert_debug_snapshot;

    #[test]
    fn prepare_options_test() {
        let options = PrepareOptions::test();
        assert_debug_snapshot!(options);
    }
}