From 9e04d66bd6acd3071e579a70a11f873d3a0ba803 Mon Sep 17 00:00:00 2001 From: Kehinde Date: Mon, 9 Nov 2026 23:42:14 +0100 Subject: [PATCH 1/5] feat: improve error handling --- Cargo.lock | 12 +++++ Cargo.toml | 2 +- src/app.rs | 130 +++++++++++++++++++++++++++++++++++++++++----------- src/main.rs | 5 +- 4 files changed, 120 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7f547cb..e2fa242 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,6 +120,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "axum-macros", "bytes", "form_urlencoded", "futures-util", @@ -165,6 +166,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "base64" version = "0.23.1" diff --git a/Cargo.toml b/Cargo.toml index ee00cef..4e6e2ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] -axum = "0.8.9" +axum = { version = "0.8.9", features = ["macros"] } env_logger = "0.11.11" envy = "0.4.2" log = "0.4.34" diff --git a/src/app.rs b/src/app.rs index 4298ee0..c5651a9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,14 +1,17 @@ mod html; +use axum::extract::Request; +use axum::middleware::Next; use axum::response::Response; -use axum::{http::StatusCode, response::IntoResponse}; +use axum::{extract::FromRequest, http::StatusCode, response::IntoResponse}; +use html::get_html_content; use regex::Regex; use reqwest::{self, Client}; use serde::{Deserialize, Serialize}; use serde_email::Email; use std::io; +use std::sync::Arc; use tracing::{Instrument, info, info_span}; - use url::Url; #[derive(Deserialize)] @@ -17,8 +20,6 @@ struct ApiError { code: u16, } -use html::get_html_content; - #[derive(thiserror::Error, Debug)] pub enum AppError { #[error("Invalid base url: {0}")] @@ -40,20 +41,52 @@ pub enum AppError { Io(#[from] io::Error), } +#[derive(FromRequest)] +#[from_request(via(axum::Json), rejection(AppError))] +struct AppJson(T); + +impl IntoResponse for AppJson +where + axum::Json: IntoResponse, +{ + fn into_response(self) -> Response { + axum::Json(self.0).into_response() + } +} + +#[derive(Serialize)] +struct ErrorResponse { + message: String, +} impl IntoResponse for AppError { fn into_response(self) -> Response { - match self { - AppError::InvalidBaseUrl(_) => StatusCode::BAD_REQUEST, + let (status, message, err) = match self { + AppError::InvalidBaseUrl(_) => ( + StatusCode::BAD_REQUEST, + "bad request".to_owned(), + Some(self), + ), AppError::ParseError(_) | AppError::Io(_) | AppError::Reqwest(_) | AppError::ApiError { message: _, code: _, - } => StatusCode::INTERNAL_SERVER_ERROR, - AppError::NotFound(_) => StatusCode::NOT_FOUND, + } => ( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong".to_owned(), + Some(self), + ), + AppError::NotFound(_) => (StatusCode::NOT_FOUND, "not found".to_owned(), Some(self)), + }; + + let mut response = (status, AppJson(ErrorResponse { message })).into_response(); + if let Some(err) = err { + response + .extensions_mut() + .insert(Arc::new(err)); } - .into_response() + response } } @@ -78,10 +111,23 @@ pub struct Guest { pub host_address: String, } +pub async fn log_app_errors(req: Request, next: Next) -> Response { + let response = next + .run(req) + .await; + if let Some(err) = response + .extensions() + .get::>() + { + tracing::error!(?err, "An unexpected error occured inside the handler") + } + response +} pub struct AccessCode(String, u32); pub fn get_name_and_number(el: &str) -> Result { - let name = Regex::new(r"(?\w+)").unwrap(); + //this regex is wrong + let name = Regex::new(r"^\s*(?\D+?)\s+\d+\s*$").unwrap(); let number = Regex::new(r"(?\d{5})").unwrap(); let Some(caps) = name.captures(el) else { return Err(AppError::ParseError(String::from( @@ -225,33 +271,50 @@ pub async fn app(config: AppConfig) -> Result { .to_string(), }; + let mut max_retries = 5; + + //shared mutable state let mut state = String::new(); let AccessCode(name, code) = get_access_code(&client, &create_endpoint, &guest) .instrument(info_span!("api", step = "getting access code...")) .await?; + //updated here? state.push_str(&name); - // Lots of problems with this while loop - // no base case where it just exists - while state.to_lowercase() - != guest - .guest_name + if max_retries > 0 { + log::info!("{:?}", name); + if state + .trim() .to_lowercase() - { - info!(returned = %state, expected= %&guest.guest_name, "name mismatch, retrying"); - let str = format!( - "returned={} expected={} name mismatch, retrying", + != name + .trim() + .to_lowercase() + { + info!(returned = %state, expected= %&guest.guest_name, "name mismatch, retrying"); + let str = format!( + "returned={} expected={} name mismatch, retrying", + state, &guest.guest_name + ); + let AccessCode(name, _) = get_access_code(&client, &create_endpoint, &guest) + .instrument(info_span!("api", span = str)) + .await?; + state = name; + max_retries -= 1; + } + } + + if max_retries == 0 { + let err_message = format!( + "returned={} expected={} name mismatch", state, &guest.guest_name ); - let AccessCode(name, _) = get_access_code(&client, &create_endpoint, &guest) - .instrument(info_span!("api", span = str)) - .await?; - - state = name; + return Err(AppError::ApiError { + message: err_message, + code: 500, + }); } - Ok(code) } @@ -261,10 +324,11 @@ mod tests { use crate::app::html::get_nested_html_content; const SAMPLE_HTML: &str = r#" - !DOCTYPE html> + Hello, world!

