rtv 4.0.1

Minimal HTTP/S client that supports nonblocking and streaming requests using mio.
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

//! This module contains definitions for the HTTP types that the user interacts with.
//!
//! It provides a [`RequestBuilder`] that allows constructing requests
//! as well as the [`Response`] type used to receive responses using a [`Client`](crate::Client).
//! The [`SimpleClient`](crate::SimpleClient) uses it's own response types.

use std::{fmt, time::Duration, ops::Range, io};

/// An HTTP method.
/// The default method is `GET`.
#[derive(Clone, Default)]
pub enum Method {
    #[default]
    Get,
    Post,
    Put,
    Delete,
    Patch,
    Head,
    Options,
    Trace,
}

/// If the connection should use tls or not.
/// 
/// ```
/// Plain = HTTP
/// Secure = HTTPS
/// ```
///
#[derive(Clone, Copy, Default)]
pub enum Mode {
    #[default]
    Plain,
    #[cfg(feature = "tls")]
    Secure,
}

/// An HTTP URI.
/// The path may start with a `/` or it may not.
#[derive(Clone, Default)]
pub struct Uri<'a> {
    pub host: &'a str,
    pub path: &'a str,
}

/// An HTTP query.
#[derive(Clone)]
pub struct Query<'a> {
    pub name: &'a str,
    pub value: &'a str,
}

/// An HTTP header.
#[derive(Clone)]
pub struct Header<'a> {
    pub name: &'a str,
    pub value: &'a str,
}

/// The ID assigned to a request.
///
/// You can use it to check if a response belongs to a request.
///
/// The inner number will start at `0` and count up by `1` (wrapping) for every
/// request sent by a perticular client. You can rely on this behaviour.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReqId {
    pub inner: usize,
}

/// Used to build a request.
/// See [`Request`].
#[derive(Default, Clone)]
pub struct RequestBuilder<'a> {
    request: Request<'a>, // only partially populated
}

impl<'a> RequestBuilder<'a> {

    /// Sets the `timeout`.
    /// By default requests do not have a timeout.
    #[inline(always)]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.request.timeout = Some(timeout);
        self
    }

    #[inline(always)]
    pub fn method(mut self, method: Method) -> Self {
        self.request.method = method;
        self
    }

    /// Sets the `mode` to [`Mode::Secure`].
    #[cfg(feature = "tls")]
    #[inline(always)]
    pub fn secure(mut self) -> Self {
        self.request.mode = Mode::Secure;
        self
    }

    /// Alias to [`secure`](RequestBuilder::secure).
    #[cfg(feature = "tls")]
    #[inline(always)]
    pub fn https(self) -> Self {
        self.secure()
    }

    /// Set the uri.host component of this request.
    #[inline(always)]
    pub fn host(mut self, host: &'a str) -> Self {
        self.request.uri.host = host;
        self
    }

    /// Set the uri.path component of this request.
    #[inline(always)]
    pub fn path(mut self, path: &'a str) -> Self {
        self.request.uri.path = path;
        self
    }

    /// Add a query parameter to the path.
    ///
    /// # Example
    ///
    /// The uri `example.com?foo=1&bar=2` could be constructed
    /// using following code:
    /// `Request::build().host("example.com").query("foo", "1").query("bar", "2")`
    #[inline(always)]
    pub fn query(mut self, name: &'a str, value: &'a str) -> Self {
        self.request.queries.push(Query { name, value });
        self
    }

    /// Insert a header into this request.
    ///
    /// For information on which headers are managed by rtv, see the [`Request`] documentation.
    #[inline(always)]
    pub fn set(mut self, name: &'a str, value: &'a str) -> Self {
        self.request.headers.push(Header { name, value });
        self
    }

    /// Alias to [`set`](RequestBuilder::set).
    #[inline(always)]
    pub fn header(self, name: &'a str, value: &'a str) -> Self {
        self.set(name, value)
    }

    /// Set a cookie.
    #[inline(always)]
    pub fn cookie(mut self, name: &'a str, value: &'a str) -> Self {
        self.request.cookies.push(Header { name, value });
        self
    }

    /// Insert the `User-Agent` header with the specified value.
    #[inline(always)]
    pub fn user_agent(self, value: &'a str) -> Self {
        self.set("User-Agent", value)
    }


    /// Update the request body with the specified data.
    #[inline(always)]
    pub fn send<T: AsRef<[u8]> + ?Sized>(mut self, body: &'a T) -> Self {
        self.request.body = body.as_ref();
        self
    }

    /// Get the request.
    /// You don't have to use this, since all functions that send a `Request` can also
    /// take a `RequestBuilder` directly.
    #[inline(always)]
    pub fn finish(self) -> Request<'a> {
        self.request
    }

}

