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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! APIs for executing HTTP requests.
//!

use super::error::{Error, HttpError};
use super::stream::{BaseStream, WriteStream};
use super::{FetchResponse, FetchResponsePending};
use bytes::Bytes;
use http::header::{HeaderMap, HeaderName, HeaderValue};
use http::{Method, Request, Uri, Version};
use num_traits::FromPrimitive;

#[link(wasm_import_module = "http_fetch")]
extern "C" {
    fn host_fetch_send(
        version_addr: *const u8,
        version_len: u32,
        headers_addr: *const u8,
        headers_len: u32,
        body_addr: *const u8,
        body_len: u32,
        url_ptr: *const u8,
        url_len: u32,
        method_ptr: *const u8,
        method_len: u32,
        err_code_ptr: *mut i32,
    ) -> i32;

    fn host_fetch_send_streaming(
        version_addr: *const u8,
        version_len: u32,
        headers_addr: *const u8,
        headers_len: u32,
        url_ptr: *const u8,
        url_len: u32,
        method_ptr: *const u8,
        method_len: u32,
        sd_ptr: *mut u32,
        err_code_ptr: *mut i32,
    ) -> i32;
}

/// An HTTP fetch request, including body, headers, method, and URL.
///
/// # Creation, conversion, and sending
///
/// New requests with an empty body can be created programmatically using [`HttpFetch::new()`]. In
/// addition, there are convenience constructors such as [`HttpFetch::get()`], [`HttpFetch::post()`],
/// [`HttpFetch::put()`], [`HttpFetch::delete()`] which automatically select the appropriate method.
/// Send requests using [`HttpFetch::send()`], for Streaming use [`HttpFetch::send_streaming()`]
///
/// For interoperability with other Rust libraries, [`HttpFetch`] can be initiated using
/// [`http`], which is crate's [`http::Request`] type along with the [`HttpFetch::send_using_standard_http_lib()`] function
/// passing [`Request<Option<Bytes>>`] as parameters.
///
/// # Builder-style Methods
///
/// [`Request`] can be used as a
/// [builder](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html), allowing requests to
/// be constructed and used through method chaining. Methods with the `with_` and `set_` name prefix, such as
/// [`set_header()`][`Self::with_raw_body()`], return `Self` to allow chaining. The builder style is
/// typically most useful when constructing and using a request in a single expression.
/// For example:
///
/// ```no_run
/// use edjx::{HttpFetch, Request, HttpError};
/// # fn f() -> Result<(), HttpError> {
/// HttpFetch::get("https://example.com")
///     .set_header("my-header", "hello!")
///     .with_raw_body("empty body")
///     .send()?;
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct HttpFetch {
    parts: Parts,
    body: Option<Vec<u8>>,
}

/// Component parts of `HttpFetch`
///
/// The HTTP fetch request head consists of a method, URI, version, and a set of
/// header fields.
#[derive(Debug)]
#[doc(hidden)]
struct Parts {
    /// The version of the request.
    version: Version,
    /// The headers for the request.
    headers: HeaderMap,
    /// The URI of the request.
    uri: Uri,
    /// The method for the request.
    method: Method,
}

#[doc(hidden)]
impl Parts {
    /// Creates a default instance of `Parts` with the version as [`HTTP/1.1`].
    fn new(method_p: Method, uri_p: Uri) -> Parts {
        Parts {
            version: Version::HTTP_11,
            headers: HeaderMap::new(),
            uri: uri_p,
            method: method_p,
        }
    }
}

impl HttpFetch {
    /// Creates a request with the given method and URI, no headers, and an empty body.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use edjx::{HttpFetch, Request, HttpError, Method};
    ///
    /// let fetch_uri = Uri::from_str("https://httpbin.org/get").unwrap();
    /// let request = HttpFetch::new(fetch_uri, Method::GET);
    /// ```
    pub fn new(uri: Uri, m: Method) -> HttpFetch {
        HttpFetch {
            body: None,
            parts: Parts::new(m, uri),
        }
    }

    /// Creates a request with the GET method and URI, no headers, and an empty body.
    pub fn get(uri: Uri) -> HttpFetch {
        HttpFetch {
            body: None,
            parts: Parts::new(Method::GET, uri),
        }
    }

    /// Creates a request with the POST method and URI, no headers, and an empty body.
    pub fn post(uri: Uri) -> HttpFetch {
        HttpFetch {
            body: None,
            parts: Parts::new(Method::POST, uri),
        }
    }

