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
use super::error::{Error, HeaderError, HttpError, StreamError};
use super::stream::{BaseStream, ReadStream};
use http::{header::HeaderName, HeaderMap, StatusCode};
use num_traits::FromPrimitive;
use std::str::{from_utf8, FromStr};

/// Response for HTTP fetch request, which may include body, headers, and status code.
///
/// ```no_run
/// use edjx::{FetchResponse, HttpFetch, StatusCode, Uri};
/// use std::str::FromStr;
///
/// let fetch_uri = Uri::from_str("https://httpbin.org/get").unwrap();
/// let mut fetch_res: FetchResponse = match HttpFetch::get(fetch_uri).send() {
///    Ok(resp) => resp,
///    Err(e) => {
///        panic!("{}", &e.to_string());
///    }
/// };
///
/// let body = fetch_res.read_body();
/// assert_eq!(fetch_res.status_code(), &StatusCode::OK);
/// ```
#[derive(Debug)]
pub struct FetchResponse {
    status: StatusCode,
    headers: HeaderMap,
    read_stream: ReadStream,
}

impl FetchResponse {
    #[doc(hidden)]
    pub(crate) fn from_server() -> Result<FetchResponse, HttpError> {
        get_fetch_response_from_host(0)
    }

    /// Returns the HTTP status code of the fetch response.
    pub fn status_code(&self) -> &StatusCode {
        return &self.status;
    }

    /// Returns the HTTP header map of the fetch response.
    pub fn headers(&self) -> &HeaderMap {
        return &self.headers;
    }

    /// Reads and returns the HTTP body of the fetch response.
    ///
    /// This method should not be called more than once.
    pub fn read_body(&mut self) -> Result<Vec<u8>, StreamError> {
        let result = self.read_stream.read_all();
        let closed = self.read_stream.close();

        if result.is_err() {
            return result;
        }

        if closed.is_err() {
            return Err(closed.err().unwrap());
        }

        return result;
    }

    /// Returns the HTTP body of the fetch response as a read stream.
    pub fn get_read_stream(&mut self) -> &mut ReadStream {
        return &mut self.read_stream;
    }
}

#[link(wasm_import_module = "fetch_response")]
extern "C" {
    fn http_fetch_response_status_code_streaming(sd: u32, err_ptr: *mut i32) -> i32;
    fn http_fetch_response_get_read_stream(
        sd: u32,
        read_sd_ptr: *mut u32,
        err_ptr: *mut i32,
    ) -> i32;
    fn http_fetch_response_get_all_header_keys_streaming(sd: u32, error_code_ptr: *mut i32) -> i32;
    fn http_fetch_response_get_header_value_streaming(
        sd: u32,
        header_ptr: *const u8,
        header_len: i32,
        err_code_ptr: *mut i32,
    ) -> i32;
}

///
/// [`FetchResponsePending`] is a placeholder for the HTTP server's response.
/// It is returned when [`crate::fetch::HttpFetch::send_streaming`] is called.
/// It is then used to retrive [`FetchResponse`] from the server.
///
/// # Example
///
/// ```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 text").unwrap();
/// write_stream.close().unwrap();
///
/// let mut fetch_res: FetchResponse = fet_resp_pending.get_fetch_response().unwrap();
///
/// ```
#[derive(Debug)]
pub struct FetchResponsePending {
    sd: u32,
}

impl FetchResponsePending {
    pub fn new(stream_desc: u32) -> Self {
        FetchResponsePending { sd: stream_desc }
    }

    /// This function is used to retrive [`FetchResponse`] from the remote
    /// server once the response is ready.
    pub fn get_fetch_response(&self) -> Result<FetchResponse, HttpError> {
        get_fetch_response_from_host(self.sd)
    }
}

fn get_fetch_response_from_host(sd: u32) -> Result<FetchResponse, HttpError> {
    let status = get_status_code_from_host_streaming(sd)?;

    let mut headers = HeaderMap::new();
    let header_keys = get_all_header_keys_from_host_streaming(sd)?;
    for key in header_keys {
        headers.insert(
            HeaderName::from_str(key.as_str()).unwrap(),
            get_header_value_from_host_streaming(sd, key.as_str())?
                .parse()
                .unwrap(),
        );
    }

    let read_sd = get_read_stream_host_streaming(sd)?;
    Ok(FetchResponse {
        status,
        headers,
        read_stream: BaseStream::new(read_sd),
    })
}

fn get_status_code_from_host_streaming(sd: u32) -> Result<StatusCode, HttpError> {
    let mut err_code: i32 = 0;
    let response = unsafe { http_fetch_response_status_code_streaming(sd, &mut err_code) };
    if response < 0 {
        Err(HttpError::from(Error::from_i32(err_code).unwrap()))
    } else {
        Ok(StatusCode::from_u16(response as u16).unwrap())
    }
}

fn get_read_stream_host_streaming(sd: u32) -> Result<u32, HttpError> {
    let mut err_code: i32 = 0;
    let mut read_sd: u32 = 0;
    let response = unsafe { http_fetch_response_get_read_stream(sd, &mut read_sd, &mut err_code) };

    if response < 0 {
        Err(HttpError::from(Error::from_i32(err_code).unwrap()))
    } else {
        Ok(read_sd)
    }
}

fn get_all_header_keys_from_host_streaming(sd: u32) -> Result<Vec<String>, HeaderError> {
    let mut err_code: i32 = 0;
    let response = unsafe { http_fetch_response_get_all_header_keys_streaming(sd, &mut err_code) };

    if response > 0 {
        let data = super::result::get_result_bytes(response).unwrap();

        let keys_delimited_string = from_utf8(&data).unwrap();
        let mut v = Vec::new();
        for header_key in keys_delimited_string.split(",") {
            if header_key.len() > 0 {
                v.push(String::from(header_key))
            }
        }
        Ok(v)
    } else if response == 0 {
        Ok(Vec::with_capacity(0))
    } else {
        Err(HeaderError::from_i32(err_code).unwrap())
    }
}

fn get_header_value_from_host_streaming(sd: u32, header_key: &str) -> Result<String, HeaderError> {
    let mut key = String::from(header_key);
    let key = key.as_mut_str();
    let dest_length = key.len() as i32;
    let dest_pointer = key.as_mut_ptr() as *const u8;
    let mut err: i32 = 0;

    let result_size = unsafe {
        http_fetch_response_get_header_value_streaming(sd, dest_pointer, dest_length, &mut err)
    };
    if result_size > 0 {
        let data = super::result::get_result_bytes(result_size);
        Ok(String::from_utf8(data.unwrap()).unwrap())
    } else if result_size == 0 {
        return Ok(String::with_capacity(0));
    } else {
        return Err(HeaderError::from_i32(err).unwrap());
    }
}