legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
Documentation
//! How a [`Fetcher`](super::Fetcher) opens a connection, and what each request did with one.
//!
//! A connection is opened only to the addresses the checked resolver returned for the URL in hand:
//! each in the order the resolver gave them, until one connects, within the connect timeout as a
//! whole. Every connection the client opens is counted, and each request notes on its own thread
//! whether it opened a connection, wrote to one, and read a byte of the response, which is what the
//! fetcher's retry rule and the heartbeat's counters are made from.

use std::cell::Cell;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use ureq::Timeout;
use ureq::unversioned::transport::time::{Duration as Budget, Instant as Moment};
use ureq::unversioned::transport::{
    Buffers, ConnectionDetails, Connector, NextTimeout, RustlsConnector, TcpConnector, Transport,
};

/// The least time one address is given, as `ureq`'s own connector gives it: a socket can't be
/// given no time at all.
const MIN_PER_ADDRESS: std::time::Duration = std::time::Duration::from_millis(10);

/// Counts of the client's connections, for the heartbeat.
#[derive(Debug, Default)]
pub(crate) struct ConnectionCounters {
    /// Connections opened, TLS included when the URL is `https`.
    pub(crate) opened: AtomicU64,
    /// Requests written to a connection an earlier request had opened.
    pub(crate) reused: AtomicU64,
    /// Fetches tried again after a failure at the connect level.
    pub(crate) retries: AtomicU64,
}

impl ConnectionCounters {
    pub(crate) fn load(&self) -> (u64, u64, u64) {
        (
            self.opened.load(Ordering::Relaxed),
            self.reused.load(Ordering::Relaxed),
            self.retries.load(Ordering::Relaxed),
        )
    }
}

/// What one request did with its connection, noted on the thread that made it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Trace {
    /// The client looked for a new connection: no idle one of the pool served the request.
    pub(crate) connecting: bool,
    /// The request was written, or writing it began, to a connection.
    pub(crate) sent: bool,
    /// A byte of the response arrived.
    pub(crate) received: bool,
}

thread_local! {
    static TRACE: Cell<Trace> = const {
        Cell::new(Trace {
            connecting: false,
            sent: false,
            received: false,
        })
    };
}

fn note(change: impl FnOnce(&mut Trace)) {
    TRACE.with(|cell| {
        let mut trace = cell.get();
        change(&mut trace);
        cell.set(trace);
    });
}

/// Run `request`, one blocking request of the client on this thread, and return its result with
/// what it did with its connection. A body read afterwards isn't part of it.
pub(crate) fn traced<T>(request: impl FnOnce() -> T) -> (T, Trace) {
    TRACE.with(|cell| cell.set(Trace::default()));
    let result = request();
    (result, TRACE.with(Cell::get))
}

/// Every address of one resolution failed to connect.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConnectFailure {
    /// How many addresses the resolution held: all of them were tried, unless the connect
    /// timeout ran out first.
    pub(crate) addresses: usize,
    /// Why each address tried failed, in order: [`io::ErrorKind::TimedOut`] for one that ran out
    /// of time.
    pub(crate) failed: Vec<io::ErrorKind>,
}

impl fmt::Display for ConnectFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "no address of {} connected", self.addresses)
    }
}

impl std::error::Error for ConnectFailure {}

/// The connector chain a fetcher's client opens connections with: [`Addresses`], then TLS for an
/// `https` URL, then [`Opened`], which counts each connection made.
pub(crate) fn connector(counters: Arc<ConnectionCounters>) -> impl Connector {
    Addresses.chain(RustlsConnector::default()).chain(Opened(counters))
}

