//! The Libby HTTP client. //! //! [`Client`] owns the identity, the pacing rules and the card-suspension //! state; it is cheap to clone (an `Arc` inside) and every clone shares them. //! //! # Politeness //! //! * Account (sentry) requests go through a single gate: one in flight, and //! at least [`ClientConfig::account_gap`] plus up to //! [`ClientConfig::account_jitter`] between one finishing and the next //! starting. Retries and token refreshes queue at the same gate. //! * Catalog, finder and image requests share a semaphore of //! [`ClientConfig::catalog_concurrency`] permits. //! * The client never polls. Pairing screens poll [`Client::sync`] //! themselves, no more often than every 2 s. //! //! # Retries //! //! 429, 500, 502, 503 and 504 answers and transport failures are retried up //! to [`ClientConfig::max_retries`] times with capped exponential backoff, or //! after `Retry-After` when the server sends one (a `Retry-After` longer than //! [`ClientConfig::max_retry_after`] is returned as //! [`Error::RateLimited`] instead of waited out). //! //! Actions that change the account and are not idempotent (borrow, renew, //! return, place hold, cancel hold, redeeming a setup code) are retried //! **only** when the request provably never reached the server: a 429 //! answer or a failure to connect. A timeout or a 5xx after sending could //! mean the action happened, and blindly repeating a borrow could borrow //! twice or burn a checkout; the caller should re-sync and decide. //! //! # Identity //! //! The identity token is a bearer credential. It is held in a //! [`SecretString`], never logged, and redacted from every `Debug` output. //! The client refreshes it on its own (on a 401/403 from sentry), so the //! caller must persist changes: [`Client::subscribe_identity`] yields a //! receiver that observes every change, including those made by //! [`Client::chip`] and [`Client::redeem_code`]. mod actions; mod auth; mod catalog; mod fulfil; mod gate; mod http; mod reader; mod tags; use std::collections::HashSet; use std::fmt; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use secrecy::{ExposeSecret, SecretString}; use tokio::sync::{Semaphore, watch}; use url::Url; pub use self::actions::{BorrowOptions, valid_hold_suspension}; pub use self::fulfil::Fulfillment; use self::gate::AccountGate; pub use self::reader::ReaderPassport; use crate::error::{Error, Result}; use crate::ids::CardId; /// Where the services live and how politely to talk to them. #[derive(Debug, Clone)] pub struct ClientConfig { /// The account API. Default `https://sentry.libbyapp.com/`. pub sentry_base: Url, /// The tag service. Default `https://vandal.libbyapp.com/`. pub vandal_base: Url, /// The catalog API. Default `https://thunder.api.overdrive.com/v2/`. pub thunder_base: Url, /// The library finder. Default `https://locate.libbyapp.com/`. pub locate_base: Url, /// Sent on every request. The default names libbui honestly. pub user_agent: String, /// Minimum pause between account requests. Default 750 ms. pub account_gap: Duration, /// Random extra pause on top of `account_gap`, `0..=account_jitter`. /// Default 250 ms. pub account_jitter: Duration, /// Concurrent catalog/finder/image requests. Default 4. pub catalog_concurrency: usize, /// Whole-request timeout. Default 30 s. pub timeout: Duration, /// Retries after the first attempt. Default 2. pub max_retries: u32, /// First backoff delay; doubles per retry. Default 500 ms. pub retry_base: Duration, /// Longest backoff delay. Default 8 s. pub retry_cap: Duration, /// Longest `Retry-After` the client will wait out itself. Default 60 s. pub max_retry_after: Duration, /// Intermediate hosts of the open-format fulfilment redirect chain. The /// client follows redirects only through these (without the bearer /// token) and returns the first location outside them as the download /// URL. Default `https://fulfill.contentreserve.com/`. pub fulfil_redirectors: Vec, } impl Default for ClientConfig { fn default() -> Self { let url = |raw: &str| Url::parse(raw).expect("default service URLs are valid"); Self { sentry_base: url("https://sentry.libbyapp.com/"), vandal_base: url("https://vandal.libbyapp.com/"), thunder_base: url("https://thunder.api.overdrive.com/v2/"), locate_base: url("https://locate.libbyapp.com/"), user_agent: concat!("libbui/", env!("CARGO_PKG_VERSION")).to_owned(), account_gap: Duration::from_millis(750), account_jitter: Duration::from_millis(250), catalog_concurrency: 4, timeout: Duration::from_secs(30), max_retries: 2, retry_base: Duration::from_millis(500), retry_cap: Duration::from_secs(8), max_retry_after: Duration::from_secs(60), fulfil_redirectors: vec![url("https://fulfill.contentreserve.com/")], } } } /// A device identity: the bearer token and the id of the chip it belongs to. /// /// `Debug` never shows the token. #[derive(Clone)] pub struct Identity { token: SecretString, chip: String, } impl Identity { /// Wraps a stored identity. pub fn new(token: impl Into, chip: impl Into) -> Self { Self { token: token.into(), chip: chip.into(), } } /// The bearer token. Expose it only to persist it. #[must_use] pub fn token(&self) -> &SecretString { &self.token } /// The chip (device) id. A refresh that returns a different one means /// the device was unlinked. #[must_use] pub fn chip(&self) -> &str { &self.chip } fn same_token(&self, other: &SecretString) -> bool { self.token.expose_secret() == other.expose_secret() } } impl fmt::Debug for Identity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Identity") .field("token", &"[REDACTED]") .field("chip", &self.chip) .finish() } } /// The Libby client. Clone it freely; clones share identity, pacing and /// suspension state. #[derive(Clone)] pub struct Client { inner: Arc, } struct Inner { config: ClientConfig, http: reqwest::Client, gate: AccountGate, catalog: Semaphore, identity: watch::Sender>, suspended: Mutex>, /// Single-flights token refreshes so concurrent 401s refresh once. refresh: tokio::sync::Mutex<()>, } impl fmt::Debug for Client { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Client") .field("config", &self.inner.config) .field("identity", &*self.inner.identity.borrow()) .field("suspended", &self.suspended_cards()) .finish_non_exhaustive() } } impl Client { /// Builds a client with no identity. /// /// # Errors /// /// [`Error::InvalidInput`] when a base URL is not an http(s) URL, a limit /// is zero, or the HTTP stack cannot be initialised. pub fn new(config: ClientConfig) -> Result { for (name, base) in [ ("sentry_base", &config.sentry_base), ("vandal_base", &config.vandal_base), ("thunder_base", &config.thunder_base), ("locate_base", &config.locate_base), ] .into_iter() .chain( config .fulfil_redirectors .iter() .map(|url| ("fulfil_redirectors", url)), ) { if !matches!(base.scheme(), "http" | "https") || base.cannot_be_a_base() { return Err(Error::InvalidInput(format!( "{name} must be an http(s) URL, got {base}" ))); } } if config.catalog_concurrency == 0 { return Err(Error::InvalidInput( "catalog_concurrency must be at least 1".into(), )); } let http = reqwest::Client::builder() // Redirects are followed by hand so the bearer token can never // leak to another host. .redirect(reqwest::redirect::Policy::none()) .user_agent(config.user_agent.clone()) .timeout(config.timeout) .connect_timeout(config.timeout.min(Duration::from_secs(10))) .build() .map_err(|e| Error::InvalidInput(format!("cannot build the HTTP client: {e}")))?; let (identity, _) = watch::channel(None); Ok(Self { inner: Arc::new(Inner { gate: AccountGate::new(config.account_gap, config.account_jitter), catalog: Semaphore::new(config.catalog_concurrency), http, identity, suspended: Mutex::new(HashSet::new()), refresh: tokio::sync::Mutex::new(()), config, }), }) } /// The configuration the client was built with. #[must_use] pub fn config(&self) -> &ClientConfig { &self.inner.config } /// The current identity, if any. #[must_use] pub fn identity(&self) -> Option { self.inner.identity.borrow().clone() } /// Replaces the identity, e.g. with one loaded from storage or pasted by /// the user. Subscribers observe the change. pub fn set_identity(&self, identity: Option) { self.inner.identity.send_replace(identity); } /// Observes identity changes. Every refresh, new chip and pairing is /// published here; persist each value the receiver sees. #[must_use] pub fn subscribe_identity(&self) -> watch::Receiver> { self.inner.identity.subscribe() } /// Whether the client has stopped all traffic for this card. #[must_use] pub fn is_suspended(&self, card: &CardId) -> bool { self.suspended().contains(card) } /// Cards the library has suspended, as seen by this client. #[must_use] pub fn suspended_cards(&self) -> Vec { let mut cards: Vec<_> = self.suspended().iter().cloned().collect(); cards.sort(); cards } /// Stops all traffic for a card, e.g. to restore a suspension recorded in /// a previous session. There is deliberately no way to undo this on a /// running client. pub fn mark_suspended(&self, card: CardId) { if self.suspended().insert(card.clone()) { tracing::warn!(%card, "library card suspended; refusing further requests for it"); } } fn suspended(&self) -> std::sync::MutexGuard<'_, HashSet> { // The set is only ever inserted into, so a panic mid-insert cannot // leave it inconsistent. self.inner .suspended .lock() .unwrap_or_else(PoisonError::into_inner) } fn ensure_not_suspended(&self, card: &CardId) -> Result<()> { if self.is_suspended(card) { Err(Error::CardSuspended { card: card.clone() }) } else { Ok(()) } } fn current_token(&self) -> Option { self.inner .identity .borrow() .as_ref() .map(|identity| identity.token.clone()) } fn publish_identity(&self, identity: Identity) { self.inner.identity.send_replace(Some(identity)); } } /// `base` with `segments` appended, each percent-encoded. fn endpoint(base: &Url, segments: &[&str]) -> Url { let mut url = base.clone(); url.path_segments_mut() .expect("base URLs are checked to be http(s) in Client::new") .pop_if_empty() .extend(segments); url } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn debug_never_shows_the_token() { let identity = Identity::new("super-secret-token", "chip-1"); let client = Client::new(ClientConfig::default()).unwrap(); client.set_identity(Some(identity.clone())); for rendered in [format!("{identity:?}"), format!("{client:?}")] { assert!(!rendered.contains("super-secret-token"), "{rendered}"); assert!(rendered.contains("chip-1"), "{rendered}"); } } #[test] fn endpoint_appends_encoded_segments() { let base = Url::parse("https://thunder.example/v2/").unwrap(); assert_eq!( endpoint(&base, &["libraries", "a b", "media"]).as_str(), "https://thunder.example/v2/libraries/a%20b/media" ); let bare = Url::parse("https://sentry.example").unwrap(); assert_eq!( endpoint(&bare, &["chip"]).as_str(), "https://sentry.example/chip" ); } #[test] fn rejects_unusable_config() { let config = ClientConfig { sentry_base: Url::parse("mailto:x@example.com").unwrap(), ..ClientConfig::default() }; assert!(matches!(Client::new(config), Err(Error::InvalidInput(_)))); let config = ClientConfig { catalog_concurrency: 0, ..ClientConfig::default() }; assert!(matches!(Client::new(config), Err(Error::InvalidInput(_)))); } #[test] fn suspension_is_sticky() { let client = Client::new(ClientConfig::default()).unwrap(); let card = CardId::new("7"); assert!(client.ensure_not_suspended(&card).is_ok()); client.mark_suspended(card.clone()); assert!(client.clone().is_suspended(&card)); assert!(matches!( client.ensure_not_suspended(&card), Err(Error::CardSuspended { .. }) )); assert_eq!(client.suspended_cards(), [card]); } }