Skip to content

Commit

Permalink
fix: was incorrectly accepting arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
zleyyij committed Jan 29, 2024
1 parent d89eda6 commit 9ea3039
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 24 deletions.
13 changes: 9 additions & 4 deletions src/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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);
Expand All @@ -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 {
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/cpu/intel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(","));
}
```
*/
Expand Down
44 changes: 25 additions & 19 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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) {
Expand All @@ -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()
);
}
}

Expand All @@ -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<String>,
}

Expand All @@ -53,36 +59,34 @@ 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<AppState>, Json(query): Json<CpuQuery>) -> Json<Cpu> {
async fn get_cpu_handler(
State(state): State<AppState>,
Query(query): Query<CpuQuery>,
) -> Json<Cpu> {
// just to get type annotations working
let mut state: AppState = state;

Json(state.cpu_cache.find(&query.name))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 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;
Expand All @@ -92,7 +96,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

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(())
Expand Down

0 comments on commit 9ea3039

Please sign in to comment.