From e614b1eec14d03e72b6e9fba15129973df1dd704 Mon Sep 17 00:00:00 2001 From: Kjetil Orbekk Date: Mon, 3 Feb 2020 23:00:23 -0500 Subject: Fix rust warnings by removing dead code --- Cargo.lock | 11 ----- Cargo.toml | 4 +- src/db.rs | 43 +++++++++----------- src/error.rs | 38 +++++++++++------ src/importer.rs | 123 +++++++++++++++----------------------------------------- src/models.rs | 8 ++-- src/schema.rs | 7 +--- src/server.rs | 33 +++++++-------- src/strava.rs | 14 ++----- 9 files changed, 102 insertions(+), 179 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eaca1d3..a55f0f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1069,8 +1069,6 @@ dependencies = [ "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", "threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", - "timer 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1564,14 +1562,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "timer" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "tokio" version = "0.2.11" @@ -2124,7 +2114,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" "checksum threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e2f0c90a5f3459330ac8bc0d2f879c693bb7a2f59689c1083fc4ef83834da865" "checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" -"checksum timer 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "31d42176308937165701f50638db1c31586f183f1aab416268216577aec7306b" "checksum tokio 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8fdd17989496f49cdc57978c96f0c9fe5e4a58a8bddc6813c449a4624f6a030b" "checksum tokio-tls 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7bde02a3a5291395f59b06ec6945a3077602fac2b07eeeaf0dee2122f3619828" "checksum tokio-util 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "571da51182ec208780505a32528fc5512a8fe1443ab960b3f2f3ef093cd16930" diff --git a/Cargo.toml b/Cargo.toml index d68ab83..0184cb5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,4 @@ rand = "0.7" chrono = { version = "0.4", features = ["serde"] } log = "0.4" fern = { version = "0.5", features = ["colored"] } -threadpool = "1.7" -timer = "0.2" -time = "0.1" \ No newline at end of file +threadpool = "1.7" \ No newline at end of file diff --git a/src/db.rs b/src/db.rs index f3a261c..548ca99 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,14 +1,13 @@ use crate::error::Error; use crate::models; use bcrypt; +use chrono::DateTime; +use chrono::Utc; use diesel::connection::Connection; use diesel::pg::PgConnection; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::RunQueryDsl; -use std::time::Duration; -use chrono::DateTime; -use chrono::Utc; pub const COST: u32 = 10; @@ -102,9 +101,7 @@ pub fn get_strava_token( Ok(token) } -pub fn insert_task( - conn: &PgConnection, - task: &models::NewTask) -> Result { +pub fn insert_task(conn: &PgConnection, task: &models::NewTask) -> Result { use crate::schema::tasks; let id = diesel::insert_into(tasks::table) .values(task) @@ -113,38 +110,36 @@ pub fn insert_task( Ok(id) } -fn update_task_inner(conn: &PgConnection, task: &models::Task) - -> Result { +fn update_task_inner(conn: &PgConnection, task: &models::Task) -> Result { use crate::schema::tasks; - diesel::delete(tasks::table.filter(tasks::columns::id.eq(task.id))) - .execute(conn)?; + diesel::delete(tasks::table.filter(tasks::columns::id.eq(task.id))).execute(conn)?; - let new_id = insert_task(conn, &models::NewTask { - start_at: task.start_at, - state: task.state, - username: &task.username, - payload: &task.payload, - })?; + let new_id = insert_task( + conn, + &models::NewTask { + start_at: task.start_at, + state: task.state, + username: &task.username, + payload: &task.payload, + }, + )?; - let new_task = tasks::table.find(new_id) - .get_result::(conn)?; + let new_task = tasks::table.find(new_id).get_result::(conn)?; Ok(new_task) } -fn update_task(conn: &PgConnection, task: &models::Task) -> Result { - conn.transaction(|| { - update_task_inner(conn, task) - }) +pub fn update_task(conn: &PgConnection, task: &models::Task) -> Result { + conn.transaction(|| update_task_inner(conn, task)) } pub fn take_task( conn: &PgConnection, state: models::TaskState, start_before: DateTime, - eta: DateTime) - -> Result { + eta: DateTime, +) -> Result { use crate::schema::tasks; conn.transaction(|| { diff --git a/src/error.rs b/src/error.rs index 75a7568..d27966a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,7 @@ use std::error::Error as StdError; use std::fmt; #[derive(Debug)] -pub struct StravaApiError{ +pub struct StravaApiError { status: reqwest::StatusCode, code: String, field: String, @@ -17,12 +17,23 @@ impl StravaApiError { pub fn new(status: reqwest::StatusCode, value: Value) -> StravaApiError { let first_error = &value["errors"][0]; - let code = first_error["code"].as_str().unwrap_or("unknown").to_string(); - let field = first_error["field"].as_str().unwrap_or("unknown").to_string(); + let code = first_error["code"] + .as_str() + .unwrap_or("unknown") + .to_string(); + let field = first_error["field"] + .as_str() + .unwrap_or("unknown") + .to_string(); - StravaApiError { status, code, field, value } + StravaApiError { + status, + code, + field, + value, + } } - } +} impl fmt::Display for StravaApiError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -37,9 +48,9 @@ mod tests { fn strava_api_error_unknown() { let data = r#""insane input""#; let json = serde_json::from_str(data).unwrap(); - let error = Error::StravaApiError(StravaApiError::new(reqwest::StatusCode::UNAUTHORIZED, json)); - assert_eq!("field 'unknown' has error 'unknown'", - format!("{}", error)); + let error = + Error::StravaApiError(StravaApiError::new(reqwest::StatusCode::UNAUTHORIZED, json)); + assert_eq!("field 'unknown' has error 'unknown'", format!("{}", error)); } #[test] @@ -54,9 +65,12 @@ mod tests { "message":"Authorization Error" }"#; let json = serde_json::from_str(data).unwrap(); - let error = Error::StravaApiError(StravaApiError::new(reqwest::StatusCode::UNAUTHORIZED, json)); - assert_eq!("field 'access_token' has error 'invalid'", - format!("{}", error)); + let error = + Error::StravaApiError(StravaApiError::new(reqwest::StatusCode::UNAUTHORIZED, json)); + assert_eq!( + "field 'access_token' has error 'invalid'", + format!("{}", error) + ); } } @@ -111,7 +125,7 @@ impl From for Error { fn from(e: DieselErr) -> Error { match e { DieselErr::NotFound => Error::NotFound, - e => Error::DieselError(e) + e => Error::DieselError(e), } } } diff --git a/src/importer.rs b/src/importer.rs index 6909350..05d56fd 100644 --- a/src/importer.rs +++ b/src/importer.rs @@ -1,26 +1,19 @@ +use chrono::Utc; use diesel::PgConnection; -use std::sync::mpsc::channel; -use std::sync::mpsc::Receiver; -use std::sync::mpsc::Sender; +use serde::Deserialize; +use serde::Serialize; use std::sync::Arc; use std::sync::Mutex; use std::sync::RwLock; -use threadpool::ThreadPool; -use chrono::Utc; -use timer::Timer; -use timer::Guard; -use std::time::Instant; -use std::time::Duration; use std::thread; -use serde::Deserialize; -use serde::Serialize; +use std::time::Duration; +use std::time::Instant; +use threadpool::ThreadPool; -use crate::error::Error; use crate::db; +use crate::error::Error; use crate::models; use crate::strava; -use crate::strava::StravaApi; -use crate::Params; pub const WORKERS: usize = 10; pub const EMPTY_PARAMS: &[(&str, &str)] = &[]; @@ -30,15 +23,6 @@ pub enum Command { ImportStravaUser { username: String }, } -macro_rules! clone { - ( [ $( $i:ident ),* ] $e:expr ) => { - { - $(let $i = $i.clone();)* - $e - } - } -} - pub struct ImporterSharedData { strava: RwLock, pool: Mutex, @@ -50,9 +34,7 @@ pub struct Importer { shared: Arc>, } -fn run_periodically( - shared: Arc>, - period: Duration) { +fn run_periodically(shared: Arc>, period: Duration) { let sleep_time = Duration::from_millis(1000); let mut now = Instant::now(); loop { @@ -69,40 +51,34 @@ fn run_periodically( } } - fn handle_one_task( - shared: Arc>) -> Result { + shared: Arc>, +) -> Result { let task = { let conn = shared.conn.lock().unwrap(); let now = Utc::now(); let eta = now + chrono::Duration::seconds(5); - db::take_task(&conn, - models::TaskState::NEW, - now, - eta)? + db::take_task(&conn, models::TaskState::NEW, now, eta)? }; let command = serde_json::from_value(task.payload.clone())?; match command { - Command::ImportStravaUser{ username } => { - import_strava_user(shared, username.as_str())? - }, + Command::ImportStravaUser { username } => import_strava_user(shared, username.as_str())?, } Ok(task) } -fn handle_tasks( - shared: Arc>) { +fn handle_tasks(shared: Arc>) { let mut done = false; while !done { match handle_one_task(shared.clone()) { Err(Error::NotFound) => { info!("No more tasks"); done = true; - }, + } Err(e) => { error!("Error handling task: {}", e); } @@ -138,13 +114,15 @@ impl Importer { } pub fn join(&self) { - self.shared.pool.lock().expect("FIX").join() + *self.shared.running.lock().unwrap() = false; + self.shared.pool.lock().unwrap().join(); } } fn import_strava_user( shared: Arc>, - username: &str) -> Result<(), Error> { + username: &str, +) -> Result<(), Error> { let strava = shared.strava.read().unwrap(); let user = db::get_user(&shared.conn.lock().unwrap(), username)?; @@ -157,29 +135,36 @@ fn import_strava_user( for page in 1.. { let params = [ ("page", &format!("{}", page)[..]), - ("per_page", &format!("{}", per_page)[..]) + ("per_page", &format!("{}", per_page)[..]), ]; - let result = strava - .get("/athlete/activities", &token.access_token, ¶ms[..])?; + let result = strava.get("/athlete/activities", &token.access_token, ¶ms[..])?; - let result = result.as_array().ok_or( - Error::UnexpectedJson(result.clone()))?; + let result = result + .as_array() + .ok_or(Error::UnexpectedJson(result.clone()))?; for activity in result { - info!("activity id: {} start: {}", activity["id"], activity["start_date"]); + info!( + "activity id: {} start: {}", + activity["id"], activity["start_date"] + ); } if result.len() < per_page { break; } thread::sleep(Duration::from_secs(1)); - }; + } Err(Error::InternalError) } -fn get_or_refresh_token(strava: &Strava, conn: &PgConnection, user: &models::User) -> Result { +fn get_or_refresh_token( + strava: &Strava, + conn: &PgConnection, + user: &models::User, +) -> Result { let mut token = db::get_strava_token(&conn, &user).expect("FIX"); if token.expires_at < Utc::now() { @@ -190,45 +175,3 @@ fn get_or_refresh_token(strava: &Strava, conn: &PgCon Ok(token) } - -// fn handle_command(state: Importer, command: Command) { -// info!("handle_command {:?}", command); -// match command { -// Command::ImportStravaUser(user) => import_strava_user(state, user), -// Command::Quit => (), -// } -// } - -// fn receive_commands(state: Importer) { -// info!("receive_commands"); -// match (|| -> Result<(), Box> { -// let rx = state.rx.lock()?; -// let mut command = rx.recv()?; -// loop { -// info!("got command: {:?}", command); -// let state0 = state.clone(); -// state.pool.execute(move || handle_command(state0, command)); -// command = rx.recv()?; -// } -// })() { -// Ok(()) => (), -// Err(e) => { -// error!("receive_commands: {:?}", e); -// () -// } -// } -// } - -// pub fn run(pool: ThreadPool, conn: PgConnection, params: &Params) -> Sender { -// let (tx, rx0) = channel(); -// let importer = Arc::new(Importer { -// pool: Mutex::new(pool.clone()), -// conn: Mutex::new(conn), -// strava: RwLock::new(strava::StravaImpl::new( -// params.strava_client_id.clone(), params.strava_client_secret.clone())), -// rx: Mutex::new(rx0), -// }); -// // pool.execute(move || receive_commands(state)); -// pool.execute(clone! { [importer] move || importer.run() }); -// tx -// } diff --git a/src/models.rs b/src/models.rs index 0b7e5db..3d7eb24 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,18 +1,18 @@ -use crate::schema::tasks; use crate::schema::config; use crate::schema::strava_tokens; +use crate::schema::tasks; use crate::schema::users; use chrono::DateTime; use chrono::Utc; -use std::fmt; -use serde_json::Value; -use diesel::pg::Pg; use diesel::deserialize; use diesel::deserialize::FromSql; +use diesel::pg::Pg; use diesel::serialize; use diesel::serialize::Output; use diesel::serialize::ToSql; use diesel::sql_types; +use serde_json::Value; +use std::fmt; use std::io::Write; #[derive(PartialEq, Debug, Clone, Copy, AsExpression, FromSqlRow)] diff --git a/src/schema.rs b/src/schema.rs index 8748f3c..e605bda 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -36,9 +36,4 @@ table! { joinable!(strava_tokens -> users (username)); joinable!(tasks -> users (username)); -allow_tables_to_appear_in_same_query!( - config, - strava_tokens, - tasks, - users, -); +allow_tables_to_appear_in_same_query!(config, strava_tokens, tasks, users,); diff --git a/src/server.rs b/src/server.rs index f0dd591..9c5618b 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,3 +1,4 @@ +use chrono::Utc; use rocket::config::Config; use rocket::config::Environment; use rocket::config::Value; @@ -13,12 +14,8 @@ use rocket::request::Request; use rocket::response::Redirect; use rocket::State; use rocket_contrib::templates::Template; -use std::collections::HashMap; -use std::sync::mpsc::Sender; -use std::sync::Mutex; -use threadpool::ThreadPool; -use chrono::Utc; use serde_json::to_value; +use std::collections::HashMap; use crate::db; use crate::error::Error; @@ -133,20 +130,20 @@ fn link_strava_callback( } #[get("/import_strava")] -fn import_strava( - conn: Db, - user: LoggedInUser, -) -> Result<(), Error> { +fn import_strava(conn: Db, user: LoggedInUser) -> Result<(), Error> { let user = db::get_user(&*conn, &user.username)?; - let command = - importer::Command::ImportStravaUser { username: user.username.clone() }; - db::insert_task(&conn, - &models::NewTask { - start_at: Utc::now(), - state: models::TaskState::NEW, - username: user.username.as_str(), - payload: &to_value(command)?, - })?; + let command = importer::Command::ImportStravaUser { + username: user.username.clone(), + }; + db::insert_task( + &conn, + &models::NewTask { + start_at: Utc::now(), + state: models::TaskState::NEW, + username: user.username.as_str(), + payload: &to_value(command)?, + }, + )?; Ok(()) } diff --git a/src/strava.rs b/src/strava.rs index ff59c66..b601b04 100644 --- a/src/strava.rs +++ b/src/strava.rs @@ -44,9 +44,7 @@ pub trait StravaApi: Sync + Send { params: &[(&str, &str)], ) -> Result; - fn refresh_token( - &self, - token: &Token) -> Result; + fn refresh_token(&self, token: &Token) -> Result; } pub struct StravaImpl { @@ -93,9 +91,7 @@ impl StravaApi for StravaImpl { Ok(json) } - fn refresh_token( - &self, - token: &Token) -> Result { + fn refresh_token(&self, token: &Token) -> Result { let uri = format!("{}{}{}", self.base_url, self.api_url, "/oauth/token"); let params = [ ("client_id", self.client_id.as_str()), @@ -103,11 +99,7 @@ impl StravaApi for StravaImpl { ("grant_type", "refresh_token"), ("refresh_token", token.refresh_token.as_str()), ]; - let response = self - .client - .post(&uri) - .form(¶ms) - .send()?; + let response = self.client.post(&uri).form(¶ms).send()?; info!("StravaApi::refresh_token returned {:?}", response); let status = response.status(); let json: Value = response.json()?; -- cgit v1.2.3