Watch
0
0
Fork
You've already forked hyperhive
0

add shared forge-client crate; hive-forge and hive-forge-notify use it

This commit is contained in:
atlas 2026-11-15 19:49:02 +01:00 • committed by mara
commit e59e41ec90

214
forge-client/src/lib.rs Normal file
View file

@ -0,0 +1,214 @@
//! Forgejo client construction, timeout policy and the drift-tolerant
//! notification thread, shared by `hive-forge` and `hive-forge-notify`.
//!
//! Construction takes a base URL and a [`TokenSource`]; 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};
/// Where a client's token comes from.
///
/// [`current`](TokenSource::current) is read each time a client is built. A
/// source whose token can change (re-read from a secret store after the
/// forge answers 401) rebuilds its client when `current()` returns a value
/// different from the one the client was built with; building is cheap and
/// pure, so a rebuild is a second call to [`async_client`].
pub trait TokenSource {
/// The token to send now.
fn current(&self) -> String;
}
/// A token that never changes.
#[derive(Clone)]
pub struct StaticToken(String);
impl StaticToken {
#[must_use]
pub fn new(token: impl Into<String>) -> Self {
Self(token.into())
}
}
impl TokenSource for StaticToken {
fn current(&self) -> String {
self.0.clone()
}
}
/// 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`'s current
/// value. 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: &impl TokenSource) -> Result<Forgejo, ForgejoError> {
Forgejo::new(Auth::Token(&token.current()), 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: &impl TokenSource,
) -> Result<forgejo_api::sync::Forgejo, ForgejoError> {
forgejo_api::sync::Forgejo::new(Auth::Token(&token.current()), 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: &impl TokenSource,
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.current()))
.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_sends_the_token_source_value_and_rejects_non_http() {
let ok = url::Url::parse("http://forge.example/").unwrap();
assert!(async_client(ok, &StaticToken::new("t")).is_ok());
let bad = url::Url::parse("ftp://forge.example/").unwrap();
assert!(async_client(bad, &StaticToken::new("t")).is_err());
}
#[cfg(feature = "sync")]
#[test]
fn raw_client_builds_and_rejects_an_unsendable_token() {
assert!(raw_blocking_client(&StaticToken::new("t"), &TimeoutPolicy::CLI).is_ok());
let err = raw_blocking_client(&StaticToken::new("a\nb"), &TimeoutPolicy::CLI).unwrap_err();
assert!(matches!(err, RawClientError::AuthHeader(_)));
}
}