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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! Web-service mocking library and server

extern crate url;
#[macro_use]
extern crate log;
extern crate http;
extern crate iron;
extern crate regex;
extern crate serde_json;
#[cfg(test)]
#[macro_use]
extern crate hyper;

mod cache_middleware;
mod error;
mod forward_middleware;
mod log_middleware;
mod request;
mod response;
mod result;

/// Control how you store cached requests
pub mod storage;

pub use crate::{
    cache_middleware::{CacheMiddleware, ResponseCache},
    error::{Error, UtilError},
    forward_middleware::{ForwardMiddleware, ProxyResponse},
};

use crate::{
    forward_middleware::ProxyLoad,
    request::{ParodyRequest, RequestLogItem},
    result::Result,
};

use hyper::net::HttpListener;
use std::{
    net::{IpAddr, SocketAddr},
    path::{Path, PathBuf},
    str::FromStr,
    sync::{Arc, Mutex},
};

fn handle_request(req: &mut iron::Request) -> iron::IronResult<iron::Response> {
    trace!("Handling request: {} {}", req.method, req.url);

    req.extensions
        .get::<persistent::Write<RequestStorage>>()
        .map(|a_storage| {
            a_storage
                .lock()
                .unwrap()
                .push(Box::new(RequestLogItem::from(req as &iron::Request)));
            debug!("Logged request: {} {}", req.method, req.url);
        });

    let proxy = req
        .extensions
        .remove::<ProxyResponse>()
        .expect("Proxy response should be always found");

    let response_storage = req
        .extensions
        .get::<ResponseCache>()
        .expect("Response cache should be always found");

    match response_storage.load() {
        Ok(cached_response) => {
            warn!("Found cached response for: {} {}", req.method, req.url);
            return Ok(cached_response.into());
        }
        Err(Error::CacheMiss) => {
            debug!("Cache miss for: {} {}", req.method, req.url);
        }
        Err(error) => {
            warn!("Cannot load response from cache: {}", error);
            return Err(iron::IronError::new(
                error,
                iron::status::InternalServerError,
            ));
        }
    };

    let mut response = match proxy.load() {
        Ok(upstream_response) => upstream_response,
        Err(error) => {
            return Err(iron::IronError::new(
                error,
                iron::status::InternalServerError,
            ))
        }
    };

    let cached_response = response_storage
        .save(&mut response)
        .map_err(|error| iron::IronError::new(error, iron::status::InternalServerError))?;

    Ok(cached_response.into())
}

type Requests = Vec<Box<dyn ParodyRequest + Send + Sync>>;
struct RequestStorage;
impl iron::typemap::Key for RequestStorage {
    type Value = Requests;
}

/// Represents a running Parody server
#[derive(Debug)]
pub struct Parody {
    listener: iron::Listening,
    a_storage: Option<Arc<Mutex<Requests>>>,
}

/// Stops the listener on destruction
impl Drop for Parody {
    fn drop(&mut self) {
        match self.listener.close() {
            Ok(_) => {}
            Err(error) => error!("Cannot close listener: {}", error),
        }
    }
}

impl Parody {
    pub fn ip(&self) -> IpAddr {
        self.listener.socket.ip()
    }

    pub fn port(&self) -> u16 {
        self.listener.socket.port()
    }

    pub fn requests(&self) -> Option<Arc<Mutex<Requests>>> {
        self.a_storage.clone().map(|a_storage| a_storage.clone())
    }

    pub fn url(&self) -> ::url::Url {
        let url = ::url::Url::parse(&format!("http://{}:{}", self.ip(), self.port()))
            .expect("URL should be correct");
        url
    }
}

fn get_storage_directory(upstream_url: &str, file: &str) -> Result<PathBuf> {
    let url = url::Url::from_str(upstream_url)?;
    let domain = url.domain().ok_or(UtilError::DomainMissing)?;

    let parent_path = Path::new(file)
        .parent()
        .ok_or(UtilError::InvalidCurrentFilePath)?;

    Ok(parent_path.join(domain))
}

