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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Ping request representation.

use std::collections::HashMap;

use chrono::prelude::{DateTime, Utc};
use serde_json::{self, Value as JsonValue};

/// Represents a request to upload a ping.
#[derive(PartialEq, Debug, Clone)]
pub struct PingRequest {
    /// The Job ID to identify this request,
    /// this is the same as the ping UUID.
    pub document_id: String,
    /// The path for the server to upload the ping to.
    pub path: String,
    /// The body of the request.
    pub body: JsonValue,
    /// A map with all the headers to be sent with the request.
    pub headers: HashMap<&'static str, String>,
}

impl PingRequest {
    /// Creates a new PingRequest.
    ///
    /// Automatically creates the default request headers.
    /// Clients may add more headers such as `userAgent` to this list.
    pub fn new(document_id: &str, path: &str, body: JsonValue) -> Self {
        Self {
            document_id: document_id.into(),
            path: path.into(),
            body,
            headers: Self::create_request_headers(),
        }
    }

    /// Verifies if current request is for a deletion-request ping.
    pub fn is_deletion_request(&self) -> bool {
        // The path format should be `/submit/<app_id>/<ping_name>/<schema_version/<doc_id>`
        self.path
            .split('/')
            .nth(3)
            .map(|url| url == "deletion-request")
            .unwrap_or(false)
    }

    /// Creates the default request headers.
    fn create_request_headers() -> HashMap<&'static str, String> {
        let mut headers = HashMap::new();
        let date: DateTime<Utc> = Utc::now();
        headers.insert("Date", date.to_string());
        headers.insert("X-Client-Type", "Glean".to_string());
        headers.insert(
            "Content-Type",
            "application/json; charset=utf-8".to_string(),
        );
        headers.insert("X-Client-Version", crate::GLEAN_VERSION.to_string());
        headers
    }
}