Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ pub async fn auth_middleware(
}

pub async fn health_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
if !state.backend_manager.get_healthy_nodes().is_empty() {
StatusCode::NO_CONTENT
} else {
if state.backend_manager.get_healthy_nodes().is_empty() {
StatusCode::SERVICE_UNAVAILABLE
} else {
StatusCode::NO_CONTENT
}
}

Expand All @@ -71,11 +71,11 @@ pub async fn backend_handler(
.backend_manager
.set_backend_state(backend, action == "enable")
.await
.map_err(|e| (StatusCode::BAD_REQUEST, format!("Error: {e:#}")))?
.map_err(|e| (StatusCode::BAD_REQUEST, format!("Error: {e:#}")))?;
}

_ => return Err((StatusCode::BAD_REQUEST, format!("Unknown action: {action}"))),
};
}

Ok((StatusCode::OK, "Ok\n".to_string()))
}
Expand Down Expand Up @@ -106,7 +106,7 @@ pub async fn config_reload(State(state): State<Arc<ApiState>>) -> Response {
format!("Error reloading config: {e:#}"),
)
.into_response();
};
}

"Ok\n".into_response()
}
Expand Down Expand Up @@ -187,7 +187,7 @@ pub fn setup_api_axum_router(
.route("/config/put", put(config_put).layer(auth.clone()));

if let Some(v) = waf_layer {
router = router.nest("/waf", waf::create_router(v).layer(auth))
router = router.nest("/waf", waf::create_router(v).layer(auth));
}

#[allow(unused_mut)]
Expand Down
33 changes: 16 additions & 17 deletions src/backend.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::significant_drop_tightening)]

use std::{cell::RefCell, fmt::Display, path::PathBuf, sync::Arc, time::Duration};

use anyhow::{Context, Error, anyhow, bail};
Expand Down Expand Up @@ -108,7 +110,7 @@ impl From<BackendConf> for Backend {
}
}