/// This just calls [`finish`](RequestBuilder::finish) and then [`format`](Request::format).
impl<'a> From<RequestBuilder<'a>> for RawRequest {
    #[inline(always)]
    fn from(builder: RequestBuilder<'a>) -> Self {
        builder.finish().format()
    }
}

/// This just calls [`format`](Request::format).
impl<'a> From<Request<'a>> for RawRequest {
    #[inline(always)]
    fn from(request: Request<'a>) -> Self {
        request.format()
    }
}

/// Represents an HTTP request.
/// You can build a request either through this struct directly
/// or through a [`RequestBuilder`].
///
/// These headers will be set automatically and are managed by rtv:
/// - `Content-Length: ...`
/// - `Connection: close`
/// - `Accept-Encoding: identity`
///
/// You can overwrite the `Accept-Encoding` header which will cause it
/// to no longer be automatically set if you wanna receive encoded body data.
/// You cannot overwrite the other automatic headers.
///
/// # Example
///
/// Create a request using a builder.
///
/// ```rust
/// let req = Request::get().secure().host("example.com");
/// ```
///
/// Overwrite the `Accept-Encoding` header.
///
/// ```rust
/// let req = Request::get().set("Accept-Encoding", "gzip");
/// ```
///
/// Create a request directly,
/// although this is not recommended.
///
/// ```rust
/// let req = Request {
///     uri: Uri { host: "example.com", path: "" },
///     timeout: Some(Duration::from_secs(2)),
///     ..Default::default(),
/// };
/// ```
///
#[derive(Clone, Default)]
pub struct Request<'a> {
    pub timeout: Option<Duration>,
    pub method: Method,
    pub mode: Mode,
    pub uri: Uri<'a>,
    pub queries: Vec<Query<'a>>,
    pub headers: Vec<Header<'a>>,
    pub cookies: Vec<Header<'a>>,
    pub body: &'a [u8],
}

impl<'a> Request<'a> {

    /// Build a request. For [`Method::Get`] and [`Method::Post`] there are two
    /// convencience functions.
    /// # Example
    /// Create a request using a builder and set the method to `Delete`.
    /// ```rust
    /// let req = Request::build().method(Method::Delete).host("example.com");
    /// ```
    /// Oh no we just deleted the exam-
    pub fn build() -> RequestBuilder<'a> {
        RequestBuilder::default()
    }

    /// Build a request with the `GET` method.
    /// 
    /// Other methods are available through [`Method`].
    pub fn get() -> RequestBuilder<'a> {
        RequestBuilder::default().method(Method::Get)
    }

    /// Build a request with the `POST` method.
    ///
    /// Other methods are available through [`Method`].
    pub fn post() -> RequestBuilder<'a> {
        RequestBuilder::default().method(Method::Post)
    }

    /// Formats this request into valid http bytes.
    ///
    /// This will copy all referenced data and thus no longer requires any lifetimes.
    pub fn format(&self) -> RawRequest {

        let method = match self.method {
            Method::Get     => "GET",
            Method::Post    => "POST",
            Method::Put     => "PUT",
            Method::Delete  => "DELETE",
            Method::Patch   => "PATCH",
            Method::Head    => "HEAD",
            Method::Options => "OPTIONS",
            Method::Trace   => "TRACE",
        };

        let host = self.uri.host;
        let trimmed_path = self.uri.path.trim_start_matches("/");

        let mut path_builder = trimmed_path.to_string();
        for (idx, Query { name, value }) in self.queries.iter().enumerate() {
            path_builder += if idx == 0 { "?" } else { "&" };
            path_builder += name;
            path_builder += "=";
            path_builder += value;
        }

        let mut headers = String::new();
        let mut overwrite_encoding = false;

        headers += "Content-Length: ";
        headers += &self.body.len().to_string();
        headers += "\r\n";

        headers += "Connection: close";
        headers += "\r\n";

        for Header { name, value } in self.headers.iter() {
            if *name == "Connection" || *name == "Content-Length" {
                panic!("The `{}` header is managed by rtv, for more info see the `Request` documentation", name);
            }
            else if *name == "Accept-Encoding" { overwrite_encoding = true }
            headers += name;
            headers += ": ";
            headers += value;
            headers += "\r\n";
        }

        headers += "Cookie: ";
        for Header { name, value } in self.cookies.iter() {
            headers += name;
            headers += "=";
            headers += value;
            headers += "; ";
        }

        headers += "\n";

        if !overwrite_encoding {
            headers += "Accept-Encoding: identity";
            headers += "\r\n";
        }

        let head = format!("{} /{} HTTP/1.1\r\nHost: {}\r\n{}\r\n", method, path_builder, host, headers);
        let host_idx = head.find("Host: ").unwrap() + 6;
        let mut bytes = head.into_bytes();

        bytes.extend_from_slice(self.body);

        RawRequest {
            bytes,
            mode: self.mode,
            timeout: self.timeout,
            host: host_idx .. host_idx + self.uri.host.len()
        }

    }

}

