JFLib

netio/client.rs#

Source: lib/netio/client.rs

client -- a blocking HTTP/1.1 client

  Client::new().request("GET", &url, &headers, body) -> Result<Response, HttpError>
  client.fetch(method, &url, &headers, body) -> Fetched { url: the last one, response }
  client.get_to(&url, &headers, max, on)   a download piece by piece (Part::Head, Part::Data)
  client.request_on(&stream, method, &url, &headers, body)   one request over a connection the
                                           caller opened (no proxy, no pool, no redirects)
  client.with_connector(Arc<dyn Fn(&Url, TcpStream) -> Result<Box<dyn Stream>, HttpError>>)
  client.with_proxy(Proxy)          HTTP proxies (netio::proxy; Proxy::from_env)
  client.with_pool(Arc<Pool>)       connections kept open for the next requests
  client.with_cookies(Arc<Mutex<Jar>>)   netpkt::cookie's jar: Set-Cookie stored, Cookie sent
  client.with_redirect_check(f)     f(from, to) before each redirect (false: the 3xx answer)
  client.request_async(method, &url, &headers, body) -> future of the answer (the request on
  plat::task's blocking pool: ui.spawn / block_on await it without blocking)
  client.download(&url, &headers, path, &ctl) -> future of the status: the body into the file
  (plat::AtomicFile: replaced only by a whole 2xx body), progress and cancel in ctl

The fields: connect_ms, timeout_ms (any single read or write), deadline_ms (a whole request,
its redirects included: see below; 0: none), max_body (the body as it came and after decoding),
user_agent, redirects (followed at most; 0: a 3xx answer comes back as it is) and decode.

decode (on by default): without an Accept-Encoding or Range header of the caller's, a request
offers "gzip, br" and a body in gzip, br, zstd (window up to 8 MiB, RFC 9659) or deflate (zlib)
is decoded as it arrives, through compress's stream decoders; Content-Encoding and
Content-Length then leave the answer's headers.  A body that does not decode is
HttpError::Encoding; stacked or unknown codings come back as they are.

Redirects (301, 302, 303, 307, 308 with a Location, RFC 9110 15.4): the Location is resolved
against the request's URL (Url::join) and handed to the redirect check; one from https to http
that it lets pass is refused (HttpError::Redirect);
303 (not after HEAD) and 301 / 302 after POST go on as GET without the body and its headers;
to another origin, Authorization, Cookie, Proxy-Authorization and Host stay behind (the jar's
cookies are those of the new URL).

Answers are read as RFC 9112 6.3 says: a status line "HTTP/1.x NNN" with a code of 100 to 599,
interim answers (1xx) skipped up to 16 of them, 101 refused (no upgrade was asked for); no body
after HEAD or with 204 and 304 (whatever Content-Length says), else the body by
Transfer-Encoding: chunked, else Content-Length, else up to the end of the connection.
A connection carries another request (the pool, Session) only after a body of known length
that was read to its end with no byte beyond it, and when neither side said close.

deadline_ms: each address connected to gets connect_ms or the time left, whichever is less;
every read waits for bytes only until the deadline (a TLS record that arrives in pieces too);
a request is written in pieces of 16 KiB, each with the time left as its timeout -- a server
that takes a piece byte by byte can still keep that piece's write going past the deadline; a
write that runs out of time is TimedOut. Outside the deadline: the name lookup (the resolver's
own timeouts) and the TLS handshake (the connector's: the socket's timeouts are set once, to
the time left when it begins, and each of its reads and writes may take that long; a handshake
that ends past the deadline, done or failed, is TimedOut).
  • enum HttpError

    • Url(String) -- not an http(s) URL, or https without a connector
    • Net(NetError)
    • Tls(String) -- the TLS layer refused (certificate, handshake)
    • Bad -- a malformed answer
    • TooLarge -- an answer over the size limit
    • File -- (download) the target file could not be created, written or put in place
    • Cancelled -- (download) cancelled through the Ctl, or the future was dropped
    • Redirect(String) -- a redirect that is not followed: from https to http, a Location that is not a URL, more than Client::redirects of them
    • Proxy(u16) -- the proxy refused the tunnel (its status; 407: it wants other credentials)
    • Encoding -- the body does not decode as its Content-Encoding says
  • type Connector = Arc<dyn Fn(&Url, TcpStream) -> Result<Box<dyn Stream>, HttpError> + Send + Sync>

  • type RedirectCheck = Arc<dyn Fn(&Url, &Url) -> bool + Send + Sync> asked before a redirect is followed: (from, to) -> false: the 3xx answer is the result

  • enum Part<'a> a piece of an answer that Client::get_to streams

    • Head(u16, &'a Headers) -- the status and the headers (first)
    • Data(&'a [u8]) -- the next bytes of the body
  • struct Fetched an answer and the URL it came from (after redirects)

    • url: Url
    • response: Response
  • struct Client

    • connect_ms: u32
    • timeout_ms: u32 -- the longest wait for any read or write
    • deadline_ms: u32 -- the longest a whole request may take, from connecting to the last byte of the body, redirects and retries included; what it bounds and what not: the module header (0: no limit beyond timeout_ms per read)
    • max_body: usize
    • user_agent: String
    • redirects: u8 -- redirects followed at most (0: a 3xx answer comes back as it is)
    • decode: bool -- offer gzip and br and decode the body (see the module header)
  • struct Pool connections kept open between requests (Client::with_pool): per origin, proxy and TLS layer, at most per_host of them and idle_ms long

    • per_host: usize
    • max_idle: usize
    • idle_ms: u32

impl Pool

  • fn new() -> Arc<Pool> 4 per host, 64 in all, 60 s
  • fn with_limits(per_host: usize, max_idle: usize, idle_ms: u32) -> Arc<Pool>
  • fn idle(&self) -> usize the connections waiting now
  • fn clear(&self) close them all

impl Client

  • fn new() -> Client

  • fn with_connector(mut self, c: Connector) -> Client the TLS layer for https URLs

  • fn with_proxy(mut self, p: Proxy) -> Client requests go through these proxies (netio::proxy)

  • fn with_pool(mut self, p: Arc<Pool>) -> Client connections stay open for the next requests (keep-alive); clones of the client share them

  • fn with_cookies(mut self, jar: Arc<Mutex<Jar>>) -> Client cookies: what answers set is stored in the jar, a request without a Cookie header of the caller's sends the jar's for its URL (netpkt::cookie, with the public suffix list)

  • fn with_redirects(mut self, n: u8) -> Client redirects: followed up to n (0: none)

  • fn with_redirect_check(mut self, f: RedirectCheck) -> Client each redirect first asks f(from, to); false: the 3xx answer is the result

  • fn cookies(&self) -> Option<&Arc<Mutex<Jar>>> the jar given to with_cookies

  • fn connect(&self, url: &Url) -> Result<Box<dyn Stream>, HttpError> open the connection a request to url goes over, directly (no proxy)

  • fn request(&self, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Response, HttpError> send one request and read the whole answer

  • fn fetch(&self, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Fetched, HttpError> request(), and the URL the answer came from (after redirects)

  • fn request_on(&self, s: &dyn Stream, method: &str, url: &Url, headers: &Headers, body: &[u8]) -> Result<Response, HttpError> One request over a connection the caller opened (a socket of its own, a test's stream): the client's headers, cookies and decoding, no proxy, pool or redirects; the request asks to close the connection, and the stream stays open (with deadline_ms, its timeouts are the time left as the request goes)

  • fn get_to(&self, url: &Url, headers: &Headers, max: u64, on: &mut dyn FnMut(Part<'_>) -> bool) -> Result<(u16, Headers), HttpError> a GET whose answer goes piece by piece to on (downloads larger than memory): first Part::Head (false: skip the body), then Part::Data for every piece of the body (false: stop, Err(HttpError::Bad)). The body may have up to max bytes. Redirects the client follows do not reach on. -> the status and the headers

  • fn get(&self, url: &Url, headers: &Headers) -> Result<Response, HttpError>

  • fn request_async(&self, method: &str, url: &Url, headers: &Headers, body: Vec<u8>) -> impl Future<Output = Result<Response, HttpError>> + use<> request() on the blocking pool (plat::task::spawn_blocking): a future of the answer

  • fn download(&self, url: &Url, headers: &Headers, path: &str, ctl: &Ctl) -> impl Future<Output = Result<u16, HttpError>> + use<> A GET whose body goes into the file at path, on the blocking pool. The file is replaced like plat::write_file (plat::AtomicFile) and only by the whole body of a 2xx answer; other answers leave it alone. ctl.progress counts the bytes (the total from Content-Length); ctl.cancel, or dropping the future, stops between pieces: Err(Cancelled), the file unchanged. -> the status

  • struct Session requests over one kept-alive connection (reconnected when the server closed it); the client's proxy, cookies and decoding apply, its pool and redirects do not

impl Session

  • fn new(client: Client, url: Url) -> Session

  • fn url(&self) -> &Url

  • fn request(&mut self, method: &str, target: &str, headers: &Headers, body: &[u8], max_body: usize) -> Result<Response, HttpError> one request (an answer of at most max_body bytes)

  • fn json_headers(token: &str) -> Headers "Bearer <token>" headers plus JSON content type

Source: docs/API.md in the JFLib repository.