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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Types for constructing and issuing HTTP requests.

use hyper::client::{Client, Response, RequestBuilder as NetRequestBuilder};
use hyper::header::{Headers, Header, HeaderFormat, ContentType};
use hyper::method::Method;

use url::Url;
use url::form_urlencoded::Serializer as FormUrlEncoded;
use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};

use std::borrow::{Borrow, Cow};
use std::fmt::{self, Write};
use std::mem;

use net::adapter::{ObjSafeAdapter, AbsAdapter};

use net::body::{Body, EmptyFields, EagerBody, RawBody};

use net::call::Call;

use net::response::FromResponse;

use executor::ExecBox;

use ::Result;

/// The request header, containing all the information needed to initialize a request.
#[derive(Debug)]
pub struct RequestHead {
    url: Cow<'static, str>,
    query: String,
    method: Method,
    headers: Headers
}

impl RequestHead {
    fn new(method: Method, url: Cow<'static, str>) -> Self {
        RequestHead {
            url: url.into(),
            query: String::new(),
            method: method,
            headers: Headers::new(),
        }
    }

    /// Set an HTTP header for this request, overwriting any previous value.
    ///
    /// ##Note
    /// Some headers, such as `Content-Type`, may be overwritten by Anterofit.
    pub fn header<H: Header + HeaderFormat>(&mut self, header: H) -> &mut Self {
        self.headers.set(header);
        self
    }

    /// Copy all the HTTP headers from `headers` into this request.
    ///
    /// Duplicate headers will be overwritten.
    ///
    /// ##Note
    /// Some headers, such as `Content-Type`, may be overwritten by Anterofit.
    pub fn headers(&mut self, headers: &Headers) -> &mut Self {
        self.headers.extend(headers.iter());
        self
    }

    /// Append `append` to the URL of this request.
    ///
    /// If this causes the request's URL to be malformed, an error will immediately
    /// be returned by `init_request()`.
    ///
    /// Characters that are not allowed to appear in a URL will be percent-encoded as appropriate
    /// for the path section of a URL.
    ///
    /// ## Note
    /// Adding a query segment via this method will not work as `?` and `=` will be encoded. Use
    /// `query()` instead to add query pairs.
    pub fn append_url<A: AsRef<str>>(&mut self, append: A) -> &mut Self {
        self.url.to_mut().extend(utf8_percent_encode(append.as_ref(), DEFAULT_ENCODE_SET));
        self
    }

    /// Prepend `prepend` to the URL of this request.
    ///
    /// This will appear between the current request URL and the base URL supplied by the adapter,
    /// if present, as the base URL is not appended until `init_request()`.
    ///
    /// If this causes the request's URL to be malformed, an error will immediately
    /// be returned by `init_request()`.
    ///
    /// Characters that are not allowed to appear in a URL will not be automatically percent-encoded.
    pub fn prepend_url<P: AsRef<str>>(&mut self, prepend: P) -> &mut Self {
        prepend_str(prepend.as_ref(), self.url.to_mut());
        self
    }

    /// Add a series of key-value pairs to this request's query. These will appear in the request
    /// URL.
    ///
    /// Characters that are not allowed to appear in a URL will automatically be percent-encoded.
    ///
    /// It is left up to the server how to resolve duplicate keys.
    ///
    /// Thanks to the mess of generics, this method is incredibly flexible: you can pass a reference
    /// to an array of pairs (2-tuples), a vector of pairs, a `HashMap` or `BTreeMap`, or any other
    /// iterator that yields pairs or references to pairs.
    ///
    /// ```rust,no_run
    /// # extern crate anterofit;
    /// # use std::collections::HashMap;
    /// # let head: &mut anterofit::net::RequestHead = unimplemented!();
    /// // `head` is `&mut RequestHead`
    /// head.query(&[("hello", "world"), ("id", "3")]);
    ///
    /// let query_pairs: HashMap<String, String> = HashMap::new();
    ///
    /// // Add some items to the map (...)
    /// head.query(query_pairs);
    /// ```
    ///
    /// ##Panics
    /// If an error is returned from `<K as Display>::fmt()` or `<V as Display>::fmt()`.
    pub fn query<Q, P, K, V>(&mut self, query: Q) -> &mut Self
    where Q: IntoIterator<Item=P>, P: Borrow<(K, V)>, K: fmt::Display, V: fmt::Display {
        let mut query_out = FormUrlEncoded::new(mem::replace(&mut self.query, String::new()));

        let mut kbuf = String::new();
        let mut vbuf = String::new();

        for pair in query {
            let &(ref key, ref val) = pair.borrow();

            kbuf.clear();
            vbuf.clear();

            // Errors here should be rare and usually indicate more serious problems.
            let _ = write!(kbuf, "{}", key).expect("Error returned from Display::fmt()");
            let _ = write!(vbuf, "{}", val).expect("Error returned from Display::fmt()");

            query_out.append_pair(&kbuf, &vbuf);
        }

        self.query = query_out.finish();

        self
    }