pub struct RawRequest {
    pub bytes: Vec<u8>,
    pub mode: Mode,
    pub timeout: Option<Duration>,
    host: Range<usize>, // where in `bytes` the host is
}

impl RawRequest {
    pub fn host(&self) -> &str {
        std::str::from_utf8(
            &self.bytes[self.host.clone()]
        ).unwrap()
    }
}

/// An owned HTTP header. This is used in a response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedHeader {
    pub name: String,
    pub value: String,
}

impl From<&httparse::Header<'_>> for OwnedHeader {
    fn from(header: &httparse::Header) -> Self {
        Self { name: header.name.to_string(), value: String::from_utf8_lossy(header.value).to_string() }
    }
}

/// A status code and message for a response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
    pub code: u16,
    pub reason: String,
}

/// The `Head` of a response. This is not to be confused with an HTTP `Header`.
///
/// The response head contains informations about the response.
///
/// Use the alternate debug formatter `{:#?}` to print out verbose information
/// including all headers and more.
#[derive(Clone, PartialEq, Eq)]
pub struct ResponseHead {
    pub status: Status,
    pub headers: Vec<OwnedHeader>,
    // `0` if not present
    pub content_length: usize,
    // `true` if chunked transfer encoding is used
    pub transfer_chunked: bool,
}

impl ResponseHead {

    /// Get the value of a header. Returns `None` if the header could not be found.
    ///
    /// This does a linear search through the inner vec.
    pub fn get_header<'d>(&'d self, name: &str) -> Option<&'d str> {
        self.headers.iter().find_map(Self::match_header(name))
    }

    /// Get an Iterator over all the headers.
    pub fn all_headers<'d>(&'d self, name: &'d str) -> impl Iterator<Item = &'d str> {
        self.headers.iter().filter_map(Self::match_header(name))
    }

    fn match_header<'d>(name: &'d str) -> impl for<'e> Fn(&'e OwnedHeader) -> Option<&'e str> + 'd { // i know the `+ 'd` is technically incorrect
        move |header| if header.name == name { Some(&header.value[..]) } else { None }
    }

}

impl fmt::Debug for ResponseHead {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            writeln!(f, "ResponseHead {{")?;
            writeln!(f, "    headers: [")?;
            for header in self.headers.iter() {
                writeln!(f, "        {}: {}", header.name, header.value)?;
            }
            writeln!(f, "    ]")?;
            writeln!(f, "    status: {:?}", self.status)?;
            writeln!(f, "    content_length: {:?}", self.content_length)?;
            writeln!(f, "    transfer_chunked: {:?}", self.transfer_chunked)?;
            write!(f, "}}")?;
            Ok(())
        } else {
            if self.transfer_chunked {
                write!(f, "ResponseHead {{ status: {}: {}, transfer_chunked: true, ... }}",
                    self.status.code,
                    self.status.reason)
            } else {
                write!(f, "ResponseHead {{ status: {}: {}, content_length: {}, ... }}",
                    self.status.code,
                    self.status.reason,
                    self.content_length)
            }
        }
    }
}

