-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.js.mbt
More file actions
299 lines (275 loc) · 7.63 KB
/
Copy pathclient.js.mbt
File metadata and controls
299 lines (275 loc) · 7.63 KB
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
///|
#external
priv type JsHeaders
///|
extern "js" fn JsHeaders::new() -> JsHeaders =
#| () => new Headers()
///|
extern "js" fn JsHeaders::append(
headers : JsHeaders,
name : String,
value : String,
) =
#| (headers, name, value) => headers.append(name, value)
///|
extern "js" fn JsHeaders::to_array(headers : JsHeaders) -> Array[Array[String]] =
#| (headers) => Array.from(headers.entries())
///|
#external
priv type JsResponse
///|
extern "js" fn JsResponse::status(response : JsResponse) -> Int =
#| (response) => response.status
///|
extern "js" fn JsResponse::status_text(response : JsResponse) -> String =
#| (response) => response.statusText
///|
extern "js" fn JsResponse::headers(response : JsResponse) -> JsHeaders =
#| (response) => response.headers
///|
extern "js" fn JsResponse::body(
response : JsResponse,
) -> @js_async.JsReadableStream =
#| (response) => response.body
///|
priv struct OngoingRequest {
body_writer : @io.PipeWrite
abort_controller : @js_async.AbortController
response : @js_async.Promise[JsResponse]
}
///|
pub struct Client {
priv host : String
priv port : Int
priv protocol : Protocol
priv headers : Map[String, String]
priv mut request : OngoingRequest?
priv mut response_body : @js_async.ReadableStream?
}
///|
pub async fn Client::Client(
uri : String,
headers? : Map[String, String] = {},
proxy? : Client,
verify? : Bool = true,
) -> Client {
Client::new(uri, headers~, proxy?, verify~)
}
///|
pub fn Client::close(self : Client) -> Unit {
if self.request is Some(request) {
request.body_writer.close()
self.request = None
}
if self.response_body is Some(response_body) {
response_body.close()
}
}
///|
fn Client::connect(
host : String,
headers? : Map[String, String] = {},
protocol? : Protocol = Https,
port? : Int = protocol.default_port(),
proxy? : Client,
) -> Client {
ignore(proxy)
{ host, headers, protocol, port, request: None, response_body: None }
}
///|
/// Create a new HTTP client by connecting to a remote host.
/// Host should be specified via `protocol://host[:port]`,
/// where `protocol` is one of `http` or `https`.
///
/// `headers` can be used to specify persistent headers for the client,
/// i.e. all requests made from this client will share these headers.
/// The ownership of `headers` will be transferred to the new client,
/// so `headers` should not be used by the caller later.
/// The headers mentioned in
/// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header
/// must not be set in `headers`.
///
/// The HTTP client make requests using native fetch API.
///
/// The `proxy` argument is not supported on JavaScript backend and has no effect.
///
/// `verify` is ignored on JS backend
#warnings("-unused_async")
pub async fn Client::new(
uri : String,
headers? : Map[String, String] = {},
proxy? : Client,
verify? : Bool = true,
) -> Client {
ignore(proxy)
ignore(verify)
let (protocol, port, host, path) = resolve_url(uri)
guard path is "/" else { raise InvalidFormat }
Client::connect(host, protocol~, port~, headers~, proxy?)
}
///|
pub impl @io.Writer for Client with write_once(self, buf, offset~, len~) {
guard self.request is Some(request)
request.body_writer.write_once(buf, offset~, len~)
}
///|
#warnings("-unused_async")
pub async fn Client::flush(_ : Client) -> Unit {
// no need to flush in JS backend
()
}
///|
pub impl @io.Reader for Client with _get_internal_buffer(self) {
guard self.response_body is Some(stream)
stream._get_internal_buffer()
}
///|
pub impl @io.Reader for Client with _direct_read(self, buf, offset~, max_len~) {
guard self.response_body is Some(stream)
stream._direct_read(buf, offset~, max_len~)
}
///|
pub async fn Client::end_request(self : Client) -> Response {
guard self.request is Some(request)
self.request = None
request.body_writer.close()
let js_response : JsResponse = request.response.wait(
abort_controller=request.abort_controller,
)
self.response_body = Some(
@js_async.ReadableStream::from_js(js_response.body()),
)
let headers = {}
for entry in js_response.headers().to_array() {
headers[entry[0].to_lower()] = entry[1]
}
{
code: js_response.status(),
reason: js_response.status_text(),
headers,
cookies: [],
}
}
///|
extern "js" fn Client::request_ffi(
uri : String,
meth : String,
headers~ : JsHeaders,
body~ : @js_async.JsReadableStream,
signal~ : @js_async.AbortSignal,
) -> @js_async.Promise[JsResponse] =
#| (uri, method, headers, body, signal) => {
#| const fixed_body = (method === "GET" || method === "HEAD") ? null : body
#| return fetch(
#| uri,
#| {
#| body: fixed_body,
#| method: method,
#| headers: headers,
#| signal: signal,
#| duplex: 'half',
#| },
#| )
#| }
///|
/// Send a HTTP request to the server.
/// Only the header of the request will be sent,
/// request body can be sent by using `Client` as a `@io.Writer`.
/// Once request body has been sent,
/// `end_request` must be called to complete the request and obtain response from the server.
///
/// After performing a request,
/// the next request MUST NOT be made before the request is completed via `end_request`.
///
/// In addition to headers in `Client::new`,
/// extra HTTP headers can be passed via `extra_headers`.
/// The headers mentioned in
/// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header
/// must not be set in `extra_headers`.
#warnings("-unused_async")
pub async fn Client::request(
self : Client,
meth : RequestMethod,
path : String,
extra_headers? : Map[String, String] = {},
) -> Unit {
guard self.request is None
let protocol = match self.protocol {
Http => "http://"
Https => "https://"
}
let path = if path is ['/', ..] { path } else { "/\{path}" }
let port = if self.port == self.protocol.default_port() {
""
} else {
":\{self.port}"
}
let uri = "\{protocol}\{self.host}\{port}\{path}"
let meth = match meth {
Get => "GET"
Head => "HEAD"
Post => "POST"
Put => "PUT"
Delete => "DELETE"
Connect => "CONNECT"
Options => "OPTIONS"
Trace => "TRACE"
Patch => "PATCH"
}
let headers = JsHeaders::new()
for k, v in self.headers {
headers.append(k, v)
}
for k, v in extra_headers {
headers.append(k, v)
}
let abort_controller = @js_async.AbortController::new()
let (body, we_write) = @js_async.JsReadableStream::new_pipe()
let response_promise = Client::request_ffi(
uri,
meth,
headers~,
body~,
signal=abort_controller.signal(),
)
let request : OngoingRequest = {
abort_controller,
body_writer: we_write,
response: response_promise,
}
self.request = Some(request)
}
///|
/// Perform a `GET` request to the server, see `Client::request` for more details.
pub async fn Client::get(
self : Client,
path : String,
extra_headers? : Map[String, String] = {},
body? : &@io.Data,
) -> Response {
self.request(Get, path, extra_headers~)
if body is Some(body) {
self.write(body)
}
self.end_request()
}
///|
/// Perform a `PUT` request to the server, see `Client::request` for more details.
pub async fn Client::put(
self : Client,
path : String,
body : &@io.Data,
extra_headers? : Map[String, String] = {},
) -> Response {
self..request(Put, path, extra_headers~)..write(body).end_request()
}
///|
/// Perform a `POST` request to the server, see `Client::request` for more details.
pub async fn Client::post(
self : Client,
path : String,
body : &@io.Data,
extra_headers? : Map[String, String] = {},
) -> Response {
self..request(Post, path, extra_headers~)..write(body).end_request()
}