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
use std::{collections::HashSet, ops::Deref, sync::Arc};

use futures::future::BoxFuture;
use http::{HeaderMap, Method, StatusCode};
use url::Url;

/// Defines http client permissions.
#[derive(Clone, Debug)]
pub struct HttpClientCapabilityV1 {
    pub allow_all: bool,
    pub allowed_hosts: HashSet<String>,
}

impl HttpClientCapabilityV1 {
    pub fn new() -> Self {
        Self {
            allow_all: false,
            allowed_hosts: HashSet::new(),
        }
    }

    pub fn new_allow_all() -> Self {
        Self {
            allow_all: true,
            allowed_hosts: HashSet::new(),
        }
    }

    pub fn is_deny_all(&self) -> bool {
        !self.allow_all && self.allowed_hosts.is_empty()
    }

    pub fn can_access_domain(&self, domain: &str) -> bool {
        self.allow_all || self.allowed_hosts.contains(domain)
    }

    pub fn update(&mut self, other: HttpClientCapabilityV1) {
        let HttpClientCapabilityV1 {
            allow_all,
            allowed_hosts,
        } = other;
        self.allow_all |= allow_all;
        self.allowed_hosts.extend(allowed_hosts);
    }
}

impl Default for HttpClientCapabilityV1 {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Default)]
pub struct HttpRequestOptions {
    pub gzip: bool,
    pub cors_proxy: Option<String>,
}

// TODO: use types from http crate?
pub struct HttpRequest {
    pub url: Url,
    pub method: Method,
    pub headers: HeaderMap,
    pub body: Option<Vec<u8>>,
    pub options: HttpRequestOptions,
}

impl HttpRequest {
    fn from_http_parts(parts: http::request::Parts, body: impl Into<Option<Vec<u8>>>) -> Self {
        let http::request::Parts {
            method,
            uri,
            headers,
            ..
        } = parts;

        HttpRequest {
            url: uri.to_string().parse().unwrap(),
            method,
            headers,
            body: body.into(),
            options: HttpRequestOptions::default(),
        }
    }
}

impl std::fmt::Debug for HttpRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let HttpRequest {
            url,
            method,
            headers,
            body,
            options,
        } = self;

        f.debug_struct("HttpRequest")
            .field("url", &format_args!("{}", url))
            .field("method", method)
            .field("headers", headers)
            .field("body", &body.as_deref().map(String::from_utf8_lossy))
            .field("options", &options)
            .finish()
    }
}

impl From<http::Request<Option<Vec<u8>>>> for HttpRequest {
    fn from(value: http::Request<Option<Vec<u8>>>) -> Self {
        let (parts, body) = value.into_parts();
        HttpRequest::from_http_parts(parts, body)
    }
}

impl From<http::Request<Vec<u8>>> for HttpRequest {
    fn from(value: http::Request<Vec<u8>>) -> Self {
        let (parts, body) = value.into_parts();
        HttpRequest::from_http_parts(parts, body)
    }
}

impl From<http::Request<&str>> for HttpRequest {
    fn from(value: http::Request<&str>) -> Self {
        value.map(|body| body.to_string()).into()
    }
}

impl From<http::Request<String>> for HttpRequest {
    fn from(value: http::Request<String>) -> Self {
        let (parts, body) = value.into_parts();
        HttpRequest::from_http_parts(parts, body.into_bytes())
    }
}

impl From<http::Request<()>> for HttpRequest {
    fn from(value: http::Request<()>) -> Self {
        let (parts, _) = value.into_parts();
        HttpRequest::from_http_parts(parts, None)
    }
}

// TODO: use types from http crate?
pub struct HttpResponse {
    pub body: Option<Vec<u8>>,
    pub redirected: bool,
    pub status: StatusCode,
    pub headers: HeaderMap,
}

impl HttpResponse {
    pub fn is_ok(&self) -> bool {
        !self.status.is_client_error() && !self.status.is_server_error()
    }
}

impl std::fmt::Debug for HttpResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let HttpResponse {
            body,
            redirected,
            status,
            headers,
        } = self;

        f.debug_struct("HttpResponse")
            .field("ok", &self.is_ok())
            .field("redirected", &redirected)
            .field("status", &status)
            .field("headers", &headers)
            .field("body", &body.as_deref().map(String::from_utf8_lossy))
            .finish()
    }
}

pub trait HttpClient: std::fmt::Debug {
    // TODO: use custom error type!
    fn request(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, anyhow::Error>>;
}

impl<D, C> HttpClient for D
where
    D: Deref<Target = C> + std::fmt::Debug,
    C: HttpClient + ?Sized + 'static,
{
    fn request(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, anyhow::Error>> {
        let client = &**self;
        client.request(request)
    }
}

pub type DynHttpClient = Arc<dyn HttpClient + Send + Sync + 'static>;