/// An HTTP response. Contains a [`ResponseState`].
///
/// A `Response` is **not** a full HTTP response but just one part of it. This arcitecture
/// allows for streaming the response data, not waiting for everything to arrive.
/// It also contains the response id, that could be obtained earlier when sending the request.
/// # Example
/// Here is an example of how matching against a response might look.
/// ```rust
/// match resp.state {
///     ResponseState::Head(head) => println!("content_length is {} bytes", head.content_length),
///     ResponseState::Data(some_data) => response_data_buffer.extend_from_slice(&some_data),
///     other if other.is_error() => panic!("error: {:?}", other),
///     ...
/// }
/// ```
#[derive(Debug)]
pub struct Response {
    pub id: ReqId,
    pub state: ResponseState,
}

impl Response {

    pub(crate) fn new(id_num: usize, state: ResponseState) -> Self {
        Self { id: ReqId { inner: id_num }, state }
    }

}

/// The state of a response.
///
/// For more information see [`Request`].
/// The first thing you receive will always be [`ResponseState::Head`].
///
/// In order to determine if a request has finished have a look at
/// [`is_done`](ResponseState::is_done),
/// [`is_error`](ResponseState::is_error),
/// [`is_finished`](ResponseState::is_finished)
///
/// After eiteher of these three methods have returned `true` you will receive no more
/// events for this Request.
#[derive(PartialEq, Eq)]
pub enum ResponseState {
    /// The response head. Contains information about what the response contains.
    Head(ResponseHead),
    /// We have read **some** data for this request. The data is not transmitted all at once,
    /// everytime the server sends a chunk of data you will receive one of these.
    Data(Vec<u8>),
    /// The request is done and will not generate any more events.
    Done,
    /// The request timed out. This will only occur if you set a timeout for a request.
    TimedOut,
    /// The server unexpectedly closed the connection for this request.
    Aborted,
    /// The host could not be found.
    UnknownHost,
    /// An http protocol error occured while reading the response. For example the server could've send invalid data.
    ProtocolError,
}

impl ResponseState {

    /// Returns `true` if this state signals that the request is finished.
    ///
    /// If true, this request will no longer generate any events.
    /// This is implemented as:
    /// ```
    /// self.is_done() || self.is_error()
    /// ```
    pub fn is_finished(&self) -> bool {
        self.is_done() || self.is_error()
    }

    /// Returns `true` if this state is `Done`.
    ///
    /// If true, this request will no longer generate any events.
    pub fn is_done(&self) -> bool {
        match self {
            Self::Head(..)      => false,
            Self::Data(..)      => false,
            Self::Done          => true, // <-
            Self::TimedOut      => false,
            Self::Aborted       => false,
            Self::UnknownHost   => false,
            Self::ProtocolError => false,
        }
    }

    /// Returns `true` if this state is either `Dead`, `TimedOut`, `UnknownHost` or `Error`.
    ///
    /// If true, this request will no longer generate any events.
    pub fn is_error(&self) -> bool {
        match self {
            Self::Head(..)      => false,
            Self::Data(..)      => false,
            Self::Done          => false,
            Self::TimedOut      => true, // <-
            Self::Aborted       => true, // <-
            Self::UnknownHost   => true, // <-
            Self::ProtocolError => true, // <-
        }
    }

    /// Returns an appropriate error if `is_error` is true.
    pub fn into_io_error(&self) -> Option<io::Error> {
        match self {
            ResponseState::Aborted       => Some(io::Error::from(io::ErrorKind::ConnectionAborted)),
            ResponseState::TimedOut      => Some(io::Error::from(io::ErrorKind::TimedOut)),
            ResponseState::UnknownHost   => Some(io::Error::new(io::ErrorKind::Other, "unknown host")),
            ResponseState::ProtocolError => Some(io::Error::new(io::ErrorKind::Other, "http protocol error")),
            _other => None
        }
    }

}

/// This doesn't print the `ResponseState::Data` raw or as a string, instread it just prints the length.
impl fmt::Debug for ResponseState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TimedOut => write!(f, "TimedOut"),
            Self::Head(head) => write!(f, "Head({:?})", head),
            Self::Data(data) => write!(f, "Data({} bytes)", data.len()),
            Self::Done => write!(f, "Done"),
            Self::Aborted => write!(f, "Dead"),
            Self::UnknownHost => write!(f, "UnknownHost"),
            Self::ProtocolError => write!(f, "Error"),
        }
    }
}