Skip to main content

Fetcher

Struct Fetcher 

Source
pub struct Fetcher { /* private fields */ }
Expand description

An async HTTP client for one remote.

A fetcher holds the mirrors, the headers, the credentials, and the TLS configuration of one remote. It serves a Target::Url from the origin of that URL. A clone of a Fetcher is another handle on the same connection pool and the same admission limit. The clone has the counters of received body bytes of the handle. counted gives a handle with more counters.

§Connections

The TLS handshake selects the protocol: ALPN offers h2 and http/1.1, and the fetcher uses the choice of the server. Over cleartext, the fetcher uses HTTP/1.1. The pool keeps one HTTP/2 connection for each origin, which carries concurrent requests. The pool also keeps HTTP/1.1 connections, and the fetcher uses one again after the previous body is read to the end.

The pool key holds three terms:

  • the endpoint of the connection
  • true if the connection presents the configured client certificate
  • true if the connection goes to a proxy and carries absolute-form requests.

The endpoint is the origin for a direct connection and for a tunnel, because the TLS of a tunnel reaches the origin. For a proxied cleartext connection, the endpoint is the proxy. So a URL target shares a connection with a mirror at the same origin. One proxy connection carries requests for all cleartext origins.

An unsuccessful status, or a Content-Length over the cap of the request, ends an attempt with a response body in flight. If the declared length is 64 KiB or less, the fetcher reads the body to the end. The HTTP/1.1 connection then goes back to the pool. If the declared length is larger, or if there is none, the fetcher closes the connection.

A fetch with FetchRequest::max_error_body reads the body of the unsuccessful response that it reports, up to that cap, with or without a declared length. If the body ends within the cap, the HTTP/1.1 connection goes back to the pool. If it grows past the cap, the fetcher closes the connection. Fetcher::fetch states the rule in “Error responses”.

A 404 is the usual answer for an object that the remote does not hold. So this rule saves a connection setup for each absent object.

All such reads of one attempt share one progress_timeout window, whatever the number of hops. A peer can declare a short body on each hop and send fewer bytes. Such a peer uses the window once, and the later reads close their connections and do not wait.

Implementations§

Source§

impl Fetcher

Source

pub async fn new(options: FetcherOptions) -> Result<Fetcher>

Creates a fetcher from options.

If the mirror list is empty, the fetcher serves Target::Url requests alone.

The fetcher has no counters of received body bytes. counted gives a handle that has counters.

The function is async, because TrustRoots::System, the default, reads the host trust store on the blocking pool. An encrypted client key runs a key derivation function, also on the blocking pool. Under TrustRoots::Pem with no encrypted client key, all work is in memory, and the function never yields.

§Trust store

The function reads the system store if a fetch can open a handshake. That is the case if one or more mirrors are https. It is also the case if the mirror list is empty, because a request can then name an https URL. It is also the case if max_redirects is more than zero, because a redirect can go to an https URL.

A fetcher with all mirrors http that follows no redirect reads no store and holds no trust anchor. If a request of that fetcher names an https URL of its own, the fetch fails before admission and names the origin. A host without a CA bundle still reaches a cleartext remote.

Under either bypass variant of TrustRoots, the function reads no store, so an empty host store fails no fetcher. With no encrypted client key, the function then never yields.

§Errors
Source

pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Fetcher

Returns a handle on this fetcher that adds counters of received body bytes.

The new handle shares the configuration, the connection pool, and the admission limit of this handle. It has the counters of this handle and the counters of received. A clone of the new handle has the same counters.

Each response body of a request of the new handle adds the bytes that it takes from the connection to each of these counters. This includes the bytes of a body before it fails, the body of a Refetch, a body that the caller drops before its end, and the response body of an upload. A request does not count a response that it does not give to the caller: a redirect, an unsuccessful status of a fetch, or a refused response.

The counters of this handle do not change. A request of this handle adds to the counters of this handle alone. Each data frame costs one relaxed atomic add for each counter. A counter that the new handle has two times gets the bytes two times.