/// Sets up the LBBackendRouter instance using the given config parameters
/// Sets up the `LBBackendRouter` instance using the given config parameters
pub fn setup_backend_router(
client: Arc<dyn ClientHttp<Body>>,
backends: Vec<BackendConf>,
Expand Down Expand Up @@ -158,7 +160,7 @@ impl Display for BackendManager {
}

impl BackendManager {
/// Create a new BackendManager
/// Create a new `BackendManager`
pub fn new(
client: Arc<dyn ClientHttp<Body>>,
config_path: PathBuf,
Expand Down Expand Up @@ -201,7 +203,7 @@ impl BackendManager {
) -> LBBackendRouter {
setup_backend_router(
self.client.clone(),
backends.clone(),
backends,
strategy,
self.check_interval,
self.check_timeout,
Expand All @@ -218,13 +220,13 @@ impl BackendManager {
strategy: Strategy,
) {
// Prepare new BackendRouter
let router_new = if !backends.is_empty() {
let router_new = if backends.is_empty() {
None
} else {
let r = self.create_backend_router(backends.clone(), strategy);
// Wait until all backends have known health status
Self::wait_healthchecks(&r).await;
Some(Arc::new(r))
} else {
None
};

// Get the old BackendRouter
Expand Down Expand Up @@ -337,8 +339,7 @@ impl BackendManager {
pub fn get_healthy_nodes(&self) -> Arc<Vec<Arc<Backend>>> {
self.backend_router
.load_full()
.map(|x| x.get_healthy())
.unwrap_or_else(|| Arc::new(vec![]))
.map_or_else(|| Arc::new(vec![]), |x| x.get_healthy())
}

/// Enables or disables the given backend
Expand Down Expand Up @@ -369,15 +370,15 @@ impl Run for BackendManager {
warn!("{self}: task started");
loop {
select! {
_ = token.cancelled() => {
() = token.cancelled() => {
warn!("{self}: task stopped");
break;
},

_ = sig.recv() => {
warn!("{self}: received config reload signal");
match self.load_config().await {
Ok(_) => warn!("{self}: configuration reloaded successfully"),
Ok(()) => warn!("{self}: configuration reloaded successfully"),
Err(e) => warn!("{self}: failed to reload config: {e:#}"),
}
}
Expand All @@ -402,19 +403,17 @@ impl ChecksTarget<Arc<Backend>> for BackendHealthChecker {
.body(Body::empty())
.unwrap(); // This should never fail

let res = match timeout(self.timeout, self.client.execute(req)).await {
Ok(res) => match res {
let res = if let Ok(res) = timeout(self.timeout, self.client.execute(req)).await {
match res {
Ok(v) => v,
Err(e) => {
info!("Health check failed for {target}: request failed: {e:#}");
return TargetState::Degraded;
}
},

Err(_) => {
info!("Health check failed for {target}: request timed out");
return TargetState::Degraded;
}
} else {
info!("Health check failed for {target}: request timed out");
return TargetState::Degraded;
};

if !res.status().is_success() {
Expand Down
2 changes: 2 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::struct_field_names)]

use std::{net::SocketAddr, path::PathBuf, time::Duration};

use clap::{Args, Parser};
Expand Down
10 changes: 5 additions & 5 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub const AUTHOR_NAME: &str = "Boundary Node Team <boundary-nodes@dfinity.org>";
pub static ENV: OnceLock<String> = OnceLock::new();
pub static HOSTNAME: OnceLock<String> = OnceLock::new();

#[allow(clippy::too_many_lines)]
pub async fn main(
cli: &Cli,
log_handle: Handle<LevelFilter, tracing_subscriber::Registry>,
Expand Down Expand Up @@ -134,17 +135,16 @@ pub async fn main(
vector.clone(),
&registry,
waf_layer,
)
.context("unable to setup Axum Router")?;
);

// HTTP server metrics
let http_metrics = Metrics::new(&registry);

// Set up HTTP router (redirecting to HTTPS or serving all endpoints)
let axum_router_http = if !cli.listen.listen_insecure_serve_http_only {
Router::new().fallback(redirect_to_https)
} else {
let axum_router_http = if cli.listen.listen_insecure_serve_http_only {
axum_router.clone()
} else {
Router::new().fallback(redirect_to_https)
};

let server_http = Arc::new(
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![allow(clippy::redundant_closure_for_method_calls)]
#![allow(clippy::doc_markdown)]

mod api;
mod backend;
mod cli;
Expand Down
6 changes: 4 additions & 2 deletions src/metrics.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::cast_possible_wrap)]

use std::{
sync::Arc,
time::{Duration, Instant},
Expand Down Expand Up @@ -71,7 +73,7 @@ impl MetricsRunner {
}

impl MetricsRunner {
async fn update(&self) -> Result<(), Error> {
fn update(&self) -> Result<(), Error> {
// Record jemalloc memory usage
epoch::advance().map_err(|e| anyhow!("unable to advance epoch: {e:#}"))?;

Expand Down Expand Up @@ -102,7 +104,7 @@ impl MetricsRunner {
impl Run for MetricsRunner {
async fn run(&self, _: CancellationToken) -> Result<(), Error> {
let start = Instant::now();
if let Err(e) = self.update().await {
if let Err(e) = self.update() {
warn!("Unable to update metrics: {e:#}");
} else {
debug!("Metrics updated in {}ms", start.elapsed().as_millis());
Expand Down
20 changes: 6 additions & 14 deletions src/middleware/metrics.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::cast_possible_wrap)]

use std::{
cell::RefCell,
sync::Arc,
Expand Down Expand Up @@ -96,6 +98,7 @@ pub struct MetricsState {
log_requests_long: Option<Duration>,
}

#[allow(clippy::too_many_lines)]
pub async fn middleware(
State(state): State<Arc<MetricsState>>,
Extension(conn_info): Extension<Arc<ConnInfo>>,
Expand All @@ -114,12 +117,7 @@ pub async fn middleware(
.remove::<RequestId>()
.map(|x| x.to_string())
.unwrap_or_default();
let request_size = request
.body()
.size_hint()
.exact()
.map(|x| x as i64)
.unwrap_or(-1);
let request_size = request.body().size_hint().exact().map_or(-1, |x| x as i64);
let remote_addr = conn_info.remote_addr.ip().to_canonical().to_string();
let timestamp = time::OffsetDateTime::now_utc();
let (tls_version, tls_cipher, tls_handshake) =
Expand Down Expand Up @@ -147,8 +145,7 @@ pub async fn middleware(
let backend = meta
.ctx
.backend
.map(|x| x.name.clone())
.unwrap_or_else(|| "unknown".into());
.map_or_else(|| "unknown".into(), |x| x.name.clone());

let labels = &[
tls_version,
Expand Down Expand Up @@ -243,12 +240,7 @@ pub async fn middleware(
.await;
let duration = start.elapsed().as_secs_f64();

let response_size = response
.body()
.size_hint()
.exact()
.map(|x| x as i64)
.unwrap_or(-1);
let response_size = response.body().size_hint().exact().map_or(-1, |x| x as i64);
let retries = response
.extensions_mut()
.remove::<Retries>()
Expand Down
16 changes: 6 additions & 10 deletions src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ async fn buffer_response(state: &HandlerState, response: Response) -> Response {
.body()
.size_hint()
.exact()
.map(|x| x <= state.response_body_size_limit as u64)
== Some(true);
.is_some_and(|x| x <= state.response_body_size_limit as u64);

// Return the response as-is if the body isn't bufferable
if !body_bufferable {
Expand All @@ -107,10 +106,9 @@ async fn buffer_response(state: &HandlerState, response: Response) -> Response {
.unwrap_or_default()
.into_inner()
.backend
.map(|x| x.name.clone())
.unwrap_or_else(|| "unknown".into());
let body = Limited::new(body, state.response_body_size_limit);
.map_or_else(|| "unknown".into(), |x| x.name.clone());

let body = Limited::new(body, state.response_body_size_limit);
let Ok(body) = timeout(state.response_body_timeout, body.collect()).await else {
info!("Timed out reading response body from backend '{backend}'");
return (
Expand Down Expand Up @@ -246,7 +244,7 @@ pub fn setup_axum_router(
vector: Option<Arc<Vector>>,
registry: &Registry,
waf_layer: Option<WafLayer>,
) -> Result<Router, Error> {
) -> Router {
let state = Arc::new(HandlerState::new(
backend_manager,
cli.network.network_request_body_buffer,
Expand Down Expand Up @@ -277,7 +275,7 @@ pub fn setup_axum_router(
))
.layer(option_layer(waf_layer));

let router = Router::new()
Router::new()
.fallback(|request: Request| async move {
let Some(host) = extract_authority(&request) else {
return Ok((StatusCode::BAD_REQUEST, "Unable to extract authority").into_response());
Expand All @@ -296,7 +294,5 @@ pub fn setup_axum_router(

Ok(handler.call(request, state).await)
})
.layer(middlewares);

Ok(router)
.layer(middlewares)
}
4 changes: 2 additions & 2 deletions src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use prometheus::Registry;

use crate::{cli::Cli, core::HOSTNAME};

// Prepares the stuff needed for serving TLS
/// Prepares the stuff needed for serving TLS
pub async fn setup(
cli: &Cli,
tasks: &mut TaskManager,
Expand Down Expand Up @@ -124,7 +124,7 @@ async fn setup_custom_domains(
}
tasks.add("custom_domains_canister_client", client.clone());

certificate_providers.push(client.clone());
certificate_providers.push(client);

Ok(())
}
Loading