Skip to content

Commit

Permalink
avoid needless clones
Browse files Browse the repository at this point in the history
  • Loading branch information
lmaotrigine committed Aug 6, 2024
1 parent 781633d commit 25b585a
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 30 deletions.
6 changes: 3 additions & 3 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ impl FromRequestParts<AppState> for Master {
type Rejection = Error;

async fn from_request_parts(req: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
let config = Config::from_ref(state);
let expected = config.secret_key;
let config: &'static Config = FromRef::from_ref(state);
let expected = &config.secret_key;
if expected.is_empty() {
return Err(Error::new(
req.uri.path(),
Expand All @@ -92,7 +92,7 @@ impl FromRequestParts<AppState> for Master {
},
|t| Ok(t.to_str().unwrap_or_default()),
)?;
if token == *expected {
if token == **expected {
Ok(Self)
} else {
Err(Error::new(
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub struct WebCli {
pub config_file: __ConfigFile,
}

#[derive(Debug, Clone)]
#[derive(Debug)]
pub struct __ConfigFile {
path: Option<PathBuf>,
}
Expand Down Expand Up @@ -167,7 +167,7 @@ impl Args for __ConfigFile {
}

/// The configuration for the server.
#[derive(Debug, Clone)]
#[derive(Debug)]
pub struct Config {
/// Database configuration.
pub database: Database,
Expand All @@ -188,14 +188,14 @@ pub struct Config {
pub bind: SocketAddr,
}

#[derive(Debug, Deserialize, Clone)]
#[derive(Debug, Deserialize)]
pub struct Database {
/// A `PostgreSQL` connection string.
pub dsn: String,
}

#[cfg(feature = "webhook")]
#[derive(Debug, Deserialize, Clone)]
#[derive(Debug, Deserialize)]
pub struct Webhook {
/// The URL of the Discord webhook.
pub url: String,
Expand Down
6 changes: 3 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub async fn handle_errors(
) -> Result<Response, Error> {
let path = req.uri().path().to_owned();
let method = req.method().clone();
let server_name = state.config.server_name;
let server_name = &state.config.server_name;
let ip = match req.extract_parts::<RealIp>().await {
Ok(RealIp(ip)) => ip,
Err(e) => {
Expand All @@ -75,7 +75,7 @@ pub async fn handle_errors(
&path,
&method,
StatusCode::INTERNAL_SERVER_ERROR,
&server_name,
server_name,
));
}
};
Expand All @@ -89,7 +89,7 @@ pub async fn handle_errors(
StatusCode::METHOD_NOT_ALLOWED | StatusCode::NOT_FOUND | StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
let code = status.as_u16();
warn!("returned {code} to {ip} - tried to {method} {path} with Authorization {auth}");
Err(Error::new(&path, &method, status, &server_name))
Err(Error::new(&path, &method, status, server_name))
}
_ => Ok(resp),
}
Expand Down
13 changes: 6 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ pub fn init_logging() {
pub struct AppState {
stats: Arc<Mutex<stats::Stats>>,
pool: PgPool,
config: Config,
config: &'static Config,
git_revision: &'static str,
#[cfg(feature = "webhook")]
webhook: util::Webhook,
webhook: Arc<util::Webhook>,
server_start_time: DateTime<Utc>,
}

Expand All @@ -92,13 +92,12 @@ impl AppState {
/// This function will return an error if the database pool could not be
/// created, or (for some reason), fetching the stats using the pool
/// fails.
pub async fn from_config(config: Config) -> sqlx::Result<Self> {
pub async fn from_config(config: &'static Config) -> sqlx::Result<Self> {
#[cfg(feature = "webhook")]
let webhook = util::Webhook::new(config.webhook.clone());
let webhook = util::Webhook::new(&config.webhook);
let pool = PgPoolOptions::default()
.max_connections(10)
.connect(&config.database.dsn)
.await?;
.connect_lazy(&config.database.dsn)?;
let (server_start_time, stats) = {
(
pool.server_start_time().await,
Expand All @@ -111,7 +110,7 @@ impl AppState {
config,
git_revision: env!("HB_GIT_REVISION"),
#[cfg(feature = "webhook")]
webhook,
webhook: Arc::new(webhook),
server_start_time,
})
}
Expand Down
7 changes: 5 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use base64ct::{Base64Url, Encoding};
use clap::Parser;
use color_eyre::eyre::Result;
use heartbeat::{handle_errors, routes::router, AppState, Cli, Config, Subcmd, WebCli};
use std::{net::SocketAddr, time::Duration};
use std::{net::SocketAddr, sync::OnceLock, time::Duration};
use tokio::net::TcpListener;
use tower_http::{
timeout::TimeoutLayer,
Expand Down Expand Up @@ -60,10 +60,13 @@ async fn main() -> Result<()> {
}

async fn web(cli: WebCli) -> Result<()> {
static CONFIG: OnceLock<Config> = OnceLock::new();
let config = Config::try_new(cli)?;
CONFIG.set(config).expect("config to not be set");
let config = CONFIG.get().expect("config to be set");
info!(config = ?config, "Loaded config");
let bind = config.bind;
let router = router(&config);
let router = router(config);
let app_state = AppState::from_config(config).await?;
let trace_service = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
Expand Down
6 changes: 1 addition & 5 deletions src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,7 @@ async fn fire_webhook(state: AppState, title: &str, message: &str, level: Webhoo
WebhookLevel::LongAbsences => WebhookColour::Orange,
WebhookLevel::None => return,
};
match state
.webhook
.execute(title, message, level, colour, &state.config)
.await
{
match state.webhook.execute(title, message, level, colour, state.config).await {
Ok(()) => (),
Err(e) => error!("{e}"),
}
Expand Down
6 changes: 3 additions & 3 deletions src/routes/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub async fn index_page(
tokio::spawn(async move {
let _ = pool.incr_visits().await;
});
(StatusCode::OK, index(&stats, git_revision, &config))
(StatusCode::OK, index(&stats, git_revision, config))
}

#[axum::debug_handler]
Expand All @@ -50,10 +50,10 @@ pub async fn stats_page(
tokio::spawn(async move {
let _ = pool.incr_visits().await;
});
(StatusCode::OK, stats_template(&stats, &config, server_start_time))
(StatusCode::OK, stats_template(&stats, config, server_start_time))
}

#[axum::debug_handler]
pub async fn privacy_page(State(AppState { config, .. }): State<AppState>) -> Markup {
privacy(&config)
privacy(config)
}
6 changes: 3 additions & 3 deletions src/util/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ use serde::Serialize;

use crate::config::{Config, Webhook as WebhookConfig, WebhookLevel};

#[derive(Debug, Clone)]
#[derive(Debug)]
pub struct Webhook {
config: WebhookConfig,
config: &'static WebhookConfig,
client: Client,
}

Expand Down Expand Up @@ -44,7 +44,7 @@ struct Author<'a> {
}

impl Webhook {
pub fn new(config: WebhookConfig) -> Self {
pub fn new(config: &'static WebhookConfig) -> Self {
Self {
config,
client: Client::new(),
Expand Down

0 comments on commit 25b585a

Please sign in to comment.