/// Connects to the addresses of [`ConnectionDetails::addrs`], which the checked resolver returned
/// and the policy allowed, one at a time in their order, and never to another: it resolves
/// nothing itself.
///
/// Each address is given an equal share of what is left of the connect timeout, so one that
/// fails at once, such as an IPv6 address on a host with no IPv6 route, leaves its time to the
/// next. `ureq`'s own connector also tries each address, but gives each a share of the whole
/// timeout fixed in advance, halving from the first, and reports only the last address's error.
/// Every connect error moves on to the next address here; when none connects, the error is a
/// [`ConnectFailure`] listing them all.
#[derive(Debug)]
struct Addresses;

impl Connector<()> for Addresses {
    type Out = Box<dyn Transport>;

    fn connect(&self, details: &ConnectionDetails, _: Option<()>) -> Result<Option<Self::Out>, ureq::Error> {
        note(|trace| trace.connecting = true);
        let count = details.addrs.len();
        let mut failed = Vec::with_capacity(count);
        for (index, address) in details.addrs.iter().enumerate() {
            let share = match details.timeout.after {
                Budget::Exact(total) => {
                    let elapsed = since(details.now, (details.current_time)());
                    let left = total.saturating_sub(elapsed);
                    if left.is_zero() {
                        failed.push(io::ErrorKind::TimedOut);
                        break;
                    }
                    let even = left / u32::try_from(count - index).unwrap_or(u32::MAX);
                    Budget::Exact(even.max(MIN_PER_ADDRESS.min(left)))
                }
                Budget::NotHappening => Budget::NotHappening,
            };
            let mut one = details.resolver.empty();
            one.push(*address);
            let attempt = ConnectionDetails {
                uri: details.uri,
                addrs: one,
                config: details.config,
                request_level: details.request_level,
                resolver: details.resolver,
                now: (details.current_time)(),
                timeout: NextTimeout {
                    after: share,
                    reason: Timeout::Connect,
                    ..details.timeout
                },
                current_time: Arc::clone(&details.current_time),
                run_connector: Arc::clone(&details.run_connector),
                register_shutdown: Arc::clone(&details.register_shutdown),
            };
            match Connector::<()>::connect(&TcpConnector::default(), &attempt, None) {
                Ok(Some(transport)) => return Ok(Some(transport.boxed())),
                Ok(None) => return Err(ureq::Error::ConnectionFailed),
                Err(ureq::Error::Io(error)) => failed.push(error.kind()),
                Err(ureq::Error::Timeout(_)) => failed.push(io::ErrorKind::TimedOut),
                Err(error) => return Err(error),
            }
        }
        Err(ureq::Error::Other(Box::new(ConnectFailure {
            addresses: count,
            failed,
        })))
    }
}

/// The time from `earlier` to `later`, zero unless both are exact.
fn since(earlier: Moment, later: Moment) -> std::time::Duration {
    match (earlier, later) {
        (Moment::Exact(earlier), Moment::Exact(later)) => later.saturating_duration_since(earlier),
        _ => std::time::Duration::ZERO,
    }
}

/// The end of the chain: counts the connection just made, and wraps it in [`Tracked`].
#[derive(Debug)]
struct Opened(Arc<ConnectionCounters>);

impl<In: Transport> Connector<In> for Opened {
    type Out = Tracked;

    fn connect(&self, _: &ConnectionDetails, chained: Option<In>) -> Result<Option<Self::Out>, ureq::Error> {
        Ok(chained.map(|transport| {
            self.0.opened.fetch_add(1, Ordering::Relaxed);
            Tracked::new(transport.boxed())
        }))
    }
}

/// A connection that notes, on the thread using it, when a request is written to it and when a
/// byte of a response arrives. It carries nothing from one request to the next.
///
/// It also reads the heads of the responses it carries, so that a connection whose last response
/// was a redirect is never reused: `ureq` hands a redirect with no body back to its pool before
/// the fetcher sees the response (`ureq` 3.5.2 `run.rs`, the `Redirect` arm of `call_run`), and
/// asks the transport whether it's open before keeping it, which this one denies. An
/// informational `1xx` head, such as `103 Early Hints`, is followed by another, as `ureq` follows
/// it; only the final response's status counts, and until it has been read whole the connection
/// is never offered for reuse.
#[derive(Debug)]
struct Tracked {
    inner: Box<dyn Transport>,
    head: Head,
}

