1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//! Axum [`extractor`](axum::extract) for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape)
//! request.
//!
//! It parses the query parameters returning an [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape)
//! request.
//!
//! Refer to [`Scrape`](crate::servers::http::v1::requests::scrape)  for more
//! information about the returned structure.
//!
//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error)
//! response (`500`) if the query parameters are missing or invalid.
//!
//! **Sample scrape request**
//!
//! <http://0.0.0.0:7070/scrape?info_hash=%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00>
//!
//! **Sample error response**
//!
//! Missing query params for scrape request: <http://0.0.0.0:7070/scrape>
//!
//! ```text
//! d14:failure reason143:Cannot parse query params for scrape request: missing query params for scrape request in src/servers/http/v1/extractors/scrape_request.rs:52:23e
//! ```
//!
//! Invalid query params for scrape request: <http://0.0.0.0:7070/scrape?info_hash=invalid>
//!
//! ```text
//! d14:failure reason235:Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e
//! ```
use std::panic::Location;

use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};

use crate::servers::http::v1::query::Query;
use crate::servers::http::v1::requests::scrape::{ParseScrapeQueryError, Scrape};
use crate::servers::http::v1::responses;

/// Extractor for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape)
/// request.
pub struct ExtractRequest(pub Scrape);

#[async_trait]
impl<S> FromRequestParts<S> for ExtractRequest
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        match extract_scrape_from(parts.uri.query()) {
            Ok(scrape_request) => Ok(ExtractRequest(scrape_request)),
            Err(error) => Err(error.into_response()),
        }
    }
}

fn extract_scrape_from(maybe_raw_query: Option<&str>) -> Result<Scrape, responses::error::Error> {
    if maybe_raw_query.is_none() {
        return Err(responses::error::Error::from(ParseScrapeQueryError::MissingParams {
            location: Location::caller(),
        }));
    }

    let query = maybe_raw_query.unwrap().parse::<Query>();

    if let Err(error) = query {
        return Err(responses::error::Error::from(error));
    }

    let scrape_request = Scrape::try_from(query.unwrap());

    if let Err(error) = scrape_request {
        return Err(responses::error::Error::from(error));
    }

    Ok(scrape_request.unwrap())
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::extract_scrape_from;
    use crate::servers::http::v1::requests::scrape::Scrape;
    use crate::servers::http::v1::responses::error::Error;
    use crate::shared::bit_torrent::info_hash::InfoHash;

    struct TestInfoHash {
        pub bencoded: String,
        pub value: InfoHash,
    }

    fn test_info_hash() -> TestInfoHash {
        TestInfoHash {
            bencoded: "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0".to_owned(),
            value: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(),
        }
    }

    fn assert_error_response(error: &Error, error_message: &str) {
        assert!(
            error.failure_reason.contains(error_message),
            "Error response does not contain message: '{error_message}'. Error: {error:?}"
        );
    }

    #[test]
    fn it_should_extract_the_scrape_request_from_the_url_query_params() {
        let info_hash = test_info_hash();

        let raw_query = format!("info_hash={}", info_hash.bencoded);

        let scrape = extract_scrape_from(Some(&raw_query)).unwrap();

        assert_eq!(
            scrape,
            Scrape {
                info_hashes: vec![info_hash.value],
            }
        );
    }

    #[test]
    fn it_should_extract_the_scrape_request_from_the_url_query_params_with_more_than_one_info_hash() {
        let info_hash = test_info_hash();

        let raw_query = format!("info_hash={}&info_hash={}", info_hash.bencoded, info_hash.bencoded);

        let scrape = extract_scrape_from(Some(&raw_query)).unwrap();

        assert_eq!(
            scrape,
            Scrape {
                info_hashes: vec![info_hash.value, info_hash.value],
            }
        );
    }

    #[test]
    fn it_should_reject_a_request_without_query_params() {
        let response = extract_scrape_from(None).unwrap_err();

        assert_error_response(
            &response,
            "Cannot parse query params for scrape request: missing query params for scrape request",
        );
    }

    #[test]
    fn it_should_reject_a_request_with_a_query_that_cannot_be_parsed() {
        let invalid_query = "param1=value1=value2";
        let response = extract_scrape_from(Some(invalid_query)).unwrap_err();

        assert_error_response(&response, "Cannot parse query params");
    }

    #[test]
    fn it_should_reject_a_request_with_a_query_that_cannot_be_parsed_into_a_scrape_request() {
        let response = extract_scrape_from(Some("param1=value1")).unwrap_err();

        assert_error_response(&response, "Cannot parse query params for scrape request");
    }
}