    /// Initialize a `hyper::client::RequestBuilder` with the parameters in this header.
    ///
    /// If provided, `base_url` will be prepended to the URL associated with this request,
    /// *then* the constructed query will be set to the URL.
    ///
    /// Finally, `client` will be used to create the `RequestBuilder` and the contained headers
    /// will be added.
    pub fn init_request<'c>(&self, base_url: Option<&Url>, client: &'c Client) -> Result<NetRequestBuilder<'c>> {
        let mut url = if let Some(base_url) = base_url {
            try!(base_url.join(&self.url))
        } else {
            try!(Url::parse(&self.url))
        };

        url.set_query(Some(&self.query));

        // This `.clone()` should be zero-cost, we don't expose Method::Extension at all.
        Ok(client.request(self.method.clone(), url).headers(self.headers.clone()))
    }

    /// Get the current URL of this request.
    pub fn get_url(&self) -> &str {
        &self.url
    }

    /// Get the current query string of this request.
    pub fn get_query(&self) -> &str {
        &self.query
    }

    /// Get the HTTP method of this request.
    pub fn get_method(&self) -> &Method {
        &self.method
    }

    /// Get the headers of this request (may be modified later).
    pub fn get_headers(&self) -> &Headers {
        &self.headers
    }
}

impl fmt::Display for RequestHead {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}{}", self.method, self.url, self.query)
    }
}

/// A container for a request header and body.
///
/// Used in the body of service methods to construct a request.
#[derive(Debug)]
pub struct RequestBuilder<'a, A: 'a, B> {
    adapter: &'a A,
    head: RequestHead,
    body: B,
}

impl<'a, A> RequestBuilder<'a, A, EmptyFields> {
    /// Create a new request builder with the given method and URL.
    ///
    /// `url` can be `String` or `&'static str`.
    pub fn new(adapter: &'a A, method: Method, url: Cow<'static, str>) -> Self {
        RequestBuilder {
            adapter: adapter,
            head: RequestHead::new(method, url),
            body: EmptyFields,
        }
    }
}

impl<'a, A, B> RequestBuilder<'a, A, B> {
    /// Get a reference to the header of the request to inspect it.
    pub fn head(&self) -> &RequestHead {
        &self.head
    }

    /// Get a mutable reference to the header of the request.
    ///
    /// Can be used to change the request URL, add GET query pairs or HTTP headers to be
    /// sent with the request.
    pub fn head_mut(&mut self) -> &mut RequestHead {
        &mut self.head
    }

    /// Set a body to be sent with the request.
    ///
    /// ##Panics
    /// If this is a GET request (cannot have a body).
    pub fn body<B_>(self, body: B_) -> RequestBuilder<'a, A, B_> {
        if let Method::Get = self.head.method {
            panic!("Cannot supply a body with GET requests!");
        }

        RequestBuilder {
            adapter: self.adapter,
            head: self.head,
            body: body,
        }
    }

    /// Pass `self` to the closure, allowing it to mutate and transform the builder
    /// arbitrarily.
    ///
    /// `try!()` will work in this closure.
    pub fn apply<F, B_>(self, functor: F) -> Result<RequestBuilder<'a, A, B_>>
    where F: FnOnce(Self) -> Result<RequestBuilder<'a, A, B_>> {
        functor(self)
    }
}
impl<'a, A, B> RequestBuilder<'a, A, B> where A: AbsAdapter {
    /// Immediately serialize `body` on the current thread and set the result as the body
    /// of this request.
    ///
    /// This is useful if you want to use a body type that is not `Send` or `'static`.
    ///
    /// ##Panics
    /// If this is a GET request (cannot have a body).
    pub fn body_eager<B_>(self, body: B_) -> Result<RequestBuilder<'a, A, RawBody<<B_ as EagerBody>::Readable>>>
    where B_: EagerBody {
        if let Method::Get = self.head.method {
            panic!("Cannot supply a body with GET requests!");
        }

        let body = try!(body.into_readable(self.adapter)).into();
        Ok(self.body(body))
    }

    /// Prepare a `Request` to be executed with the parameters supplied in this builder.
    ///
    /// This request will need to be executed (using `exec()` or `exec_here()`) before anything
    /// else is done. As much work as possible will be relegated to the adapter's executor.
    pub fn build<T>(self) -> Request<'a, T> where B: Body, T: FromResponse {
        let RequestBuilder {
            adapter, head, body
        } = self;

        let adapter_ = adapter.clone();

        let (mut guard, call) = super::call::oneshot(Some(head));

        let exec = Box::new(move || {
            let res = exec_request(&adapter_, guard.head_mut(), body)
                .and_then(|response| T::from_response(&adapter_, response));

            guard.complete(res);
        });

        Request {
            adapter: adapter,
            exec: exec,
            call: call,
        }
    }
}