Source

pub fn max_outstanding(&self) -> usize

Returns the number of requests that the fetcher admits at one time.

The number is max_outstanding of the options, and at least 1. All handles on one fetcher share this limit.

Source

pub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched>

Sends request to each destination in turn and returns the response.

§Retries

A path target goes to each mirror, in the mirror order. The fetch resolves the destination of a mirror at the attempt that uses it. A URL target has the one destination that the URL names.

  • The fetch tries each destination in order before it retries.
  • Transport failures and the statuses 408, 429, and 5xx are retryable. If one or more destinations of a round fail that way, the fetch repeats the round, up to max_retries times. The delay before a repeat starts at 250ms, doubles each time, and stops at two seconds. A repeated round asks only the destinations with a retryable failure.
  • Each other unsuccessful status is definitive. The fetch does not ask that destination again, because its answer is the same in each round.
  • The expiry of connect_timeout, progress_timeout, or low_speed is a transport failure. The fetch reports the deadline that expires first.

The hop count belongs to one attempt. So a retryable status on a hop makes the whole attempt retryable, and the repeated round starts again from the destination that the route names.

The retries end at the response head. So if a body fails in transit, the caller gets a failed read. refetching fetches such a body again.

§Failure order

A fetch ends if it has no more destinations to ask or no more rounds to repeat. In both cases, it reports a definitive answer if it got one, and the first retryable failure if not.

A caller can act on a definitive answer, for example a 404 that states that the object is absent. So the fetch reports such an answer from any round, and an earlier retryable failure does not hide it. Of two definitive answers, the fetch reports the answer that it got first. In one round, this is the mirror order.

§Redirects

A 301, 302, 303, 307, or 308 sends the attempt to the URL of its Location header, up to max_redirects times. A fetch is a GET, so none of the five statuses changes the method of the next hop.