/// Starts a server listening at random port at localhost for a directory relative to the given file
///
/// # Example
/// ```
/// use std::path::Path;
/// let parody = parody::start_relative_to_file("https://example.com", file!()).unwrap();
/// println!("PARODY_IP={}", parody.ip());
/// println!("PARODY_PORT={}", parody.port());
/// ```
pub fn start_relative_to_file(upstream_url: &str, file: &str) -> Result<Parody> {
    start(
        url::Url::from_str(upstream_url)?,
        storage::Config::default().with_root_dir(get_storage_directory(upstream_url, file)?),
    )
}

/// Starts a server at random port at localhost
///
/// With this function you can configure your Parody server precisely
///
/// # Example
/// ```
/// use std::str::FromStr;
/// use std::path::Path;
/// let storage_config = parody::storage::Config::default().with_root_dir(Path::new("/tmp/parody/example.com").to_owned());
/// let upstream_url = url::Url::from_str("http://example.com").unwrap();
/// let parody = parody::start(upstream_url, storage_config).unwrap();
/// println!("PARODY_IP={}", parody.ip());
/// println!("PARODY_PORT={}", parody.port());
/// ```
pub fn start(upstream_url: url::Url, storage_config: storage::Config) -> Result<Parody> {
    let mut chain = iron::Chain::new(handle_request);
    chain.link_before(CacheMiddleware::new().with_storage_config(storage_config));
    chain.link_before(ForwardMiddleware::new(upstream_url));

    let a_storage = Arc::new(Mutex::new(Vec::new()));

    chain.link(persistent::Write::<RequestStorage>::both(a_storage.clone()));

    let listener: HttpListener = HttpListener::new(SocketAddr::from(([127, 0, 0, 1], 0)))?;

    iron::Iron::new(chain)
        .listen(listener, iron::Protocol::http())
        .map(|listener| Parody {
            listener: listener,
            a_storage: Some(a_storage),
        })
        .map_err(|err| err.into())
}

#[cfg(test)]
mod test {
    extern crate tempfile;
    use super::*;
    use iron::IronResult;
    use regex::Regex;

    struct ListenerGuard {
        listener: iron::Listening,
    }

    impl Drop for ListenerGuard {
        fn drop(&mut self) {
            match self.listener.close() {
                Ok(_) => {}
                Err(error) => error!("Cannot close listener: {}", error),
            }
        }
    }

    fn respond_lorem_ipsum(_: &mut iron::Request) -> IronResult<iron::Response> {
        Ok(iron::Response::with((
            iron::status::ImATeapot,
            "lorem ipsum",
        )))
    }

    #[test]
    fn parody_when_downloaded_content_from_proxy_should_return_content() {
        let storage_dir = tempfile::tempdir().expect("Can create storage directory");
        let lorem_listener: HttpListener = HttpListener::new(SocketAddr::from(([127, 0, 0, 1], 0)))
            .expect("should be able to listen");

        let lorem_server = iron::Iron::new(respond_lorem_ipsum)
            .listen(lorem_listener, iron::Protocol::http())
            .expect("should be able to start server");

        let lorem_guard = ListenerGuard {
            listener: lorem_server,
        };

        let lorem_url = format!("http://localhost:{}", lorem_guard.listener.socket.port());

        let parody: Parody = start(
            url::Url::parse(&lorem_url).expect("URL constant is correct"),
            storage::Config::default().with_root_dir(storage_dir.into_path()),
        )
        .expect("Should start parody server");

        let mut response = reqwest::get(parody.url()).expect("Get request should succeed");

        assert_eq!(response.status(), reqwest::StatusCode::from_u16(418).expect("Status code valid"));

        assert_eq!(
            response.text().expect("response should contain text"),
            "lorem ipsum"
        );
    }

    #[test]
    fn parody_url_should_return_url_of_currently_running_process() {
        let parody: Parody =
            start_relative_to_file("https://example.com", file!()).expect("Server should start");

        let url_regex =
            Regex::new(r"http://127\.0\.0\.1:[0-9]{1,6}/").expect("Regex constant is valid");

        dbg!(parody.url().as_str());

        assert!(url_regex.is_match(parody.url().as_str()));
    }
}