Skip to content

Commit

Permalink
refactor(api): [torrust#143] extract and rename functions
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jan 13, 2023
1 parent 072f3d7 commit 436bc96
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 48 deletions.
98 changes: 65 additions & 33 deletions src/apis/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use crate::api::resource::stats::Stats;
use crate::api::resource::torrent::{ListItem, Torrent};
use crate::protocol::info_hash::InfoHash;
use crate::tracker::auth::KeyId;
use crate::tracker::services::statistics::get_metrics;
use crate::tracker::services::torrent::{get_torrent_info, get_torrents, Pagination};
use crate::tracker::services::statistics::{get_metrics, TrackerMetrics};
use crate::tracker::services::torrent::{get_torrent_info, get_torrents, BasicInfo, Info, Pagination};
use crate::tracker::Tracker;

/* code-review:
Expand Down Expand Up @@ -91,6 +91,18 @@ pub enum ActionStatus<'a> {

// Resource responses

fn response_stats(tracker_metrics: TrackerMetrics) -> Json<Stats> {
Json(Stats::from(tracker_metrics))
}

fn response_torrent_list(basic_infos: &[BasicInfo]) -> Json<Vec<ListItem>> {
Json(ListItem::new_vec(basic_infos))
}

fn response_torrent_info(info: Info) -> Response {
Json(Torrent::from(info)).into_response()
}

fn response_auth_key(auth_key: &AuthKey) -> Response {
(
StatusCode::OK,
Expand Down Expand Up @@ -120,6 +132,10 @@ fn response_invalid_info_hash_param(info_hash: &str) -> Response {
))
}

fn response_invalid_auth_key_param(invalid_key: &str) -> Response {
response_bad_request(&format!("Invalid auth key id param \"{invalid_key}\""))
}

fn response_bad_request(body: &str) -> Response {
(
StatusCode::BAD_REQUEST,
Expand All @@ -129,7 +145,35 @@ fn response_bad_request(body: &str) -> Response {
.into_response()
}

fn response_err(reason: String) -> Response {
fn response_torrent_not_known() -> Response {
Json(json!("torrent not known")).into_response()
}

fn response_failed_to_remove_torrent_from_whitelist() -> Response {
response_unhandled_rejection("failed to remove torrent from whitelist".to_string())
}

fn response_failed_to_whitelist_torrent() -> Response {
response_unhandled_rejection("failed to whitelist torrent".to_string())
}

fn response_failed_to_reload_whitelist() -> Response {
response_unhandled_rejection("failed to reload whitelist".to_string())
}

fn response_failed_to_generate_key() -> Response {
response_unhandled_rejection("failed to generate key".to_string())
}

fn response_failed_to_delete_key() -> Response {
response_unhandled_rejection("failed to delete key".to_string())
}

fn response_failed_to_reload_keys() -> Response {
response_unhandled_rejection("failed to reload keys".to_string())
}

fn response_unhandled_rejection(reason: String) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
Expand All @@ -139,25 +183,19 @@ fn response_err(reason: String) -> Response {
}

pub async fn get_stats_handler(State(tracker): State<Arc<Tracker>>) -> Json<Stats> {
Json(Stats::from(get_metrics(tracker.clone()).await))
response_stats(get_metrics(tracker.clone()).await)
}

#[derive(Deserialize)]
pub struct InfoHashParam(String);

pub async fn get_torrent_handler(State(tracker): State<Arc<Tracker>>, Path(info_hash): Path<InfoHashParam>) -> Response {
let parsing_info_hash_result = InfoHash::from_str(&info_hash.0);

match parsing_info_hash_result {
match InfoHash::from_str(&info_hash.0) {
Err(_) => response_invalid_info_hash_param(&info_hash.0),
Ok(info_hash) => {
let optional_torrent_info = get_torrent_info(tracker.clone(), &info_hash).await;

match optional_torrent_info {
Some(info) => Json(Torrent::from(info)).into_response(),
None => Json(json!("torrent not known")).into_response(),
}
}
Ok(info_hash) => match get_torrent_info(tracker.clone(), &info_hash).await {
Some(info) => response_torrent_info(info),
None => response_torrent_not_known(),
},
}
}

Expand All @@ -172,26 +210,24 @@ pub async fn get_torrents_handler(
State(tracker): State<Arc<Tracker>>,
pagination: Query<PaginationParams>,
) -> Json<Vec<ListItem>> {
Json(ListItem::new_vec(
response_torrent_list(
&get_torrents(
tracker.clone(),
&Pagination::new_with_options(pagination.0.offset, pagination.0.limit),
)
.await,
))
)
}

pub async fn add_torrent_to_whitelist_handler(
State(tracker): State<Arc<Tracker>>,
Path(info_hash): Path<InfoHashParam>,
) -> Response {
let parsing_info_hash_result = InfoHash::from_str(&info_hash.0);

match parsing_info_hash_result {
match InfoHash::from_str(&info_hash.0) {
Err(_) => response_invalid_info_hash_param(&info_hash.0),
Ok(info_hash) => match tracker.add_torrent_to_whitelist(&info_hash).await {
Ok(..) => response_ok(),
Err(..) => response_err("failed to whitelist torrent".to_string()),
Err(..) => response_failed_to_whitelist_torrent(),
},
}
}
Expand All @@ -200,29 +236,27 @@ pub async fn remove_torrent_from_whitelist_handler(
State(tracker): State<Arc<Tracker>>,
Path(info_hash): Path<InfoHashParam>,
) -> Response {
let parsing_info_hash_result = InfoHash::from_str(&info_hash.0);

match parsing_info_hash_result {
match InfoHash::from_str(&info_hash.0) {
Err(_) => response_invalid_info_hash_param(&info_hash.0),
Ok(info_hash) => match tracker.remove_torrent_from_whitelist(&info_hash).await {
Ok(..) => response_ok(),
Err(..) => response_err("failed to remove torrent from whitelist".to_string()),
Err(..) => response_failed_to_remove_torrent_from_whitelist(),
},
}
}

pub async fn reload_whitelist_handler(State(tracker): State<Arc<Tracker>>) -> Response {
match tracker.load_whitelist().await {
Ok(..) => response_ok(),
Err(..) => response_err("failed to reload whitelist".to_string()),
Err(..) => response_failed_to_reload_whitelist(),
}
}

pub async fn generate_auth_key_handler(State(tracker): State<Arc<Tracker>>, Path(seconds_valid_or_key): Path<u64>) -> Response {
let seconds_valid = seconds_valid_or_key;
match tracker.generate_auth_key(Duration::from_secs(seconds_valid)).await {
Ok(auth_key) => response_auth_key(&AuthKey::from(auth_key)),
Err(_) => response_err("failed to generate key".to_string()),
Err(_) => response_failed_to_generate_key(),
}
}

Expand All @@ -233,21 +267,19 @@ pub async fn delete_auth_key_handler(
State(tracker): State<Arc<Tracker>>,
Path(seconds_valid_or_key): Path<KeyIdParam>,
) -> Response {
let key_id = KeyId::from_str(&seconds_valid_or_key.0);

match key_id {
Err(_) => response_bad_request(&format!("Invalid auth key id param \"{}\"", seconds_valid_or_key.0)),
match KeyId::from_str(&seconds_valid_or_key.0) {
Err(_) => response_invalid_auth_key_param(&seconds_valid_or_key.0),
Ok(key_id) => match tracker.remove_auth_key(&key_id.to_string()).await {
Ok(_) => response_ok(),
Err(_) => response_err("failed to delete key".to_string()),
Err(_) => response_failed_to_delete_key(),
},
}
}

pub async fn reload_keys_handler(State(tracker): State<Arc<Tracker>>) -> Response {
match tracker.load_keys().await {
Ok(..) => response_ok(),
Err(..) => response_err("failed to reload keys".to_string()),
Err(..) => response_failed_to_reload_keys(),
}
}

Expand Down
14 changes: 13 additions & 1 deletion tests/api/asserts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub async fn assert_torrent_not_known(response: Response) {
assert_eq!(response.text().await.unwrap(), "\"torrent not known\"");
}

pub async fn assert_invalid_infohash(response: Response, invalid_infohash: &str) {
pub async fn assert_invalid_infohash_param(response: Response, invalid_infohash: &str) {
assert_bad_request(
response,
&format!(
Expand All @@ -86,6 +86,18 @@ pub async fn assert_invalid_infohash(response: Response, invalid_infohash: &str)
.await;
}

pub async fn assert_invalid_auth_key_param(response: Response, invalid_auth_key: &str) {
assert_bad_request(response, &format!("Invalid auth key id param \"{}\"", &invalid_auth_key)).await;
}

pub async fn assert_invalid_key_duration_param(response: Response, invalid_key_duration: &str) {
assert_bad_request(
response,
&format!("Invalid URL: Cannot parse `\"{invalid_key_duration}\"` to a `u64`"),
)
.await;
}

pub async fn assert_token_not_valid(response: Response) {
assert_unhandled_rejection(response, "token not valid").await;
}
Expand Down
25 changes: 11 additions & 14 deletions tests/tracker_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,7 @@ mod tracker_apis {

use super::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found};
use crate::api::asserts::{
assert_bad_request, assert_invalid_infohash, assert_not_found, assert_token_not_valid, assert_torrent_info,
assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info,
assert_torrent_list, assert_torrent_not_known, assert_unauthorized,
};
use crate::api::client::{Client, Query, QueryParam};
Expand Down Expand Up @@ -1123,7 +1123,7 @@ mod tracker_apis {
.get_torrent(invalid_infohash)
.await;

assert_invalid_infohash(response, invalid_infohash).await;
assert_invalid_infohash_param(response, invalid_infohash).await;
}

for invalid_infohash in &invalid_infohashes_returning_not_found() {
Expand Down Expand Up @@ -1165,8 +1165,8 @@ mod tracker_apis {
use super::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found};
use crate::api::asserts::{
assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist,
assert_failed_to_whitelist_torrent, assert_invalid_infohash, assert_not_found, assert_ok, assert_token_not_valid,
assert_unauthorized,
assert_failed_to_whitelist_torrent, assert_invalid_infohash_param, assert_not_found, assert_ok,
assert_token_not_valid, assert_unauthorized,
};
use crate::api::client::Client;
use crate::api::connection_info::{connection_with_invalid_token, connection_with_no_token};
Expand Down Expand Up @@ -1250,7 +1250,7 @@ mod tracker_apis {
.whitelist_a_torrent(invalid_infohash)
.await;

assert_invalid_infohash(response, invalid_infohash).await;
assert_invalid_infohash_param(response, invalid_infohash).await;
}

for invalid_infohash in &invalid_infohashes_returning_not_found() {
Expand Down Expand Up @@ -1300,7 +1300,7 @@ mod tracker_apis {
.remove_torrent_from_whitelist(invalid_infohash)
.await;

assert_invalid_infohash(response, invalid_infohash).await;
assert_invalid_infohash_param(response, invalid_infohash).await;
}

for invalid_infohash in &invalid_infohashes_returning_not_found() {
Expand Down Expand Up @@ -1396,8 +1396,9 @@ mod tracker_apis {
use torrust_tracker::tracker::auth::Key;

use crate::api::asserts::{
assert_auth_key_utf8, assert_bad_request, assert_failed_to_delete_key, assert_failed_to_generate_key,
assert_failed_to_reload_keys, assert_ok, assert_token_not_valid, assert_unauthorized,
assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys,
assert_invalid_auth_key_param, assert_invalid_key_duration_param, assert_ok, assert_token_not_valid,
assert_unauthorized,
};
use crate::api::client::Client;
use crate::api::connection_info::{connection_with_invalid_token, connection_with_no_token};
Expand Down Expand Up @@ -1458,11 +1459,7 @@ mod tracker_apis {
.post(&format!("key/{}", &invalid_key_duration))
.await;

assert_bad_request(
response,
&format!("Invalid URL: Cannot parse `\"{invalid_key_duration}\"` to a `u64`"),
)
.await;
assert_invalid_key_duration_param(response, invalid_key_duration).await;
}
}

Expand Down Expand Up @@ -1517,7 +1514,7 @@ mod tracker_apis {
.delete_auth_key(invalid_auth_key_id)
.await;

assert_bad_request(response, &format!("Invalid auth key id param \"{}\"", &invalid_auth_key_id)).await;
assert_invalid_auth_key_param(response, invalid_auth_key_id).await;
}
}

Expand Down

0 comments on commit 436bc96

Please sign in to comment.