/// The bytes of a status line kept to read its code: `HTTP/1.1 302` is 12.
const STATUS_LINE: usize = 12;

/// What a [`Tracked`] connection has read of the response to the request written last.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Head {
    /// No request written yet.
    Idle,
    /// Reading a response's head.
    Reading {
        /// The start of its first line.
        first: [u8; STATUS_LINE],
        /// The bytes of the current line so far, carriage returns aside.
        line: usize,
        /// The lines ended so far.
        lines: usize,
    },
    /// The final response's head has been read: its status code, or 0 when its first line isn't
    /// a status line.
    Final(u16),
}

impl Head {
    const READING: Self = Self::Reading {
        first: [0; STATUS_LINE],
        line: 0,
        lines: 0,
    };

    /// Read `bytes`, the next bytes of the responses, up to the end of the final head.
    fn read(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            let Self::Reading { first, line, lines } = self else {
                return;
            };
            match byte {
                b'\r' => {}
                b'\n' if *line == 0 && *lines > 0 => {
                    // An empty line ends a head: an informational one is followed by another...
                    let code = status(first);
                    *self = if (100..200).contains(&code) {
                        Self::READING
                    } else {
                        Self::Final(code)
                    };
                }
                b'\n' => {
                    *lines += 1;
                    *line = 0;
                }
                byte => {
                    if *lines == 0 && *line < STATUS_LINE {
                        first[*line] = byte;
                    }
                    *line = line.saturating_add(1);
                }
            }
        }
    }
}

/// The status code of a status line's start, such as `HTTP/1.1 302`, or 0.
fn status(first: &[u8; STATUS_LINE]) -> u16 {
    if !first.starts_with(b"HTTP/") || first[8] != b' ' {
        return 0;
    }
    std::str::from_utf8(&first[9..])
        .ok()
        .and_then(|code| code.parse().ok())
        .unwrap_or(0)
}

impl Tracked {
    const fn new(inner: Box<dyn Transport>) -> Self {
        Self {
            inner,
            head: Head::Idle,
        }
    }

    /// Note a response byte when the input buffer grew past `before`, and read the bytes that
    /// arrived into the response's head.
    fn note_input(&mut self, before: usize) {
        let input = self.inner.buffers().input();
        let Some(arrived) = input.get(before..).filter(|arrived| !arrived.is_empty()) else {
            return;
        };
        note(|trace| trace.received = true);
        self.head.read(arrived);
    }

    /// Whether the connection may be reused: its last response's final head was read whole, and
    /// isn't a redirect's.
    const fn reusable(&self) -> bool {
        matches!(self.head, Head::Final(code) if !matches!(code, 0 | 301 | 302 | 303 | 307 | 308))
    }
}

impl Transport for Tracked {
    fn buffers(&mut self) -> &mut dyn Buffers {
        self.inner.buffers()
    }

    fn transmit_output(&mut self, amount: usize, timeout: NextTimeout) -> Result<(), ureq::Error> {
        note(|trace| trace.sent = true);
        self.head = Head::READING;
        self.inner.transmit_output(amount, timeout)
    }

    fn maybe_await_input(&mut self, timeout: NextTimeout) -> Result<bool, ureq::Error> {
        let before = self.inner.buffers().input().len();
        let result = self.inner.maybe_await_input(timeout);
        self.note_input(before);
        result
    }

    fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, ureq::Error> {
        let before = self.inner.buffers().input().len();
        let result = self.inner.await_input(timeout);
        self.note_input(before);
        result
    }

    fn is_open(&mut self) -> bool {
        self.reusable() && self.inner.is_open()
    }

    fn is_tls(&self) -> bool {
        self.inner.is_tls()
    }
}