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
trueif the connection presents the configured client certificatetrueif 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
impl Fetcher
Sourcepub async fn new(options: FetcherOptions) -> Result<Fetcher>
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
Error::Fetchif alow_speedrule holds a zero.Error::Fetchif a mirror URL is not a valid absolute URL, has no usable host, or holds a query string or userinfo.Error::Fetchif a mirror URL names a port that is not a number from 0 to 65535.Error::Unsupportedif the scheme of a mirror URL is neitherhttpnorhttps.Error::Fetchif a header name or value is invalid, or if a header isHostor a header that the connection layer sets.Error::Fetchif a mirror is cleartexthttp, the options hold a credential, andallow_cleartext_credentialsisfalse. The credentials arebasic_auth,bearer_token,signer, and anAuthorization,Proxy-Authorization, orCookieheader.Error::Fetchif two of these are set:basic_auth,bearer_token,signer, and anAuthorizationheader.Error::Fetchifbasic_authdoes not give a valid header value, or ifbearer_tokendoes not have the token68 syntax.Error::Unsupportedif a proxy URL is nothttp://host[:port],socks5://host[:port], orsocks5h://host[:port], from the options or from the environment.Error::Unsupportedif a SOCKS5 URL has a userinfo that SOCKS proxies refuses.Error::Unsupportedif a proxy variable has white space around its value.Error::Fetchif the TLS material does not parse or the TLS setup fails: a trust anchor, the client certificate, or the client key.ClientIdentity::key_passphrasestates the refusals of a client key.Error::Fetchif the system trust store holds no certificate, and one or more mirrors arehttpsor the mirror list is empty.
Sourcepub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Fetcher
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.
Sourcepub fn max_outstanding(&self) -> usize
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.
Sourcepub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched>
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_retriestimes. 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, orlow_speedis 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_timeoutfrom the arrival of the response head, and withinfetch_timeout. Thelow_speedrule does not apply to it. - The fetch does not read a body that declares a coding or a
Content-Lengthover 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::Fetchbefore admission, if a path holds a?or a#, if the query of aTarget::PathQueryholds a#, or if the fetcher has no mirror for a path target.Error::Fetchbefore admission, if a URL target is not a valid absolute URL, or holds a fragment or userinfo.Error::Unsupportedif the scheme of a URL target is neitherhttpnorhttps.Error::Fetchbefore admission, if a request header is invalid, isHost, or is a header that the connection layer sets.Error::Fetchbefore admission, if anAuthorizationheader is besidebasic_auth.Error::Fetchbefore admission, if the fetcher has asignerand the request carriesbasic_author anAuthorizationheader.Error::Fetchbefore admission, if a credential can reach a cleartext destination, and neitherallow_cleartext_credentialsnorFetcherOptions::allow_cleartext_credentialsistrue.Error::Fetchbefore admission, if the route names a TLS destination and the fetcher holds no trust anchors.Error::Fetchif a transport failure ends the rounds: a failed connect, handshake, or proxyCONNECT, or an expired deadline.Error::Fetchif the fetch refuses a redirect hop, as the redirect rules state.Error::Fetchif hyper cannot build a request, for example from an invalid validator value.- The error of the
signer, unchanged, if it fails. AnError::Fetchif it returns a header that a request cannot carry. The fetch asks no other destination and repeats no round. Error::Fetchiffetch_timeoutexpires.Error::HttpStatusif a destination answers with a status other than 200 and 304, and other than 206 to a request with aRangeheader. This includes a redirect that the fetch does not follow: no usableLocation, or a redirect limit of zero. Withmax_error_body, the error carries the response, as the rules of the error responses state.Error::RedirectLimitif an attempt followsmax_redirectsredirects, and the next response names a URL to follow.Error::FetchTooLargeif theContent-Lengthof the response is more thanmax_size.Error::ContentEncodedif the response declares a coding, as the content coding rules state.
Sourcepub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r>
pub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r>
Sourcepub async fn upload(&self, request: UploadRequest<'_>) -> Result<Uploaded>
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
CONNECTtunnel - 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
Locationthat the upload can read - each redirect if
max_redirectsis 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
connect_timeoutbounds the open of a connection.fetch_timeoutbounds the upload from admission to the hand-over alone.- While a streamed body streams, the one bound is the stall window of
UploadWriter, which starts at the hand-over. - For a body given whole, a frame that the connection does not take for
progress_timeoutends the upload withError::UploadInterrupted. - The wait for the response head lasts
response_timeout. - The response body has the progress window of a fetch.
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::Fetchbefore admission, if a path holds a?or a#, if the query of aTarget::PathQueryholds a#, or if the fetcher has no mirror for a path target.Error::Fetchbefore admission, if a URL target is not a valid absolute URL, or holds a fragment or userinfo.Error::Unsupportedif the scheme of a URL target is neitherhttpnorhttps.Error::Fetchbefore admission, if a request header is invalid, isHost, or is a header that the connection layer sets.Error::Fetchbefore admission, if two credentials of the request meet:basic_auth,bearer_token, and anAuthorizationheader. A bearer token that is not token68 also fails.Error::Fetchbefore admission, if the fetcher has asignerand the request carries one of these credentials:basic_auth,bearer_token, or anAuthorizationheader.Error::Fetchbefore admission, if a credential can reach a cleartext destination, and neitherallow_cleartext_credentialsnorFetcherOptions::allow_cleartext_credentialsistrue.Error::Fetchbefore admission, if the route names a TLS destination and the fetcher holds no trust anchors.Error::Fetchbefore admission, if the method isDELETEand the body is not an emptyUploadBody::bytes.Error::Fetchif a transport failure ends the rounds before the hand-over: a failed connect, handshake, or proxyCONNECT, or an expired deadline.Error::Fetchif hyper cannot build the request.- The error of the
signer, unchanged, if it fails before the hand-over. AnError::Fetchif 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::Fetchif the writer of a streamed body is dropped before the hand-over.Error::Fetchiffetch_timeoutexpires before the hand-over.Error::UploadInterruptedif 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 aContent-Lengthovermax_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());