Skip to main content

stele/
request.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5/// A single intake request, as captured by the fake intake.
6///
7/// The request carries the items that the intake decoded from its payload. The item type depends on the signal.
8#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
9pub struct IntakeRequest<T> {
10    path: String,
11    headers: BTreeMap<String, String>,
12    items: T,
13}
14
15impl<T> IntakeRequest<T> {
16    /// Creates a new `IntakeRequest`.
17    ///
18    /// Header names are lowercased. When a header appears more than once, its values are joined with `, `.
19    pub fn new<'a, I>(path: impl Into<String>, headers: I, items: T) -> Self
20    where
21        I: IntoIterator<Item = (&'a str, &'a str)>,
22    {
23        let mut header_map = BTreeMap::<String, String>::new();
24        for (name, value) in headers {
25            header_map
26                .entry(name.to_ascii_lowercase())
27                .and_modify(|existing| {
28                    existing.push_str(", ");
29                    existing.push_str(value);
30                })
31                .or_insert_with(|| value.to_string());
32        }
33
34        Self {
35            path: path.into(),
36            headers: header_map,
37            items,
38        }
39    }
40
41    /// Returns the request path.
42    pub fn path(&self) -> &str {
43        &self.path
44    }
45
46    /// Returns the request headers, keyed by lowercased name.
47    pub fn headers(&self) -> &BTreeMap<String, String> {
48        &self.headers
49    }
50
51    /// Returns the value of the given header, matched case-insensitively.
52    pub fn header(&self, name: &str) -> Option<&str> {
53        self.headers.get(&name.to_ascii_lowercase()).map(String::as_str)
54    }
55
56    /// Returns the items carried by the request.
57    pub fn items(&self) -> &T {
58        &self.items
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::IntakeRequest;
65
66    #[test]
67    fn headers_are_lowercased_and_repeated_values_joined() {
68        let request = IntakeRequest::new(
69            "/api/v2/series",
70            [("User-Agent", "agent/1.0"), ("X-Tag", "a"), ("x-tag", "b")],
71            Vec::<u32>::new(),
72        );
73
74        assert_eq!(request.path(), "/api/v2/series");
75        assert_eq!(request.header("USER-AGENT"), Some("agent/1.0"));
76        assert_eq!(request.header("x-tag"), Some("a, b"));
77        assert_eq!(request.header("missing"), None);
78        assert_eq!(request.headers().len(), 2);
79    }
80}