web: context: Own the Config

The `server::context::Context` struct now owns the
`server::config::Config` struct.  Consumers who need to access
configuration properties can obtain a reference to the configuration
using the `config()` method.

This change will ultimately support the "service" structures, which will
be constructed and owned by the context.  They will need to reference
the config as well.
backend
Dustin 2022-01-13 19:47:19 -06:00
parent ea89601f49
commit ef97448b72
2 changed files with 16 additions and 16 deletions

View File

@ -1,23 +1,25 @@
use super::config::Config;
use crate::rpc::gen_client::Client;
use crate::server::error::{ApiError, ErrorResponse};
use jsonrpc_core_client::transports::ipc::connect;
use rocket::http::Status as HttpStatus;
use rocket::serde::json::Json;
use std::path::PathBuf;
pub struct Context {
socket_path: PathBuf,
config: Config,
}
impl Context {
pub fn new<P: Into<PathBuf>>(socket: P) -> Self {
Self {
socket_path: socket.into(),
}
/// Construct a new Context
///
/// The context takes ownership of the configuration. To access it,
/// use [`Self::config()`].
pub fn new(config: Config) -> Self {
Self { config }
}
pub async fn client(&self) -> Result<Client, ApiError> {
match connect(&self.socket_path).await {
match connect(&self.config.socket).await {
Ok(client) => Ok(client),
Err(e) => Err((
HttpStatus::ServiceUnavailable,
@ -28,4 +30,9 @@ impl Context {
)),
}
}
/// Get a reference to the web server application configuration
pub fn config(&self) -> &Config {
&self.config
}
}

View File

@ -7,7 +7,6 @@ use config::Config;
use argh::FromArgs;
use context::Context;
use rocket;
use rocket::fairing::AdHoc;
use rocket::figment::providers::{Env, Format, Serialized, Toml};
use rocket::figment::Figment;
@ -53,20 +52,14 @@ pub async fn main() -> Result<(), rocket::Error> {
figment = figment.merge(("socket", socket));
}
let context = Context::new(
figment
.find_value("socket")
.expect("No daemon socket path configured")
.as_str()
.expect("Invalid daemon socket path"),
);
let config: Config = figment.extract().unwrap();
let context = Context::new(config);
rocket::custom(figment)
.mount(
"/",
rocket::routes![routes::status::get_status, routes::auth::login],
)
.attach(AdHoc::config::<Config>())
.manage(context)
.ignite()
.await?