    /// Creates a request with the PUT method and URI, no headers, and an empty body.
    pub fn put(uri: Uri) -> HttpFetch {
        HttpFetch {
            body: None,
            parts: Parts::new(Method::PUT, uri),
        }
    }

    /// Creates a request with the DELETE method and URI, no headers, and an empty body.
    pub fn delete(uri: Uri) -> HttpFetch {
        HttpFetch {
            body: None,
            parts: Parts::new(Method::DELETE, uri),
        }
    }

    /// Sets the HTTP version of the request.
    pub fn set_version(mut self, version: Version) -> Self {
        self.parts.version = version;
        return self;
    }

    /// Sets the HTTP version of the request.
    pub fn get_version(&self) -> Version {
        return self.parts.version;
    }

    /// Sets the given [`&str`] value as the body of the request.
    ///
    /// Any body that was previously set on the request is discarded.
    pub fn with_raw_body(mut self, text: &str) -> Self {
        self.body = Some(Vec::from(text));
        return self;
    }

    /// Sets the given [`Vec<u8>`] value as the body of the request.
    ///
    /// Any body that was previously set on the request is discarded.
    pub fn with_binary_body(mut self, bytes: Vec<u8>) -> Self {
        self.body = Some(bytes);
        return self;
    }

    /// Sets a request header to the given value, discarding any previous values for the given
    /// header name.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use edjx::HttpFetch;
    ///
    /// let fetch_uri = Uri::from_str("https://httpbin.org/get").unwrap();
    /// let mut resp = HttpFetch::get(fetch_uri).set_header("hello".parse().unwrap(), "world!".parse().unwrap());
    ///
    /// let header_map = resp.get_headers();
    /// assert!(header_map.contains_key("hello"));
    /// ```
    pub fn set_header(mut self, header_name: HeaderName, value: HeaderValue) -> Self {
        self.parts.headers.append(header_name, value);
        return self;
    }

    /// Returns the request's header map as [`http::header::HeaderMap`].
    pub fn get_headers(&self) -> &HeaderMap {
        return &self.parts.headers;
    }

