webmachine_rust/
context.rs

1//! The `context` module encapsulates the context of the environment that the webmachine is
2//! executing in. Basically wraps the request and response.
3
4use std::any::Any;
5use std::collections::{BTreeMap, HashMap};
6use std::fmt::{Debug, Display};
7use std::sync::Arc;
8use std::time::SystemTime;
9use bytes::Bytes;
10use chrono::{DateTime, FixedOffset};
11use maplit::hashmap;
12
13use crate::headers::HeaderValue;
14
15/// Request that the state machine is executing against
16#[derive(Debug, Clone, PartialEq)]
17pub struct WebmachineRequest {
18  /// Path of the received request
19  pub request_path: String,
20  /// Resource base path (configured in the dispatcher)
21  pub base_path: String,
22  /// Any additional path after the base path
23  pub sub_path: Option<String>,
24  /// Path parts mapped to any variables (i.e. parts like /{id} will have id mapped)
25  pub path_vars: HashMap<String, String>,
26  /// Request method
27  pub method: String,
28  /// Request headers
29  pub headers: HashMap<String, Vec<HeaderValue>>,
30  /// Request body
31  pub body: Option<Bytes>,
32  /// Query parameters
33  pub query: HashMap<String, Vec<String>>
34}
35
36impl Default for WebmachineRequest {
37  /// Creates a default request (GET /)
38  fn default() -> WebmachineRequest {
39    WebmachineRequest {
40      request_path: "/".to_string(),
41      base_path: "/".to_string(),
42      sub_path: None,
43      path_vars: Default::default(),
44      method: "GET".to_string(),
45      headers: HashMap::new(),
46      body: None,
47      query: HashMap::new()
48    }
49  }
50}
51
52impl WebmachineRequest {
53    /// returns the content type of the request, based on the content type header. Defaults to
54    /// 'application/json' if there is no header.
55    pub fn content_type(&self) -> HeaderValue {
56      match self.headers.keys().find(|k| k.to_uppercase() == "CONTENT-TYPE") {
57        Some(header) => match self.headers.get(header).unwrap().first() {
58          Some(value) => value.clone(),
59          None => HeaderValue::json()
60        },
61        None => HeaderValue::json()
62      }
63    }
64
65    /// If the request is a put or post
66    pub fn is_put_or_post(&self) -> bool {
67        ["PUT", "POST"].contains(&self.method.to_uppercase().as_str())
68    }
69
70    /// If the request is a get or head request
71    pub fn is_get_or_head(&self) -> bool {
72        ["GET", "HEAD"].contains(&self.method.to_uppercase().as_str())
73    }
74
75    /// If the request is a get
76    pub fn is_get(&self) -> bool {
77        self.method.to_uppercase() == "GET"
78    }
79
80    /// If the request is an options
81    pub fn is_options(&self) -> bool {
82        self.method.to_uppercase() == "OPTIONS"
83    }
84
85    /// If the request is a put
86    pub fn is_put(&self) -> bool {
87        self.method.to_uppercase() == "PUT"
88    }
89
90    /// If the request is a post
91    pub fn is_post(&self) -> bool {
92        self.method.to_uppercase() == "POST"
93    }
94
95    /// If the request is a delete
96    pub fn is_delete(&self) -> bool {
97        self.method.to_uppercase() == "DELETE"
98    }
99
100    /// If an Accept header exists
101    pub fn has_accept_header(&self) -> bool {
102        self.has_header("ACCEPT")
103    }
104
105    /// Returns the acceptable media types from the Accept header
106    pub fn accept(&self) -> Vec<HeaderValue> {
107        self.find_header("ACCEPT")
108    }
109
110    /// If an Accept-Language header exists
111    pub fn has_accept_language_header(&self) -> bool {
112        self.has_header("ACCEPT-LANGUAGE")
113    }
114
115    /// Returns the acceptable languages from the Accept-Language header
116    pub fn accept_language(&self) -> Vec<HeaderValue> {
117        self.find_header("ACCEPT-LANGUAGE")
118    }
119
120    /// If an Accept-Charset header exists
121    pub fn has_accept_charset_header(&self) -> bool {
122        self.has_header("ACCEPT-CHARSET")
123    }
124
125    /// Returns the acceptable charsets from the Accept-Charset header
126    pub fn accept_charset(&self) -> Vec<HeaderValue> {
127        self.find_header("ACCEPT-CHARSET")
128    }
129
130    /// If an Accept-Encoding header exists
131    pub fn has_accept_encoding_header(&self) -> bool {
132        self.has_header("ACCEPT-ENCODING")
133    }
134
135    /// Returns the acceptable encodings from the Accept-Encoding header
136    pub fn accept_encoding(&self) -> Vec<HeaderValue> {
137        self.find_header("ACCEPT-ENCODING")
138    }
139
140    /// If the request has the provided header
141    pub fn has_header(&self, header: &str) -> bool {
142      self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()).is_some()
143    }
144
145    /// Returns the list of values for the provided request header. If the header is not present,
146    /// or has no value, and empty vector is returned.
147    pub fn find_header(&self, header: &str) -> Vec<HeaderValue> {
148        match self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()) {
149            Some(header) => self.headers.get(header).unwrap().clone(),
150            None => Vec::new()
151        }
152    }
153
154    /// If the header has a matching value
155    pub fn has_header_value(&self, header: &str, value: &str) -> bool {
156        match self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()) {
157            Some(header) => match self.headers.get(header).unwrap().iter().find(|val| *val == value) {
158                Some(_) => true,
159                None => false
160            },
161            None => false
162        }
163    }
164}
165
166/// Response that is generated as a result of the webmachine execution
167#[derive(Debug, Clone, PartialEq)]
168pub struct WebmachineResponse {
169    /// status code to return
170    pub status: u16,
171    /// headers to return
172    pub headers: BTreeMap<String, Vec<HeaderValue>>,
173    /// Response Body
174    pub body: Option<Bytes>
175}
176
177impl WebmachineResponse {
178    /// Creates a default response (200 OK)
179    pub fn default() -> WebmachineResponse {
180        WebmachineResponse {
181            status: 200,
182            headers: BTreeMap::new(),
183            body: None
184        }
185    }
186
187    /// If the response has the provided header
188    pub fn has_header(&self, header: &str) -> bool {
189      self.headers.keys().find(|k| k.to_uppercase() == header.to_uppercase()).is_some()
190    }
191
192    /// Adds the header values to the headers
193    pub fn add_header(&mut self, header: &str, values: Vec<HeaderValue>) {
194      self.headers.insert(header.to_string(), values);
195    }
196
197    /// Adds the headers from a HashMap to the headers
198    pub fn add_headers(&mut self, headers: HashMap<String, Vec<String>>) {
199      for (k, v) in headers {
200        self.headers.insert(k, v.iter().map(HeaderValue::basic).collect());
201      }
202    }
203
204    /// Adds standard CORS headers to the response
205    pub fn add_cors_headers(&mut self, allowed_methods: &[&str]) {
206      let cors_headers = WebmachineResponse::cors_headers(allowed_methods);
207      for (k, v) in cors_headers {
208        self.add_header(k.as_str(), v.iter().map(HeaderValue::basic).collect());
209      }
210    }
211
212    /// Returns a HashMap of standard CORS headers
213    pub fn cors_headers(allowed_methods: &[&str]) -> HashMap<String, Vec<String>> {
214      hashmap!{
215        "Access-Control-Allow-Origin".to_string() => vec!["*".to_string()],
216        "Access-Control-Allow-Methods".to_string() => allowed_methods.iter().map(|v| v.to_string()).collect(),
217        "Access-Control-Allow-Headers".to_string() => vec!["Content-Type".to_string()]
218      }
219    }
220
221    /// If the response has a body
222    pub fn has_body(&self) -> bool {
223        match &self.body {
224            &None => false,
225            &Some(ref body) => !body.is_empty()
226        }
227    }
228}
229
230/// Trait to store arbitrary values
231pub trait MetaDataThing: Any + Debug {}
232
233/// Values that can be stored as metadata
234#[derive(Debug, Clone)]
235pub enum MetaDataValue {
236  /// No Value,
237  Empty,
238  /// String Value
239  String(String),
240  /// Unsigned integer
241  UInteger(u64),
242  /// Signed integer
243  Integer(i64),
244  /// Boxed Any
245  Anything(Arc<dyn MetaDataThing + Send + Sync>)
246}
247
248impl MetaDataValue {
249  /// If the metadata value is empty
250  pub fn is_empty(&self) -> bool {
251    match self {
252      MetaDataValue::Empty => true,
253      _ => false
254    }
255  }
256
257  /// If the metadata value is a String
258  pub fn as_string(&self) -> Option<String> {
259    match self {
260      MetaDataValue::String(s) => Some(s.clone()),
261      _ => None
262    }
263  }
264
265  /// If the metadata value is an unsigned integer
266  pub fn as_uint(&self) -> Option<u64> {
267    match self {
268      MetaDataValue::UInteger(u) => Some(*u),
269      _ => None
270    }
271  }
272
273  /// If the metadata value is a signed integer
274  pub fn as_int(&self) -> Option<i64> {
275    match self {
276      MetaDataValue::Integer(i) => Some(*i),
277      _ => None
278    }
279  }
280
281  /// If the metadata value is an Anything
282  pub fn as_anything(&self) -> Option<&(dyn Any + Send + Sync)> {
283    match self {
284      MetaDataValue::Anything(thing) => Some(thing.as_ref()),
285      _ => None
286    }
287  }
288}
289
290impl Display for MetaDataValue {
291  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292    match self {
293      MetaDataValue::String(s) => write!(f, "{}", s.as_str()),
294      MetaDataValue::UInteger(u) => write!(f, "{}", *u),
295      MetaDataValue::Integer(i) => write!(f, "{}", *i),
296      MetaDataValue::Empty => Ok(()),
297      MetaDataValue::Anything(thing) => write!(f, "any({:?})", thing)
298    }
299  }
300}
301
302impl Default for MetaDataValue {
303  fn default() -> Self {
304    MetaDataValue::Empty
305  }
306}
307
308impl Default for &MetaDataValue {
309  fn default() -> Self {
310    &MetaDataValue::Empty
311  }
312}
313
314impl From<String> for MetaDataValue {
315  fn from(value: String) -> Self {
316    MetaDataValue::String(value)
317  }
318}
319
320impl From<&String> for MetaDataValue {
321  fn from(value: &String) -> Self {
322    MetaDataValue::String(value.clone())
323  }
324}
325
326impl From<&str> for MetaDataValue {
327  fn from(value: &str) -> Self {
328    MetaDataValue::String(value.to_string())
329  }
330}
331
332impl From<u16> for MetaDataValue {
333  fn from(value: u16) -> Self {
334    MetaDataValue::UInteger(value as u64)
335  }
336}
337
338impl From<i16> for MetaDataValue {
339  fn from(value: i16) -> Self {
340    MetaDataValue::Integer(value as i64)
341  }
342}
343
344impl From<u64> for MetaDataValue {
345  fn from(value: u64) -> Self {
346    MetaDataValue::UInteger(value)
347  }
348}
349
350impl From<i64> for MetaDataValue {
351  fn from(value: i64) -> Self {
352    MetaDataValue::Integer(value)
353  }
354}
355
356/// Main context struct that holds the request and response.
357#[derive(Debug, Clone)]
358pub struct WebmachineContext {
359  /// Request that the webmachine is executing against
360  pub request: WebmachineRequest,
361  /// Response that is the result of the execution
362  pub response: WebmachineResponse,
363  /// selected media type after content negotiation
364  pub selected_media_type: Option<String>,
365  /// selected language after content negotiation
366  pub selected_language: Option<String>,
367  /// selected charset after content negotiation
368  pub selected_charset: Option<String>,
369  /// selected encoding after content negotiation
370  pub selected_encoding: Option<String>,
371  /// parsed date and time from the If-Unmodified-Since header
372  pub if_unmodified_since: Option<DateTime<FixedOffset>>,
373  /// parsed date and time from the If-Modified-Since header
374  pub if_modified_since: Option<DateTime<FixedOffset>>,
375  /// If the response should be a redirect
376  pub redirect: bool,
377  /// If a new resource was created
378  pub new_resource: bool,
379  /// General store of metadata. You can use this to store attributes as the webmachine executes.
380  pub metadata: HashMap<String, MetaDataValue>,
381  /// Start time instant when the context was created
382  pub start_time: SystemTime
383}
384
385impl WebmachineContext {
386  /// Convenience method to downcast a metadata anything value
387  pub fn downcast_metadata_value<'a, T: 'static>(&'a self, key: &'a str) -> Option<&'a T> {
388    self.metadata.get(key)
389      .and_then(|value| value.as_anything())
390      .and_then(|value| value.downcast_ref())
391  }
392}
393
394impl Default for WebmachineContext {
395  /// Creates a default context
396  fn default() -> WebmachineContext {
397    WebmachineContext {
398      request: WebmachineRequest::default(),
399      response: WebmachineResponse::default(),
400      selected_media_type: None,
401      selected_language: None,
402      selected_charset: None,
403      selected_encoding: None,
404      if_unmodified_since: None,
405      if_modified_since: None,
406      redirect: false,
407      new_resource: false,
408      metadata: HashMap::new(),
409      start_time: SystemTime::now()
410    }
411  }
412}
413
414#[cfg(test)]
415mod tests {
416  use expectest::prelude::*;
417
418  use crate::headers::*;
419
420  use super::*;
421
422  #[test]
423  fn request_does_not_have_header_test() {
424      let request = WebmachineRequest {
425          .. WebmachineRequest::default()
426      };
427      expect!(request.has_header("Vary")).to(be_false());
428      expect!(request.has_header_value("Vary", "*")).to(be_false());
429  }
430
431  #[test]
432  fn request_with_empty_header_test() {
433      let request = WebmachineRequest {
434          headers: hashmap!{ "HeaderA".to_string() => Vec::new() },
435          .. WebmachineRequest::default()
436      };
437      expect!(request.has_header("HeaderA")).to(be_true());
438      expect!(request.has_header_value("HeaderA", "*")).to(be_false());
439  }
440
441  #[test]
442  fn request_with_header_single_value_test() {
443      let request = WebmachineRequest {
444          headers: hashmap!{ "HeaderA".to_string() => vec![h!("*")] },
445          .. WebmachineRequest::default()
446      };
447      expect!(request.has_header("HeaderA")).to(be_true());
448      expect!(request.has_header_value("HeaderA", "*")).to(be_true());
449      expect!(request.has_header_value("HeaderA", "other")).to(be_false());
450  }
451
452  #[test]
453  fn request_with_header_multiple_value_test() {
454      let request = WebmachineRequest {
455          headers: hashmap!{ "HeaderA".to_string() => vec![h!("*"), h!("other")]},
456          .. WebmachineRequest::default()
457      };
458      expect!(request.has_header("HeaderA")).to(be_true());
459      expect!(request.has_header_value("HeaderA", "*")).to(be_true());
460      expect!(request.has_header_value("HeaderA", "other")).to(be_true());
461      expect!(request.has_header_value("HeaderA", "other2")).to(be_false());
462  }
463}