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
//! Defines a Bins trait for storing Requests as well as a default in-memory implementation
//! of that trait for easy testing.
use std::collections::HashMap;

use models::*;

/// ADT for denoting status when inserting a request with a bin id.
pub enum InsertRequestStatus {
    /// Insert successful
    Ok,
    /// Insert failed because no bin by that Id exists
    NoSuchBin,
}

/// ADT For deleting a bin by id
pub enum DeleteBinStatus {
    /// Successfully deleted
    Ok,
    /// No such bin. Deletion was not carried out.
    NoSuchBin,
}

/// A Bin holds a bunch of requests. For now it's just an alias for a Vector.
pub type Bin = Vec<Request>;

/// Trait for storage operations for Requests.
pub trait Bins {
    /// Returns a BinSummary of a newly-reated bin. The Id in the summary
    /// must be unique at the time of creation.
    fn create_bin(&mut self) -> BinSummary;

    /// Delete a bin by Id
    fn delete_bin(&mut self, id: &Id) -> DeleteBinStatus;

    /// Get a bin (not just a summary) by Id
    fn get_bin<'a>(&'a self, id: &'a Id) -> Option<&Bin>;

    /// Get a bin summary by Id
    fn get_bin_summary(&self, id: &Id) -> Option<BinSummary>;

    /// Get bin summaries for all currently-stored bins
    fn get_bin_summaries(&self) -> HashMap<Id, BinSummary>;

    /// Insert a request into a Bin using a bin Id.
    fn insert_request(&mut self, id: &Id, request: Request) -> InsertRequestStatus;
}

/// A simple in-memory implementation of Bins.
#[derive(Debug)]
pub struct InMemoryBins {
    pub bins: HashMap<Id, Vec<Request>>,
}

impl InMemoryBins {
    pub fn new() -> InMemoryBins {
        InMemoryBins { bins: HashMap::new() }
    }
}

impl Bins for InMemoryBins {
    fn create_bin(&mut self) -> BinSummary {
        let mut uuid = Id::random();
        while self.bins.contains_key(&uuid) {
            uuid = Id::random();
        }
        self.bins.insert(uuid.to_owned(), Vec::new());
        BinSummary {
            id: uuid,
            request_count: 0,
        }
    }

    fn delete_bin(&mut self, id: &Id) -> DeleteBinStatus {
        match self.bins.remove(id) {
            Some(_) => DeleteBinStatus::Ok,
            _ => DeleteBinStatus::NoSuchBin,
        }
    }

    fn get_bin_summary(&self, id: &Id) -> Option<BinSummary> {
        self.bins.get(id).map(|b| {
                                  BinSummary {
                                      id: id.to_owned(),
                                      request_count: b.len(),
                                  }
                              })
    }

    fn get_bin_summaries(&self) -> HashMap<Id, BinSummary> {
        let mut map: HashMap<Id, BinSummary> = HashMap::new();
        for (k, b) in self.bins.iter() {
            map.insert(k.to_owned(),
                       BinSummary {
                           id: k.to_owned(),
                           request_count: b.len(),
                       });
        }
        map
    }

    fn get_bin(&self, id: &Id) -> Option<&Bin> {
        self.bins.get(id)
    }

    fn insert_request(&mut self, id: &Id, request: Request) -> InsertRequestStatus {
        match self.bins.get_mut(id) {
            Some(bin) => {
                bin.push(request);
                InsertRequestStatus::Ok
            }
            None => InsertRequestStatus::NoSuchBin,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_inmemory_bin_creation() {
        let mut bins = InMemoryBins::new();
        let _ = bins.create_bin();
    }

    #[test]
    fn test_inmemory_bin_deletion() {
        let mut bins = InMemoryBins::new();
        let bin = bins.create_bin();
        bins.delete_bin(&bin.id);
        assert!(bins.bins.is_empty())
    }

    #[test]
    fn test_inmemory_get_bin_summary() {
        let mut bins = InMemoryBins::new();
        let bin = bins.create_bin();
        let req = Request {
            content_length: None,
            content_type: Some("fake".to_owned()),
            time: 123,
            method: "GET".to_owned(),
            path: "/whoa".to_owned(),
            body: None,
            headers: HashMap::new(),
            query_string: HashMap::new(),
        };
        bins.insert_request(&bin.id, req);

        let summary = bins.get_bin_summary(&bin.id).unwrap();
        assert_eq!(summary.request_count, 1)
    }

    #[test]
    fn test_inmemory_get_bin() {
        let mut bins = InMemoryBins::new();
        let bin = bins.create_bin();
        let req = Request {
            content_length: None,
            content_type: Some("fake".to_owned()),
            time: 123,
            method: "GET".to_owned(),
            path: "/whoa".to_owned(),
            body: None,
            headers: HashMap::new(),
            query_string: HashMap::new(),
        };
        bins.insert_request(&bin.id, req);

        let summary = bins.get_bin(&bin.id).unwrap();
        // Don't want to implement Clone in case we clone the requests by accident somewhere..
        assert_eq!(summary[0],
                   Request {
                       content_length: None,
                       content_type: Some("fake".to_owned()),
                       time: 123,
                       method: "GET".to_owned(),
                       path: "/whoa".to_owned(),
                       body: None,
                       headers: HashMap::new(),
                       query_string: HashMap::new(),
                   })
    }

    #[test]
    fn test_inmemory_get_bin_summaries() {
        let mut bins = InMemoryBins::new();
        let bin = bins.create_bin();
        let req = Request {
            content_length: None,
            content_type: Some("fake".to_owned()),
            time: 123,
            method: "GET".to_owned(),
            path: "/whoa".to_owned(),
            body: None,
            headers: HashMap::new(),
            query_string: HashMap::new(),
        };
        bins.insert_request(&bin.id, req);

        let summaries = bins.get_bin_summaries();
        assert_eq!(summaries.get(&bin.id).unwrap().request_count, 1)
    }
}