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
use std::collections::HashMap;

use tracing::*;
use async_trait::async_trait;

use crate::{Sampler, record::{RecordData, ResponseResult}};

pub type HeaderMap = reqwest::header::HeaderMap;
pub type HeaderValue = reqwest::header::HeaderValue;

#[derive(Clone)]
pub struct HttpSampler {
    label: String,
    url: String,
    method: Method,
    headers: HeaderMap,
    body: Option<String>,
}

#[derive(Clone)]
pub enum Method {
    GET,
    POST,
    PUT,
}

impl Method {
    pub fn len(&self) -> u32{
        match self {
            Method::GET => 3,
            Method::POST => 4,
            Method::PUT => 3,
        }
    }
}

impl HttpSampler {
    pub fn new(label: &str, url: &str, method: Method, headers: HeaderMap, body: Option<String>) -> Self {
        Self { label: label.to_string(), url: url.to_string(), method, headers, body }
    }

    fn request_size(&self) -> u32 {
        self.request_line_size() + self.request_headers_size() + self.request_body_size()
    }

    fn request_headers_size(&self) -> u32 {
        let mut size = 0u32;
        for (key, value) in self.headers.clone() {
            match key {
                Some(header_name) => {
                    size = size + (header_name.to_string().len() + value.len() + ":\r\n".len()) as u32;
                },
                None => {},
            }
        }
        size
    }

    fn request_line_size(&self) -> u32 {
        self.method.len() + (self.url.len() + "  HTTP/1.1\r\n".len()) as u32
    }

    fn request_body_size(&self) -> u32 {
        (self.body.clone().unwrap_or("".to_string()).len() + "\r\n".len()) as u32 
    }
}

#[async_trait]
impl Sampler for HttpSampler {
    async fn run(&self) -> RecordData{
        let client = reqwest::Client::new();
        let s = self.clone();
        let start_send_timestamp = chrono::Local::now();
        let resp = match self.method {
            Method::GET => client.get(s.url.clone()).headers(s.headers.clone()).send().await,
            Method::POST => client.post(s.url.clone()).headers(s.headers.clone()).body(s.body.clone().unwrap()).send().await,
            Method::PUT => client.put(s.url.clone()).headers(s.headers.clone()).body(s.body.clone().unwrap()).send().await,
        };
        
        let finish_send_timestamp = chrono::Local::now();
        match resp {
            Ok(r) => {
                let data_type = String::from("text");
                let code = r.status().as_u16();
                let resp_msg = r.status().canonical_reason().unwrap_or("Unknown");
                let success = code < 400u16;
                let fail_msg = if success {
                    None
                } else {
                    Some(resp_msg.to_string())
                };
                let mut resp_headers: HashMap<String, String> = HashMap::new();
                for (h_key, h_val) in r.headers() {
                    resp_headers.insert(h_key.to_string(), h_val.to_str().unwrap().to_string());
                }

                let resp_body = r.text().await.unwrap_or("".to_string());

                RecordData::new(
                    start_send_timestamp.timestamp_millis() as u128,
                    (finish_send_timestamp - start_send_timestamp).num_milliseconds() as u64,
                    self.label.clone(),
                    code,
                    resp_msg.into(),
                    "".to_string(),
                    data_type,
                    success,
                    fail_msg,
                    resp_body.len() as u64,
                    s.request_size() as u64,
                    0,
                    0,
                    s.url,
                    (finish_send_timestamp - start_send_timestamp).num_milliseconds() as u64,
                    0,
                    0,
                    Some(ResponseResult::new(resp_headers, resp_body)),
                )

            },
            Err(e) => {
                error!("failed! --> {}", e.to_string());
                RecordData::new(
                    start_send_timestamp.timestamp_millis() as u128,
                    (finish_send_timestamp - start_send_timestamp).num_milliseconds() as u64,
                    self.label.clone(),
                    0,
                    "no data".to_string(),
                    "".to_string(),
                    "no data".to_string(),
                    false,
                    Some(e.to_string()),
                    0u64,
                    s.request_size() as u64,
                    0,
                    0,
                    s.url,
                    (finish_send_timestamp - start_send_timestamp).num_milliseconds() as u64,
                    0,
                    0,
                    None,
                )
            },
        }
    }

}