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
206
207
208
209
210
211
212
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Types used when performing HTTP requests.

use custom_debug_derive::Debug;
use linera_witty::{WitLoad, WitStore, WitType};
use serde::{Deserialize, Serialize};

use crate::hex_debug;

/// An HTTP request.
#[derive(Clone, Debug, Eq, PartialEq, WitLoad, WitStore, WitType)]
#[witty(name = "http-request")]
pub struct Request {
    /// The [`Method`] used for the HTTP request.
    pub method: Method,

    /// The URL this request is intended to.
    pub url: String,

    /// The headers that should be included in the request.
    pub headers: Vec<Header>,

    /// The body of the request.
    #[debug(with = "hex_debug")]
    pub body: Vec<u8>,
}

impl Request {
    /// Creates an HTTP GET [`Request`] for a `url`.
    pub fn get(url: impl Into<String>) -> Self {
        Request {
            method: Method::Get,
            url: url.into(),
            headers: vec![],
            body: vec![],
        }
    }

    /// Creates an HTTP POST [`Request`] for a `url` with a `payload` that's arbitrary bytes.
    pub fn post(url: impl Into<String>, payload: impl Into<Vec<u8>>) -> Self {
        Request {
            method: Method::Post,
            url: url.into(),
            headers: vec![],
            body: payload.into(),
        }
    }

    /// Creates an HTTP POST [`Request`] for a `url` with a body that's the `payload` serialized to
    /// JSON.
    pub fn post_json(
        url: impl Into<String>,
        payload: &impl Serialize,
    ) -> Result<Self, serde_json::Error> {
        Ok(Request {
            method: Method::Post,
            url: url.into(),
            headers: vec![Header::new("Content-Type", b"application/json")],
            body: serde_json::to_vec(payload)?,
        })
    }

    /// Adds a header to this [`Request`].
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
        self.headers.push(Header::new(name, value));
        self
    }
}

/// The method used in an HTTP request.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitLoad, WitStore, WitType)]
#[witty(name = "http-method")]
pub enum Method {
    /// A GET request.
    Get,

    /// A POST request.
    Post,

    /// A PUT request.
    Put,

    /// A DELETE request.
    Delete,

    /// A HEAD request.
    Head,

    /// A OPTIONS request.
    Options,

    /// A CONNECT request.
    Connect,

    /// A PATCH request.
    Patch,

    /// A TRACE request.
    Trace,
}

#[cfg(with_reqwest)]
impl From<Method> for reqwest::Method {
    fn from(method: Method) -> Self {
        match method {
            Method::Get => reqwest::Method::GET,
            Method::Post => reqwest::Method::POST,
            Method::Put => reqwest::Method::PUT,
            Method::Delete => reqwest::Method::DELETE,
            Method::Head => reqwest::Method::HEAD,
            Method::Options => reqwest::Method::OPTIONS,
            Method::Connect => reqwest::Method::CONNECT,
            Method::Patch => reqwest::Method::PATCH,
            Method::Trace => reqwest::Method::TRACE,
        }
    }
}

/// A response for an HTTP request.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, WitLoad, WitStore, WitType)]
#[witty(name = "http-response")]
pub struct Response {
    /// The status code of the HTTP response.
    pub status: u16,

    /// The headers included in the response.
    pub headers: Vec<Header>,

    /// The body of the response.
    #[debug(with = "hex_debug")]
    #[serde(with = "serde_bytes")]
    pub body: Vec<u8>,
}

impl Response {
    /// Creates an HTTP [`Response`] with a user defined `status_code`.
    pub fn new(status_code: u16) -> Self {
        Response {
            status: status_code,
            headers: vec![],
            body: vec![],
        }
    }

    /// Creates an HTTP [`Response`] with an OK status code and the provided `body`.
    pub fn ok(body: impl Into<Vec<u8>>) -> Self {
        Response {
            status: 200,
            headers: vec![],
            body: body.into(),
        }
    }

    /// Creates an HTTP [`Response`] with an Unauthorized status code.
    pub fn unauthorized() -> Self {
        Response {
            status: 401,
            headers: vec![],
            body: vec![],
        }
    }

    /// Adds a header to this [`Response`].
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
        self.headers.push(Header::new(name, value));
        self
    }
}

#[cfg(with_reqwest)]
impl Response {
    /// Creates a [`Response`] from a [`reqwest::Response`], waiting for it to be fully
    /// received.
    pub async fn from_reqwest(response: reqwest::Response) -> reqwest::Result<Self> {
        let headers = response
            .headers()
            .into_iter()
            .map(|(name, value)| Header::new(name.to_string(), value.as_bytes()))
            .collect();

        Ok(Response {
            status: response.status().as_u16(),
            headers,
            body: response.bytes().await?.to_vec(),
        })
    }
}

/// A header for an HTTP request or response.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, WitLoad, WitStore, WitType)]
#[witty(name = "http-header")]
pub struct Header {
    /// The header name.
    pub name: String,

    /// The value of the header.
    #[debug(with = "hex_debug")]
    #[serde(with = "serde_bytes")]
    pub value: Vec<u8>,
}

impl Header {
    /// Creates a new [`Header`] with the provided `name` and `value`.
    pub fn new(name: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
        Header {
            name: name.into(),
            value: value.into(),
        }
    }
}