diff --git a/src/cpu.rs b/src/cpu.rs index 64c91b8..52d4cc4 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -26,7 +26,6 @@ pub struct CpuCache { } impl CpuCache { - /// Create a new cache and parse the cpu databases into memory pub fn new() -> Self { let intel_cpus = get_intel_cpus(); @@ -44,7 +43,7 @@ impl CpuCache { /// Given a string that contains the inexact name of a cpu, try to find the best fit /// and return it. For example, it might take an input of "AMD Ryzen 5 3600 6-Core Processor", /// and return the entry with a `name` of "AMD Ryzen™ 5 3600". - /// + /// /// A mutable reference is required so that the comparison cache can be shared between calls pub fn find(&mut self, input: &str) -> Cpu { let input_model = find_model(input); @@ -56,7 +55,12 @@ impl CpuCache { }; // first see if a comparison has already been made if let Some(cpu_name) = self.comparison_cache.get(input) { - return cpus.into_iter().filter(|cpu| cpu.name == cpu_name.to_string()).nth(0).unwrap().clone() + return cpus + .into_iter() + .filter(|cpu| cpu.name == cpu_name.to_string()) + .nth(0) + .unwrap() + .clone(); } // performing a full search if the cpu isn't found in the cache let mut best_fit = Cpu { @@ -74,7 +78,8 @@ impl CpuCache { best_fit = cpu.clone(); } } - self.comparison_cache.insert(input.to_string(), best_fit.name.clone()); + self.comparison_cache + .insert(input.to_string(), best_fit.name.clone()); debug!( "Given the input: {:?}, the CPU {:?} was found", input, best_fit.name diff --git a/src/cpu/intel/mod.rs b/src/cpu/intel/mod.rs index 74744a1..537657e 100644 --- a/src/cpu/intel/mod.rs +++ b/src/cpu/intel/mod.rs @@ -38,7 +38,7 @@ let ids = [PASTE_IDS_HERE]; }, []); for (const chunk of chunks) { - console.log("https://ark.intel.com/content/www/us/en/ark/compare.html?productIds=" + chunk.join(",")); + console.log("https://ark.intel.com/content/www/us/en/ark/compare.html?productIds=" + chunk.join(",")); } ``` */ diff --git a/src/main.rs b/src/main.rs index 0fcd83c..8d5cf38 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,13 +1,14 @@ mod cpu; +use axum::extract::Query; use axum::{extract::State, routing::get, Json, Router}; +use chrono::Local; +use clap::Parser; +use colored::*; use cpu::{Cpu, CpuCache}; use log::info; -use log::{Record, Metadata, Level, LevelFilter}; +use log::{Level, LevelFilter, Metadata, Record}; use serde::{Deserialize, Serialize}; -use colored::*; -use chrono::Local; -use clap::Parser; use std::env; /// https://docs.rs/log/latest/log/#implementing-a-logger struct SimpleLogger; @@ -16,7 +17,7 @@ impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { // determine at what level things will be logged at // TODO: make this configurable via environment variable - metadata.level() <= Level::Error + metadata.level() <= Level::Info } fn log(&self, record: &Record) { @@ -28,7 +29,12 @@ impl log::Log for SimpleLogger { Level::Debug => format!("{}", record.level()).bold().green(), Level::Trace => format!("{}", record.level()).bold().cyan(), }; - println!("({})[{}] {}", Local::now().to_rfc2822(), level, record.args()); + println!( + "({})[{}] {}", + Local::now().to_rfc2822(), + level, + record.args() + ); } } @@ -37,7 +43,7 @@ impl log::Log for SimpleLogger { #[derive(Parser)] struct Args { - #[arg(short='p', long="port")] + #[arg(short = 'p', long = "port")] port: Option, } @@ -53,18 +59,15 @@ struct CpuQuery { pub name: String, } -/// This handler accepts a json in the form of a [CpuQuery] -/// ```json -/// { -/// "name": "SEARCH_QUERY" -/// } -/// ``` +/// This handler accepts a `GET` request to `/api/cpus/?name=[CPU_NAME]`. /// It relies on a globally shared [AppState] to re-use the cpu cache, and responds to the request with a serialized [Cpu]. /// It will always attempt to find a cpu, and should always return a cpu. The correctness of the return value is not guaranteed. -async fn get_cpu_handler(State(state): State, Json(query): Json) -> Json { +async fn get_cpu_handler( + State(state): State, + Query(query): Query, +) -> Json { // just to get type annotations working let mut state: AppState = state; - Json(state.cpu_cache.find(&query.name)) } @@ -72,17 +75,18 @@ async fn get_cpu_handler(State(state): State, Json(query): Json Result<(), Box> { // initialize logging log::set_logger(&LOGGER) - .map(|()| log::set_max_level(LevelFilter::Info)).unwrap(); + .map(|()| log::set_max_level(LevelFilter::Info)) + .unwrap(); let cli_args = Args::parse(); info!("Application started"); // parse command line arguments // create a new http router and register respective routes and handlers let app = Router::new() - .route("/api/cpus", get(get_cpu_handler)) + .route("/api/cpus/", get(get_cpu_handler)) .with_state(AppState { cpu_cache: CpuCache::new(), }); - + let mut port: String = String::from("3000"); if let Ok(value) = env::var("HWAPI_PORT") { port = value; @@ -92,7 +96,9 @@ async fn main() -> Result<(), Box> { info!("Listening on port {}", port); // run the app - let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await.unwrap(); + let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)) + .await + .unwrap(); axum::serve(listener, app).await.unwrap(); Ok(())