The fetch resolves Location against the URL of the response that carries it. So Location can be an absolute URL, a relative URL (/other/path, sibling), or a scheme-relative URL (//host/path). The resolution normalizes the result, as the HTTP specification prescribes for a redirect:

  • it resolves dot segments
  • it reads a backslash as a path separator
  • it removes tabs and newlines
  • it percent-encodes a character that a path or a query cannot carry
  • it puts an IPv4 or an IPv6 host in canonical form
  • it removes the fragment.

A Target::Url goes on the wire as the caller wrote it. So one string as a URL target and as a Location can reach the server as two different request targets.

The fetch refuses two hops definitively: a scheme other than http or https, and a hop from https to http. The Error::Fetch names the URL that redirected and the URL that it named. On a fetcher with no trust anchors, the fetch also refuses a hop to a TLS origin in the same way. The fetch follows a hop from http to https.

If a response with one of the five statuses has no readable Location, the fetch reports the status, whatever the hop count. This applies to a missing header, an empty value, a value that is not text, and a value that the resolution cannot read.

Authorization, Proxy-Authorization, and Cookie from either layer go to the origin that the route names. They also go to a hop at that origin: the same scheme, host, and port.

The fetch removes them for a hop at another origin. A removed credential stays removed for the rest of the attempt, also on a redirect back to the named origin. At that time, the operator of the other origin has the request.

The signer follows the same rule. It signs each hop at the named origin again, with the path and the query of that hop. It signs no hop at another origin, and no hop after it.

All other headers go to each hop, also the User-Agent and the Accept-Encoding of the fetcher. The fetcher presents a configured client certificate to the origin that the route names and to no other origin. So the pool keeps the connections with the certificate apart from the connections without it.

The fetch discards the body of an intermediate response as it discards the body of an unsuccessful response. So if the declared length is 64 KiB or less, the HTTP/1.1 connection goes back to the pool. A chain on one origin then uses one connection. If the intermediate responses declare more, or declare no length, the chain opens a connection for each hop.

The validators go to each hop, because they describe the resource. A 304 from any hop is the answer of the fetch. Each message names the URL of the response that answered, which after a redirect is the URL of the last hop.

A fetch with max_error_body and a redirect limit of zero gets each redirect as an unsuccessful response. So the caller reads its headers, for example Location, and its body. A redirect with no usable Location is also such a response, at any limit.

§Content coding

A fetch gives the bytes that the remote stores. So each request carries Accept-Encoding: identity, and asks for no content coding. Without that header, a server can compress a response and stay within the HTTP specification. The body then holds bytes other than the bytes that the checksum of the object names.

A 200 response, or a 206 response to a request with a Range header, fails the attempt definitively with Error::ContentEncoded in two cases: a Content-Encoding other than identity, or a Transfer-Encoding other than chunked and identity. This applies whichever layer asked for the coding. A caller that wants a coded body decodes it outside the fetcher.

chunked frames a message, and the connection removes the framing. So a response with chunked alone gives the body as the remote wrote it.

§Error responses

A request with max_error_body set keeps the unsuccessful response that the fetch reports. The Error::HttpStatus then carries an ErrorResponse with the headers of that response, and its body if the whole body is within the cap.

  • The fetch reads the body of a failure only if the failure order can make it the reported failure. So it reads at most two bodies: one retryable failure and one definitive answer. It keeps the body of the failure that it reports. If each round gets a 503, the error holds the body of the first 503. A 503 and then a 404 give the body of the 404.
  • The read takes place within one progress_timeout from the arrival of the response head, and within fetch_timeout. The low_speed rule does not apply to it.
  • The fetch does not read a body that declares a coding or a Content-Length over the cap. It discards such a body, and the error holds the headers alone.
  • A body that grows past the cap, fails in transit, or does not end within the window gives the headers alone. The fetch keeps no part of such a body.
  • The read never changes the retry class of the status.
  • The bytes of a kept body do not count in the received counters of counted.

Before a body arrives, the read reserves at most 64 KiB, whatever length the response declares. The capacity of a kept body never passes the cap. So the fetch holds at most two kept bodies of at most the cap each, one retryable and one definitive, and one frame of the body that it reads.

§Errors

If more than one destination fails, the failure order rules state which error the fetch reports.

  • Error::Fetch before admission, if a path holds a ? or a #, if the query of a Target::PathQuery holds a #, or if the fetcher has no mirror for a path target.
  • Error::Fetch before admission, if a URL target is not a valid absolute URL, or holds a fragment or userinfo.
  • Error::Unsupported if the scheme of a URL target is neither http nor https.
  • Error::Fetch before admission, if a request header is invalid, is Host, or is a header that the connection layer sets.
  • Error::Fetch before admission, if an Authorization header is beside basic_auth.
  • Error::Fetch before admission, if the fetcher has a signer and the request carries basic_auth or an Authorization header.
  • Error::Fetch before admission, if a credential can reach a cleartext destination, and neither allow_cleartext_credentials nor FetcherOptions::allow_cleartext_credentials is true.
  • Error::Fetch before admission, if the route names a TLS destination and the fetcher holds no trust anchors.
  • Error::Fetch if a transport failure ends the rounds: a failed connect, handshake, or proxy CONNECT, or an expired deadline.
  • Error::Fetch if the fetch refuses a redirect hop, as the redirect rules state.
  • Error::Fetch if hyper cannot build a request, for example from an invalid validator value.
  • The error of the signer, unchanged, if it fails. An Error::Fetch if it returns a header that a request cannot carry. The fetch asks no other destination and repeats no round.
  • Error::Fetch if fetch_timeout expires.
  • Error::HttpStatus if a destination answers with a status other than 200 and 304, and other than 206 to a request with a Range header. This includes a redirect that the fetch does not follow: no usable Location, or a redirect limit of zero. With max_error_body, the error carries the response, as the rules of the error responses state.
  • Error::RedirectLimit if an attempt follows max_redirects redirects, and the next response names a URL to follow.
  • Error::FetchTooLarge if the Content-Length of the response is more than max_size.
  • Error::ContentEncoded if the response declares a coding, as the content coding rules state.
Source

pub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r>

Returns a Refetch of request, which fetches a failed body again.

Refetch states the budget that it spends.

Source

pub async fn upload(&self, request: UploadRequest<'_>) -> Result<Uploaded>

Sends request and tries each destination until one takes it.

Each final status returns an Uploaded, also 408, 429, and 5xx. The mirrors, the proxy, TLS, the client certificate, the headers, the credentials, the signer, and the cleartext rule apply to an upload as they apply to fetch. An upload can also carry a BearerToken of its own as its credential. The fetcher sets no Content-Type header and no Expect header.

The hand-over gives the request to hyper. A failure before the hand-over returns the error that a fetch returns. A failure after the hand-over returns Error::UploadInterrupted.

§Retries

The fetcher tries an upload again only while no part of the request is sent. The request is unsent if the attempt fails before hyper accepts it, in one of these steps:

  • the connect
  • the CONNECT tunnel
  • the TLS handshake
  • the HTTP handshake
  • the wait for a ready connection.

The request is also unsent if hyper gives it back unwritten. The bytes of a CONNECT go to the proxy alone and are no part of the request.

An unsent attempt spends a round as a retryable failure of a fetch does. The upload asks the next mirror, then repeats the round after the backoff, up to max_retries times. A 407 to the CONNECT is definitive. If the rounds run out before the request is sent, the upload returns the Error::Fetch that a fetch returns.

If the writer of a streamed body is dropped before it closes the body, the upload fails before the hand-over. It fails with Error::Fetch and sends nothing.

All other outcomes count as sent. The upload then ends on the destination that took it, and asks no other mirror and no other round. A failure after the hand-over fails the upload with Error::UploadInterrupted, because the server can have received the whole request and acted on it. An HTTP/2 stream that the server refuses or resets after the hand-over is such a failure.

§Redirects

For a body given whole, the upload follows a 307 or a 308. It keeps the method and sends the bytes again. The redirect rules of fetch apply: the redirect limit, the refusal of a hop from https to http, and the scope of the credentials and of the signer.

The first hop sends the request. So a failure on a later hop, a refused hop, and a redirect past the limit each fail the upload with Error::UploadInterrupted.

The upload returns these redirects as their status in an Uploaded:

  • a redirect status other than 307 and 308
  • each redirect of a streamed body
  • a 307 or a 308 with no Location that the upload can read
  • each redirect if max_redirects is 0.
§Unsuccessful answers

An answer other than 2xx returns an Uploaded with its status and its headers, also when the upload cannot deliver its body. The upload does not deliver a body that declares a coding in Content-Encoding or Transfer-Encoding, or a Content-Length over max_response. It withholds such a body: Uploaded::body_withheld returns true, the body reads as empty, and the connection closes. So a definitive refusal, for example a 403 behind a proxy that compresses it, keeps its status, and the caller does not take it for an interrupted upload.

A 2xx answer with such a body fails the upload with Error::UploadInterrupted.

§Connections

An upload uses the pooled HTTP/2 connection of its origin. It takes an idle HTTP/1.1 connection from the pool only if the connection became idle less than 2 seconds ago. Otherwise, it opens a connection of its own.

A server can close an idle connection at any time. If hyper began to write an upload over a connection that the server closed, the upload counts as sent. A server closes an idle connection at the end of its idle timeout, so it keeps a connection that became idle a short time ago.

If a pooled HTTP/1.1 connection fails before hyper writes the request, the fetcher drops the connection. The upload then continues over a new connection and spends no round.

The HTTP/1.1 connection of an upload goes back to the pool if both bodies end cleanly. That is, hyper takes the end of the request body before the response head arrives. Then the caller reads the response body to its end with no failure. Each of these closes the connection:

  • a response that closes the connection
  • an HTTP/1.0 response
  • an answer that arrives before the end of the request body
  • a response body that fails
  • a response that is dropped before its end.
§The response ends the request body

A server can answer before it reads the whole request body. If the response body ends or is dropped before the request body ends, the fetcher fails the request body. The writer then gets io::ErrorKind::BrokenPipe, and hyper stops the body.

The stop of the body closes an HTTP/1.1 connection and resets an HTTP/2 stream. The same applies to a response that the upload does not deliver: a followed redirect, a refused coding, a declared length over the cap, and a withheld body.

§Deadlines

Before the hand-over, a wait of the writer has no bound of its own. This applies at the gate, during the connect, and during the backoff between rounds. The low-speed rule does not apply to an upload.

§Errors

If more than one destination fails before the hand-over, the failure order of fetch states which error the upload returns.

  • Error::Fetch before admission, if a path holds a ? or a #, if the query of a Target::PathQuery holds a #, or if the fetcher has no mirror for a path target.
  • Error::Fetch before admission, if a URL target is not a valid absolute URL, or holds a fragment or userinfo.
  • Error::Unsupported if the scheme of a URL target is neither http nor https.
  • Error::Fetch before admission, if a request header is invalid, is Host, or is a header that the connection layer sets.
  • Error::Fetch before admission, if two credentials of the request meet: basic_auth, bearer_token, and an Authorization header. A bearer token that is not token68 also fails.
  • Error::Fetch before admission, if the fetcher has a signer and the request carries one of these credentials: basic_auth, bearer_token, or an Authorization header.
  • Error::Fetch before admission, if a credential can reach a cleartext destination, and neither allow_cleartext_credentials nor FetcherOptions::allow_cleartext_credentials is true.
  • Error::Fetch before admission, if the route names a TLS destination and the fetcher holds no trust anchors.
  • Error::Fetch before admission, if the method is DELETE and the body is not an empty UploadBody::bytes.
  • Error::Fetch if a transport failure ends the rounds before the hand-over: a failed connect, handshake, or proxy CONNECT, or an expired deadline.
  • Error::Fetch if hyper cannot build the request.
  • The error of the signer, unchanged, if it fails before the hand-over. An Error::Fetch if it returns a header that a request cannot carry. The upload asks no other destination and repeats no round. A failure of the signer on a redirect hop is a failure after the hand-over.
  • Error::Fetch if the writer of a streamed body is dropped before the hand-over.
  • Error::Fetch if fetch_timeout expires before the hand-over.
  • Error::UploadInterrupted if a failure occurs after the hand-over. This includes a refused redirect hop, a redirect past the limit, and a 2xx response that declares a coding or a Content-Length over max_response. The message names the cause.
§Examples
use ostrya_fetch::{Fetcher, FetcherOptions, UploadBody, UploadRequest};
let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
let body = UploadBody::bytes(b"report".to_vec());
let uploaded = fetcher.upload(UploadRequest::path("inbox/report", body)).await?;
println!("the server answered {}", uploaded.status());

Trait Implementations§

Source§

impl Clone for Fetcher

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Fetcher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Fetcher

§

impl !UnwindSafe for Fetcher

§

impl Forget for Fetcher

§

impl Freeze for Fetcher
where *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze, *const ArcInner<[Arc<Atomic<u64>>]> is !null: Freeze, PhantomData<ArcInner<[Arc<Atomic<u64>>]>>: Freeze,

§

impl Move for Fetcher

§

impl Send for Fetcher
where Arc<Inner>: Send, Arc<[Arc<Atomic<u64>>]>: Send,

§

impl Sync for Fetcher
where Arc<Inner>: Sync, Arc<[Arc<Atomic<u64>>]>: Sync,

§

impl Unpin for Fetcher
where Arc<Inner>: Unpin, Arc<[Arc<Atomic<u64>>]>: Unpin,

§

impl UnsafeUnpin for Fetcher
where *const ArcInner<Inner> is !null: UnsafeUnpin, PhantomData<ArcInner<Inner>>: UnsafeUnpin, *const ArcInner<[Arc<Atomic<u64>>]> is !null: UnsafeUnpin, PhantomData<ArcInner<[Arc<Atomic<u64>>]>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more