-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.mbt
More file actions
324 lines (305 loc) · 9.74 KB
/
Copy pathclient.mbt
File metadata and controls
324 lines (305 loc) · 9.74 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
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
///|
#cfg(target="native")
priv enum ClientTransport {
Plain(@socket.Tcp)
Proxy(Client)
}
///|
#cfg(target="native")
pub struct Client {
/// Simple HTTP client which connect to a remote host via TCP
priv reader : Reader
priv transport : ClientTransport
priv tls : @tls.Tls?
priv sender : Sender
priv mut request_method : RequestMethod?
/// whether automatic decompression should be enabled for current request
priv mut auto_decompress : Bool
}
///|
#cfg(target="native")
pub async fn Client::Client(
uri : String,
headers? : Map[String, String] = {},
proxy? : Client,
verify? : Bool = true,
) -> Client {
Client::new(uri, headers~, proxy?, verify~)
}
///|
#cfg(target="native")
pub suberror ProxyError {
/// Error raised when the proxy responded with a non-2XX response code
ProxyError(Response)
} derive(Debug, ToJson)
///|
#cfg(target="native")
async fn Client::connect(
host : String,
headers? : Map[String, String] = {},
protocol? : Protocol = Https,
port? : Int = protocol.default_port(),
proxy? : Client,
verify? : Bool = true,
) -> Client {
let transport = if proxy is Some(proxy) {
let path = "\{host}:\{port}"
try {
let response = proxy..request(Connect, path).end_request()
guard response.code is (200..<300) else { raise ProxyError(response) }
proxy..skip_response_body().enter_passthrough_mode()
} catch {
err => {
proxy.close()
raise err
}
}
Proxy(proxy)
} else {
Plain(@socket.Tcp::connect_to_host(host, port~))
}
headers["Host"] = host
let (tls, reader, sender) = match (protocol, transport) {
(Http, Plain(conn)) =>
(None, Reader::new(conn), Sender::new(conn, headers~))
(Https, Plain(conn)) => {
let tls = @tls.Tls::client(conn, host~, verify~) catch {
err => {
transport.close()
raise err
}
}
(Some(tls), Reader::new(tls), Sender::new(tls, headers~))
}
(Http, Proxy(proxy)) =>
(None, Reader::new(proxy), Sender::new(proxy, headers~))
(Https, Proxy(proxy)) => {
let tls = @tls.Tls::client(proxy, host~, verify~) catch {
err => {
transport.close()
raise err
}
}
(Some(tls), Reader::new(tls), Sender::new(tls, headers~))
}
}
{
transport,
tls,
reader,
sender,
request_method: None,
auto_decompress: false,
}
}
///|
#cfg(target="native")
/// 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`.
/// If `protocol` is `https`, a TLS connection will be established,
/// and the certificate of the remote peer will be verified.
///
/// If the protocol is `https` and `verify` is `false` (`true` by default), certificate validation will be skipped.
/// `verify=false` should be used for testing only.
///
/// `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 following headers is automatically set,
/// and must not be specified in `headers`:
///
/// - Host
/// - Content-Length, Transfer-Encoding
///
/// If `proxy` is present, it should be another HTTP client in a clean state.
/// The new client will send a `CONNECT` request via the proxy client
/// and try to establish a tunnel via the proxy client.
/// All subsequent requests made by the new client will go through the proxy tunnel.
/// The ownership of the proxy client is transferred to the new client,
/// so it must not be used nor closed anymore by the caller.
/// Using another HTTP client as proxy allows advanced features such as
/// proxy authentication and https `CONNECT` proxy.
pub async fn Client::new(
uri : String,
headers? : Map[String, String] = {},
proxy? : Client,
verify? : Bool = true,
) -> Client {
let (protocol, port, host, path) = resolve_url(uri)
guard path is "/" else { raise InvalidFormat }
Client::connect(host, protocol~, port~, headers~, proxy?, verify~)
}
///|
#cfg(target="native")
fn ClientTransport::close(self : ClientTransport) -> Unit {
match self {
Plain(conn) => conn.close()
Proxy(proxy) => proxy.close()
}
}
///|
#cfg(target="native")
/// Close a HTTP client and release underlying resource.
/// In particular close the underlying TCP connection.
/// This function is idempotent: it is safe to call `.close()` multiple times,
/// only the first `.close()` call takes effect.
pub fn Client::close(self : Client) -> Unit {
if self.tls is Some(tls) {
tls.close()
}
self.transport.close()
}
///|
#cfg(target="native")
pub impl @io.Reader for Client with _direct_read(self, buf, offset~, max_len~) {
self.reader._direct_read(buf, offset~, max_len~)
}
///|
#cfg(target="native")
pub impl @io.Reader for Client with _get_internal_buffer(self) {
self.reader._get_internal_buffer()
}
///|
#cfg(target="native")
/// Write data to the body of the request currently being sent.
/// Must be called after `send_request`.
/// `end_request` must be called after all content of response body has been sent.
///
/// Writing to `@http.Client` MAY be buffered,
/// call `flush` manually to ensure data is delivered to the remote peer.
pub impl @io.Writer for Client with write_once(self, buf, offset~, len~) {
guard !(self.sender.mode is SendingHeader)
self.sender.write_once(buf, offset~, len~)
}
///|
#cfg(target="native")
pub impl @io.Writer for Client with write_reader(self, reader) {
guard !(self.sender.mode is SendingHeader)
self.sender.write_reader(reader)
}
///|
#cfg(target="native")
/// Flush buffered data in the request body being sent, if any.
pub async fn Client::flush(self : Client) -> Unit {
self.sender.flush()
}
///|
#cfg(target="native")
/// End the body of the request currently being sent,
/// and obtain response from the server.
/// Should be called immediately after request body is fully sent.
///
/// Only the header of the response will be received and returned,
/// the body of the response can be extracted by using `Client` as a `@io.Reader`.
///
/// If the body of the last response is still not consumed,
/// it will be discarded.
pub async fn Client::end_request(self : Client) -> Response {
self.sender.end_body()
self.reader.skip_body()
let response = self.reader.read_response(
request_method=self.request_method,
auto_decompress=self.auto_decompress,
)
self.request_method = None
self.auto_decompress = false
response
}
///|
#cfg(target="native")
/// 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::connect`,
/// extra HTTP headers can be passed via `extra_headers`.
/// The following headers is automatically set by `request`,
/// and must not be specified in `extra_headers`:
///
/// - Host
/// - Transfer-Encoding
///
/// If `Content-Length` is present in `extra_headers`,
/// it should be the total length of the request body.
/// The request body can still be sent incrementally,
/// but if the actual body being sent is shorter and longer than the provided length,
/// an error will be raised.
pub async fn Client::request(
self : Client,
meth : RequestMethod,
path : String,
extra_headers? : Map[String, String] = {},
) -> Unit {
self.auto_decompress = self.sender.send_request(meth, path, extra_headers~)
self.request_method = Some(meth)
}
///|
#cfg(target="native")
/// Skip the body of the response currently being produced,
/// so that the next request can be made.
pub async fn Client::skip_response_body(self : Client) -> Unit {
self.reader.skip_body()
}
///|
#cfg(target="native")
/// 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()
}
///|
#cfg(target="native")
/// 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()
}
///|
#cfg(target="native")
/// 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()
}
///|
#cfg(target="native")
/// Let the client enter "pass through" mode,
/// where the client serve as a TCP tunnel (maybe TLS encrypted) directly.
/// This is useful for the special `CONNECT` HTTP request and HTTP protocol upgrade.
///
/// In passthrough mode,
/// Read/write the client becomes direct read/write on the underlying connection,
/// and all API except `@io.Reader` and `@io.Writer` must not be used anymore.
///
/// When entering pass through mode,
/// the client must be in a clean state
/// (i.e. not in the middle of sending a request).
/// Unread data from the body of the last response will be discarded.
pub async fn Client::enter_passthrough_mode(self : Client) -> Unit {
guard self.sender.mode is SendingHeader
self.reader.enter_passthrough_mode()
self.sender.enter_passthrough_mode()
}