    /// Returns the request's header map as a mutable reference to [`http::header::HeaderMap`].
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        return &mut self.parts.headers;
    }

    /// Sends the request to the server, and returns after the response is
    /// received or an error occurs.
    ///
    /// # Error Response
    ///
    /// This method returns an error response of kind [`HttpError`] if any of the configured limits
    /// are exceeded.
    ///
    /// # Example
    ///
    /// Sending the client request:
    ///
    /// ```no_run
    /// use edjx::HttpFetch;
    ///
    /// HttpFetch::get("https://example.com").send();
    /// ```
    pub fn send(&self) -> Result<FetchResponse, HttpError> {
        let headers_vec =
            serde_json::to_vec(&super::utils::convert_to_hashmap(&self.parts.headers)).unwrap();
        let headers_slice = headers_vec.as_slice();
        let version: String = super::utils::to_version_string(&self.parts.version);
        let body_len: u32;
        let body_slice;
        let empty_body_vec = Vec::new();
        let method: String = self.parts.method.as_str().to_string();
        let uri: String = self.parts.uri.to_string();
        if self.body.is_none() {
            body_len = 0;
            body_slice = empty_body_vec.as_slice();
        } else {
            body_slice = self.body.as_ref().unwrap().as_slice();
            body_len = body_slice.len() as u32;
        }

        let mut error_code: i32 = 0;

        let response_value = unsafe {
            host_fetch_send(
                version.as_ptr(),
                version.len() as u32,
                headers_slice.as_ptr(),
                headers_slice.len() as u32,
                body_slice.as_ptr(),
                body_len,
                uri.as_ptr(),
                uri.len() as u32,
                method.as_ptr(),
                method.len() as u32,
                &mut error_code,
            )
        };

        if response_value < 0 {
            return Err(HttpError::from(Error::from_i32(error_code).unwrap()));
        }

        Ok(FetchResponse::from_server()?)
    }

    /// Starts streaming an HTTP Fetch request to the server.
    /// This method returns a [`FetchResponsePending`] object and a [`WriteStream`] object.
    /// The [`WriteStream`] object is used to stream data, the [`FetchResponsePending`] object
    /// is a placeholder to retreive [`FetchResponse`]. In the background,
    /// this method triggers sending HTTP headers and other HTTP artifacts
    /// to the server.
    ///
    /// This method and the `send()` method cannot be used together.
    ///
    /// # Error Response
    ///
    /// This method returns an error response of kind [`HttpError`]
    ///
    /// # Example
    ///
    /// Streaming the client request:
    ///
    /// ```no_run
    /// use edjx::{HttpFetch, FetchResponse, BaseStream, Uri};
    /// use std::str::FromStr;
    ///
    /// let fetch_uri = Uri::from_str("https://httpbin.org/post").unwrap();
    /// let (fet_resp_pending, mut write_stream) = HttpFetch::post(fetch_uri).send_streaming().unwrap();
    ///
    /// write_stream.write_chunk_text("Chunk with text").unwrap();
    /// write_stream.write_chunk_binary(Vec::from("Chunk with binary data")).unwrap();
    /// write_stream.close().unwrap();
    ///  
    /// let mut fetch_res: FetchResponse = fet_resp_pending.get_fetch_response().unwrap();
    /// ```
    pub fn send_streaming(&self) -> Result<(FetchResponsePending, WriteStream), HttpError> {
        let headers_vec =
            serde_json::to_vec(&super::utils::convert_to_hashmap(&self.parts.headers)).unwrap();
        let headers_slice = headers_vec.as_slice();
        let version: String = super::utils::to_version_string(&self.parts.version);
        let method: String = self.parts.method.as_str().to_string();
        let uri: String = self.parts.uri.to_string();

        let mut error_code: i32 = 0;
        let mut sd: u32 = 0;

        let response_value = unsafe {
            host_fetch_send_streaming(
                version.as_ptr(),
                version.len() as u32,
                headers_slice.as_ptr(),
                headers_slice.len() as u32,
                uri.as_ptr(),
                uri.len() as u32,
                method.as_ptr(),
                method.len() as u32,
                &mut sd,
                &mut error_code,
            )
        };

        if response_value < 0 {
            return Err(HttpError::from(Error::from_i32(error_code).unwrap()));
        }

        Ok((FetchResponsePending::new(sd), BaseStream::new(sd)))
    }

    /// Sends the request to the server, using standard HTTP request library [`http::Request`] and
    /// returns after a response is received or an error occurs.
    ///
    /// # Error Response
    ///
    /// This method returns an error response of kind [`HttpError`] if any of the
    /// configured limits are exceeded.
    ///
    /// # Example
    ///
    /// Sending a request using [`http::Request`]:
    ///
    /// ```no_run
    /// use edjx::HttpFetch;
    /// use http::Request;
    /// use bytes::Bytes;
    ///
    /// let req_builder = http::request::Builder::new()
    ///       .method(http::Method::POST)
    ///       .uri(&query_url)
    ///       .header("header1", "header1_value");
    ///  
    /// let bytes = Bytes::from("Body bytes");
    /// let req = req_builder.body(Some(bytes)).unwrap();
    /// //let req = req_builder.body(None).unwrap(); //for request without body.
    ///
    /// let fetch_response = HttpFetch::send_using_standard_http_lib(req);
    ///
    /// ```
    pub fn send_using_standard_http_lib(
        req: Request<Option<Bytes>>,
    ) -> Result<FetchResponse, HttpError> {
        let headers_vec =
            serde_json::to_vec(&super::utils::convert_to_hashmap(&req.headers())).unwrap();
        let headers_slice = headers_vec.as_slice();
        let version: String = super::utils::to_version_string(&req.version());
        let method: String = req.method().as_str().to_string();
        let uri: String = req.uri().to_string();
        let body = match req.body() {
            None => Default::default(),
            Some(body) => body.as_ref(),
        };

        let mut error_code: i32 = 0;
        let response_value = unsafe {
            host_fetch_send(
                version.as_ptr(),
                version.len() as u32,
                headers_slice.as_ptr(),
                headers_slice.len() as u32,
                body.as_ptr(),
                body.len() as u32,
                uri.as_ptr(),
                uri.len() as u32,
                method.as_ptr(),
                method.len() as u32,
                &mut error_code,
            )
        };

        if response_value < 0 {
            return Err(HttpError::from(Error::from_i32(error_code).unwrap()));
        }

        Ok(FetchResponse::from_server()?)
    }
}