/// A request which is ready to be sent to the server.
///
/// Use `exec()` or `exec_here()` to send the request and receive the response.
///
/// ##Note
/// If an error occurred during initialization of the request, it will be immediately
/// returned when the request is executed; no network or disk activity will occur.
#[must_use = "Request has not been sent yet"]
pub struct Request<'a, T = ()> {
    adapter: &'a ObjSafeAdapter,
    exec: Box<ExecBox>,
    call: Call<T>,
}

impl<'a, T> Request<'a, T> {
    /// Construct a `Result` wrapping an immediate return of `res`.
    ///
    /// No network or disk activity will occur when this request is executed.
    pub fn immediate(res: Result<T>) -> Request<'static, T> {
        Request {
            adapter: super::adapter::NOOP,
            exec: ExecBox::noop(),
            call: super::call::immediate(res),
        }
    }

    /// Execute this request on the current thread, **blocking** until the result is available.
    pub fn exec_here(self) -> Result<T> {
        self.exec.exec();
        self.call.wait()
    }

    /// Returns `true` if a result is immediately available (`exec_here()` will not block).
    pub fn is_immediate(&self) -> bool {
        self.call.is_immediate()
    }
}

impl<'a, T> Request<'a, T> where T: Send + 'static {
    /// Execute this request on the adapter's executor, returning a type which can
    /// be polled for the result.
    pub fn exec(self) -> Call<T> {
        self.adapter.execute(self.exec);
        self.call
    }

    /// Add a callback to be executed with the request's return value when available, mapping
    /// it to another value (or `()` if no return value).
    ///
    /// `on_complete` will always be executed on the adapter's executor because the return
    /// value will not be available until the request is executed, whereas `on_result()`'s closure
    /// may be executed immediately if an immediate result is available.
    ///
    /// If a result is immediately available, `on_complete` will be discarded.
    ///
    /// ## Note
    /// `on_complete` should not be long-running in order to not block other requests waiting
    /// on the executor.
    ///
    /// ## Warning about Panics
    /// Panics in `on_complete` will cause the return value to be lost. There is no safety
    /// issue and subsequent requests shouldn't be affected, but it may be harder to debug
    /// without knowing which request caused the panic.
    pub fn on_complete<F, R>(self, on_complete: F) -> Request<'a, R>
    where F: FnOnce(T) -> R + Send + 'static, R: Send + 'static {
        self.on_result(|res| res.map(on_complete))
    }

    // RFC: add `on_error()`?

    /// Add a callback to be executed with the request's result when available, mapping it to
    /// another result (which can be `::Result<()>`).
    ///
    /// If a result is immediately available, `on_result` will be executed on the current thread
    /// with the result, and the return value will be immediately available as well.
    ///
    /// ## Note
    /// `on_result` should not be long-running in order to not block other requests waiting
    /// on the executor, or block the current thread if the result is immediate.
    ///
    /// ## Warning about Panics
    /// Panics in `on_result` will cause the return value to be lost. There is no safety
    /// issue and subsequent requests shouldn't be affected, but it may be harder to debug
    /// without knowing which request caused the panic.
    ///
    /// If the result is immediately available, panics in `on_result` will occur on the
    /// current thread.
    pub fn on_result<F, R>(self, on_result: F) -> Request<'a, R>
    where F: FnOnce(Result<T>) -> Result<R> + Send + 'static, R: Send + 'static {
        let Request { adapter, exec, call } = self;

        if call.is_immediate() {
            let res = on_result(call.wait());
            return Request::immediate(res);
        }

        let (mut guard, new_call) = super::call::oneshot(None);

        let new_exec = Box::new(move || {
            exec.exec();

            guard.complete(
                on_result(call.wait())
            );
        });

        Request {
            adapter: adapter,
            exec: new_exec,
            call: new_call,
        }
    }
}

fn exec_request<A, B>(adpt: &A, head: &mut RequestHead, body: B) -> Result<Response>
where A: AbsAdapter, B: Body {

    adpt.intercept(head);

    let mut readable = try!(body.into_readable(adpt));

    if let Some(content_type) = readable.content_type {
        head.header(ContentType(content_type));
    }

    let request = try!(adpt.request_builder(head));

    request.body(&mut readable.readable).send().map_err(Into::into)
}

// FIXME: remove the inferior version and inline this when this is stabilized.
#[cfg(feature = "nightly")]
fn prepend_str(prepend: &str, to: &mut String) {
    to.insert_str(0, prepend);
}

// Stable workaround that avoids unsafe code at the cost of an additional allocation.
#[cfg(not(feature = "nightly"))]
fn prepend_str(prepend: &str, to: &mut String) {
    let cap = prepend.len().checked_add(to.len())
        .expect("Overflow evaluating capacity");

    let append = mem::replace(to, String::with_capacity(cap));

    *to += prepend;
    *to += &*append;
}