Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/forge-client/src/lib.rs

182 lines
6.1 KiB
Rust

//! Forgejo client construction, timeout policy and the drift-tolerant
//! notification thread, shared by every hyperhive forge consumer.
//!
//! Construction takes a base URL and the token as a string; the bounds on how
//! long a call may take come from a [`TimeoutPolicy`] the caller names.
mod notification;
#[cfg(feature = "sync")]
use std::fmt;
use std::future::Future;
use std::time::Duration;
use forgejo_api::{Auth, Forgejo, ForgejoError};
pub use notification::{NotificationRepo, NotificationSubject, NotificationThread, parse_rfc3339};
/// How long a caller lets forge calls take. Each caller picks one policy and
/// keeps it; the `forgejo_api` clients carry no timeout of their own, so a
/// bound exists only where the caller applies it from here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeoutPolicy {
/// Bound on reaching the forge, applied to the raw client. `None`: unbounded.
pub connect: Option<Duration>,
/// Whole-request budget for a small JSON call.
pub json: Duration,
/// Whole-request budget for a call that downloads a file body.
pub download: Duration,
}
impl TimeoutPolicy {
/// The `hive-forge` CLI: 5 s to connect, 15 s per JSON call, 10 minutes
/// for a download. `reqwest::blocking` has no idle timeout, so the
/// download figure bounds the whole transfer.
pub const CLI: Self = Self {
connect: Some(Duration::from_secs(5)),
json: Duration::from_secs(15),
download: Duration::from_mins(10),
};
/// A policy bounding JSON calls only (the notifier: no connect bound, no
/// downloads).
#[must_use]
pub const fn json_only(json: Duration) -> Self {
Self {
connect: None,
json,
download: json,
}
}
/// Run `call`, giving up after [`json`](Self::json).
///
/// # Errors
///
/// `Elapsed` when the budget ran out first.
pub async fn bound_json<F: Future>(
&self,
call: F,
) -> Result<F::Output, tokio::time::error::Elapsed> {
tokio::time::timeout(self.json, call).await
}
}
/// The async typed client for the forge at `url`, sending `token`. No timeout
/// is set on it: bound each call with
/// [`TimeoutPolicy::bound_json`].
///
/// # Errors
///
/// `url` is not http(s), or the token is not ASCII.
pub fn async_client(url: url::Url, token: &str) -> Result<Forgejo, ForgejoError> {
Forgejo::new(Auth::Token(token), url)
}
/// The blocking typed client for the forge at `url`. No timeout is set on it.
///
/// # Errors
///
/// `url` is not http(s), or the token is not ASCII.
#[cfg(feature = "sync")]
pub fn sync_client(url: url::Url, token: &str) -> Result<forgejo_api::sync::Forgejo, ForgejoError> {
forgejo_api::sync::Forgejo::new(Auth::Token(token), url)
}
/// Why [`raw_blocking_client`] failed.
#[cfg(feature = "sync")]
#[derive(Debug)]
pub enum RawClientError {
/// The token cannot be sent as a header value.
AuthHeader(reqwest::header::InvalidHeaderValue),
/// `reqwest` refused to build the client.
Build(reqwest::Error),
}
#[cfg(feature = "sync")]
impl fmt::Display for RawClientError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AuthHeader(e) => write!(f, "auth header: {e}"),
Self::Build(e) => write!(f, "build reqwest client: {e}"),
}
}
}
#[cfg(feature = "sync")]
impl std::error::Error for RawClientError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::AuthHeader(e) => Some(e),
Self::Build(e) => Some(e),
}
}
}
/// A blocking `reqwest` client carrying the forge token and asking for JSON,
/// with `policy.connect` as its connect timeout. For the routes Forgejo
/// serves only through its web router, which `forgejo_api` cannot reach.
///
/// # Errors
///
/// [`RawClientError`] when the token is not a valid header value or the
/// client cannot be built.
#[cfg(feature = "sync")]
pub fn raw_blocking_client(
token: &str,
policy: &TimeoutPolicy,
) -> Result<reqwest::blocking::Client, RawClientError> {
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue};
let mut headers = HeaderMap::new();
let mut auth =
HeaderValue::from_str(&format!("token {token}")).map_err(RawClientError::AuthHeader)?;
auth.set_sensitive(true);
headers.insert(AUTHORIZATION, auth);
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
let mut builder = reqwest::blocking::Client::builder().default_headers(headers);
if let Some(connect) = policy.connect {
builder = builder.connect_timeout(connect);
}
builder.build().map_err(RawClientError::Build)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cli_policy_keeps_the_hive_forge_bounds() {
assert_eq!(TimeoutPolicy::CLI.connect, Some(Duration::from_secs(5)));
assert_eq!(TimeoutPolicy::CLI.json, Duration::from_secs(15));
assert_eq!(TimeoutPolicy::CLI.download, Duration::from_mins(10));
}
#[tokio::test(start_paused = true)]
async fn bound_json_gives_up_after_the_json_budget() {
let policy = TimeoutPolicy {
download: Duration::from_hours(1),
..TimeoutPolicy::json_only(Duration::from_secs(10))
};
let slow = policy.bound_json(tokio::time::sleep(Duration::from_secs(11)));
assert!(slow.await.is_err());
let quick = policy.bound_json(tokio::time::sleep(Duration::from_secs(9)));
assert!(quick.await.is_ok());
}
#[test]
fn async_client_rejects_a_non_http_url() {
let ok = url::Url::parse("http://forge.example/").unwrap();
assert!(async_client(ok, "t").is_ok());
let bad = url::Url::parse("ftp://forge.example/").unwrap();
assert!(async_client(bad, "t").is_err());
}
#[cfg(feature = "sync")]
#[test]
fn raw_client_builds_and_rejects_an_unsendable_token() {
assert!(raw_blocking_client("t", &TimeoutPolicy::CLI).is_ok());
let err = raw_blocking_client("a\nb", &TimeoutPolicy::CLI).unwrap_err();
assert!(matches!(err, RawClientError::AuthHeader(_)));
}
}