Hello, world!

+

mr obinna 33588

opeyemi adeleke

"#; @@ -274,6 +338,12 @@ mod tests { assert_eq!(text, "Hello, world!") } + #[test] + fn it_gets_space_separated_text_from_html() { + let text = get_html_content("h2", SAMPLE_HTML); + assert_eq!(text, "mr obinna 33588") + } + #[test] fn it_gets_nested_text_from_html() { let text = get_nested_html_content("h5", "p", SAMPLE_HTML).unwrap(); @@ -287,4 +357,12 @@ mod tests { assert_eq!(name, "Opeyemi"); assert_eq!(number, 51402) } + + #[test] + fn it_extracts_name_when_honorific_is_added() { + let access_code = get_name_and_number("mr obinna 33588"); + let AccessCode(name, number) = access_code.unwrap(); + assert_eq!(name, "mr obinna"); + assert_eq!(number, 33588) + } } diff --git a/src/main.rs b/src/main.rs index b08934e..40d8c3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ mod app; -use crate::app::{AppConfig, AppError, Result, app}; -use axum::extract::State; +use crate::app::{AppConfig, AppError, Result, app, log_app_errors}; use axum::{Json, Router, routing::get, routing::post}; +use axum::{extract::State, middleware::from_fn}; use log::info; use serde::{Deserialize, Serialize}; use serde_email::Email; @@ -90,6 +90,7 @@ async fn server(config: &Config) -> Result { .route("/access-code", post(handle_access_code)) .route("/", get(json)) .with_state(state) + .layer(from_fn(log_app_errors)) .layer(PropagateRequestIdLayer::x_request_id()) .layer( TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::new().include_headers(true)), From 9f497f35f122904d63924c2409dc5d27c56fb149 Mon Sep 17 00:00:00 2001 From: Kehinde Date: Tue, 10 Nov 2026 16:13:48 +0100 Subject: [PATCH 2/5] fix: remove regex comment --- src/app.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index c5651a9..24c46c0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -126,7 +126,6 @@ pub async fn log_app_errors(req: Request, next: Next) -> Response { pub struct AccessCode(String, u32); pub fn get_name_and_number(el: &str) -> Result { - //this regex is wrong let name = Regex::new(r"^\s*(?\D+?)\s+\d+\s*$").unwrap(); let number = Regex::new(r"(?\d{5})").unwrap(); let Some(caps) = name.captures(el) else { From 54e386a4f5cc1e789d0f89cfcebcbd221e76421a Mon Sep 17 00:00:00 2001 From: Kehinde Date: Tue, 10 Nov 2026 16:20:31 +0100 Subject: [PATCH 3/5] fix: avoid recreating regex in the loop --- src/app.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/app.rs b/src/app.rs index 24c46c0..38a076d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -9,8 +9,10 @@ use regex::Regex; use reqwest::{self, Client}; use serde::{Deserialize, Serialize}; use serde_email::Email; -use std::io; -use std::sync::Arc; +use std::{ + io, + sync::{Arc, LazyLock}, +}; use tracing::{Instrument, info, info_span}; use url::Url; @@ -126,14 +128,16 @@ pub async fn log_app_errors(req: Request, next: Next) -> Response { pub struct AccessCode(String, u32); pub fn get_name_and_number(el: &str) -> Result { - let name = Regex::new(r"^\s*(?\D+?)\s+\d+\s*$").unwrap(); - let number = Regex::new(r"(?\d{5})").unwrap(); - let Some(caps) = name.captures(el) else { + static NAME: LazyLock = + LazyLock::new(|| Regex::new(r"^\s*(?\D+?)\s+\d+\s*$").unwrap()); + static NUMBER: LazyLock = LazyLock::new(|| Regex::new(r"(?\d{5})").unwrap()); + + let Some(caps) = NAME.captures(el) else { return Err(AppError::ParseError(String::from( "Could not find the name", ))); }; - let Some(num_caps) = number.captures(el) else { + let Some(num_caps) = NUMBER.captures(el) else { return Err(AppError::ParseError(String::from( "Could not find the number", ))); @@ -175,6 +179,7 @@ async fn get_access_code( let guest_with_code = get_html_content("h2", &html); + // this recompiles the regex in a loop which is a poor pattern let AccessCode(name, number) = get_name_and_number(&guest_with_code)?; Ok(AccessCode(name, number)) From 84dc48475edbb6139f616d93f06c6dcb941bce05 Mon Sep 17 00:00:00 2001 From: Kehinde Date: Wed, 11 Nov 2026 13:11:25 +0100 Subject: [PATCH 4/5] feat: use try syntax for error Honestly, i am not certain at this point how different try is from manually panicking. this is cleaner and easier to read. --- src/main.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 40d8c3e..c239614 100644 --- a/src/main.rs +++ b/src/main.rs @@ -116,9 +116,7 @@ async fn main() -> Result<()> { let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); info!("Starting server on {addr:#?}"); - let listener = tokio::net::TcpListener::bind("0.0.0.0:3000") - .await - .unwrap_or_else(|error| panic!("{error:#?}")); + let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?; let server = server(&config).await?; From d781cb8bfc98a030a8832ae43ba4dfe921870f61 Mon Sep 17 00:00:00 2001 From: Kehinde Date: Wed, 11 Nov 2026 13:12:38 +0100 Subject: [PATCH 5/5] feat: lots of improvement We create a ProxyClient and implement methods on it. The access-code retry is now a recursive call with a manual retry value set. The default is 5 for a start. I'll observe with logs and see how this holds up --- src/app.rs | 313 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 176 insertions(+), 137 deletions(-) diff --git a/src/app.rs b/src/app.rs index 38a076d..17db6aa 100644 --- a/src/app.rs +++ b/src/app.rs @@ -10,10 +10,11 @@ use reqwest::{self, Client}; use serde::{Deserialize, Serialize}; use serde_email::Email; use std::{ + fmt::Display, io, sync::{Arc, LazyLock}, }; -use tracing::{Instrument, info, info_span}; +use tracing::{Instrument, info_span}; use url::Url; #[derive(Deserialize)] @@ -125,9 +126,11 @@ pub async fn log_app_errors(req: Request, next: Next) -> Response { } response } -pub struct AccessCode(String, u32); -pub fn get_name_and_number(el: &str) -> Result { +#[derive(Serialize, Debug)] +pub struct AccessCode(pub String, pub u32); + +pub fn extract_name_and_number(el: &str) -> Result { static NAME: LazyLock = LazyLock::new(|| Regex::new(r"^\s*(?\D+?)\s+\d+\s*$").unwrap()); static NUMBER: LazyLock = LazyLock::new(|| Regex::new(r"(?\d{5})").unwrap()); @@ -149,71 +152,179 @@ pub fn get_name_and_number(el: &str) -> Result { Ok(AccessCode(name, number)) } -async fn get_access_code( - client: &Client, - create_endpoint: &str, - guest: &Guest, -) -> Result { - let res = client - .post(create_endpoint) - .form(&guest) - .send() - .await?; +pub type Result = std::result::Result; - if !res - .status() - .is_success() - { - let api_error: ApiError = res - .json() +struct ProxyClient { + base_url: String, + http_client: Client, +} + +impl ProxyClient { + pub fn new(base_url: &str) -> Result { + let endpoint = Url::parse(&base_url) + .map_err(|_| AppError::InvalidBaseUrl("Base url is invalid".to_string()))?; + + Ok(Self { + base_url: endpoint.to_string(), + http_client: Client::builder() + .cookie_store(true) + .build()?, + }) + } + + fn get_url(&self, path: P) -> String { + format!( + "{}/{}", + self.base_url + .trim_end_matches("/"), + path + ) + } + + pub async fn get_to_home(&self) -> Result<()> { + let res = self + .http_client + .get(&self.base_url) + .send() .await?; - return Err(AppError::ApiError { - message: api_error.message, - code: api_error.code, - }); + + if !res + .status() + .is_success() + { + let api_error: ApiError = res + .json() + .await?; + return Err(AppError::ApiError { + message: api_error.message, + code: api_error.code, + }); + } + + Ok(()) } - let html = res - .text() - .await?; + pub async fn login(&self, form_data: FormData) -> Result<()> { + let url = self.get_url("login"); - let guest_with_code = get_html_content("h2", &html); + let res = self + .http_client + .post(url) + .form(&form_data) + .send() + .instrument(info_span!("api", step = "logging in...")) + .await?; - // this recompiles the regex in a loop which is a poor pattern - let AccessCode(name, number) = get_name_and_number(&guest_with_code)?; + if !res + .status() + .is_success() + { + let api_error: ApiError = res + .json() + .await?; + return Err(AppError::ApiError { + message: api_error.message, + code: api_error.code, + }); + } - Ok(AccessCode(name, number)) -} + Ok(()) + } -pub type Result = std::result::Result; + pub async fn go_to_create(&self) -> Result<()> { + let url = self.get_url("create"); -pub async fn app(config: AppConfig) -> Result { - let client = reqwest::Client::builder() - .cookie_store(true) - .build()?; - - let res = client - .get( - config - .endpoint - .to_string(), - ) - .send() - .instrument(info_span!("api", step = "checking site...")) - .await?; + let res = self + .http_client + .get(url) + .send() + .instrument(info_span!("api", step = "opening create page")) + .await?; - if !res - .status() - .is_success() - { - let api_error: ApiError = res - .json() + if !res + .status() + .is_success() + { + let api_error: ApiError = res + .json() + .await?; + return Err(AppError::ApiError { + message: api_error.message, + code: api_error.code, + }); + } + Ok(()) + } + + pub async fn get_access_code(&self, guest: &Guest, retries: u32) -> Result { + log::info!("{:?}", retries); + if retries < 1 { + return Err(AppError::ApiError { + message: "could not get code".to_string(), + code: 500, + }); + } + + let url = self.get_url("create"); + let res = self + .http_client + .post(url) + .form(&guest) + .send() .await?; - return Err(AppError::ApiError { - message: api_error.message, - code: api_error.code, - }); + + if !res + .status() + .is_success() + { + let api_error: ApiError = res + .json() + .await?; + return Err(AppError::ApiError { + message: api_error.message, + code: api_error.code, + }); + } + + let html = res + .text() + .await?; + + let guest_with_code = get_html_content("h2", &html); + let AccessCode(name, number) = extract_name_and_number(&guest_with_code)?; + + if name + .trim() + .to_lowercase() + != guest + .guest_name + .trim() + .to_lowercase() + { + log::info!("{:?} retrie(s) left", retries); + let str = format!( + "returned={} expected={} name mismatch, retrying", + name, guest.guest_name + ); + return Box::pin(self.get_access_code(guest, retries - 1)) + .instrument(info_span!("api", span = str)) + .await; + } + + Ok(AccessCode(name, number)) } +} + +pub async fn app(config: AppConfig) -> Result { + let client = ProxyClient::new( + &config + .endpoint + .to_string(), + )?; + + client + .get_to_home() + .await?; let form_data = FormData { user_name: config @@ -222,48 +333,14 @@ pub async fn app(config: AppConfig) -> Result { user_psswrd: config.password, }; - let endpoint = format!("{}/{}", config.endpoint, "login"); - - let res = client - .post(endpoint) - .form(&form_data) - .send() - .instrument(info_span!("api", step = "logging in...")) + client + .login(form_data) .await?; - if !res - .status() - .is_success() - { - let api_error: ApiError = res - .json() - .await?; - return Err(AppError::ApiError { - message: api_error.message, - code: api_error.code, - }); - } - - let create_endpoint = format!("{}/{}", config.endpoint, "create"); - let res = client - .get(create_endpoint.to_string()) - .send() - .instrument(info_span!("api", step = "opening create page")) + client + .go_to_create() .await?; - if !res - .status() - .is_success() - { - let api_error: ApiError = res - .json() - .await?; - return Err(AppError::ApiError { - message: api_error.message, - code: api_error.code, - }); - } - let guest = Guest { guest_name: config .visitor @@ -275,50 +352,12 @@ pub async fn app(config: AppConfig) -> Result { .to_string(), }; - let mut max_retries = 5; - - //shared mutable state - let mut state = String::new(); - - let AccessCode(name, code) = get_access_code(&client, &create_endpoint, &guest) - .instrument(info_span!("api", step = "getting access code...")) + let AccessCode(name, code) = client + .get_access_code(&guest, 5) .await?; - //updated here? - state.push_str(&name); + log::info!("name: {:?} and code: {:?}", name, code); - if max_retries > 0 { - log::info!("{:?}", name); - if state - .trim() - .to_lowercase() - != name - .trim() - .to_lowercase() - { - info!(returned = %state, expected= %&guest.guest_name, "name mismatch, retrying"); - let str = format!( - "returned={} expected={} name mismatch, retrying", - state, &guest.guest_name - ); - let AccessCode(name, _) = get_access_code(&client, &create_endpoint, &guest) - .instrument(info_span!("api", span = str)) - .await?; - state = name; - max_retries -= 1; - } - } - - if max_retries == 0 { - let err_message = format!( - "returned={} expected={} name mismatch", - state, &guest.guest_name - ); - return Err(AppError::ApiError { - message: err_message, - code: 500, - }); - } Ok(code) } @@ -356,7 +395,7 @@ mod tests { #[test] fn it_extracts_name_and_number_from_text() { - let access_code = get_name_and_number("Opeyemi 51402"); + let access_code = extract_name_and_number("Opeyemi 51402"); let AccessCode(name, number) = access_code.unwrap(); assert_eq!(name, "Opeyemi"); assert_eq!(number, 51402) @@ -364,7 +403,7 @@ mod tests { #[test] fn it_extracts_name_when_honorific_is_added() { - let access_code = get_name_and_number("mr obinna 33588"); + let access_code = extract_name_and_number("mr obinna 33588"); let AccessCode(name, number) = access_code.unwrap(); assert_eq!(name, "mr obinna"); assert_eq!(number, 33588)