Watch
0
0
Fork
You've already forked hyperhive
0

forge-client: take the token as a string, drop TokenSource and StaticToken

This commit is contained in:
atlas 2026-11-15 23:22:48 +01:00
commit 6d968c7fe6
14 changed files with 44 additions and 81 deletions

View file

@ -111,7 +111,7 @@ Wire types + socket plumbing:
spec. ⚠️ **This socket never leaves the container** — `hive-c0re` is not
in the path, unlike `hive-core-agent-sock`.
- **`forge-client/`** — the shared Forgejo client construction (`async_client`,
`sync_client`), `TimeoutPolicy`, `TokenSource`, and the one drift-tolerant
`sync_client`), `TimeoutPolicy`, and the one drift-tolerant
`NotificationThread`; used by `hive-forge`, `hive-forge-notify`,
`swarm-controller` and `swarm-ci-metrics`.
- **`hive-sock-client/`** — the shared JSON-line unix-socket client; retry

View file

@ -7,7 +7,8 @@ schema change that `forgejo-api` does not yet model is fixed here once.
## When to use it
- Building a `forgejo_api` client from a base URL and a token: `async_client`,
- Building a `forgejo_api` client from a base URL and a token string:
`async_client`,
and with the `sync` feature `sync_client`.
- Building the raw `reqwest` client for Forgejo's web-router-only routes (the
`sync` feature): `raw_blocking_client`.
@ -16,11 +17,10 @@ schema change that `forgejo-api` does not yet model is fixed here once.
- Parsing a notification thread from the forge: `NotificationThread`. Every
field is optional and lenient, so an unknown or reshaped field cannot fail
the page the way `forgejo_api::structs::NotificationThread` does.
- Supplying the token: `TokenSource`. `StaticToken` is a fixed string; a
caller whose token can change implements the trait and rebuilds its client
when `current()` returns a different value.
## Not here
Anything that decides what a notification means (delivery, read-state,
filtering): that stays in `hive-forge-notify` and `hive-forge`.
A token that changes (the controller re-reads it from the secret store after a 401) is the caller's to track: it calls `async_client` again with the new value.

View file

@ -1,7 +1,7 @@
//! Forgejo client construction, timeout policy and the drift-tolerant
//! notification thread, shared by every hyperhive forge consumer.
//!
//! Construction takes a base URL and a [`TokenSource`]; the bounds on how
//! 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;
@ -15,35 +15,6 @@ 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.
@ -91,15 +62,15 @@ impl TimeoutPolicy {
}
}
/// The async typed client for the forge at `url`, sending `token`'s current
/// value. No timeout is set on it: bound each call with
/// 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: &impl TokenSource) -> Result<Forgejo, ForgejoError> {
Forgejo::new(Auth::Token(&token.current()), url)
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.
@ -108,11 +79,8 @@ pub fn async_client(url: url::Url, token: &impl TokenSource) -> Result<Forgejo,
///
/// `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)
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.
@ -155,14 +123,14 @@ impl std::error::Error for RawClientError {
/// client cannot be built.
#[cfg(feature = "sync")]
pub fn raw_blocking_client(
token: &impl TokenSource,
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.current()))
.map_err(RawClientError::AuthHeader)?;
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"));
@ -197,18 +165,18 @@ mod tests {
}
#[test]
fn async_client_sends_the_token_source_value_and_rejects_non_http() {
fn async_client_rejects_a_non_http_url() {
let ok = url::Url::parse("http://forge.example/").unwrap();
assert!(async_client(ok, &StaticToken::new("t")).is_ok());
assert!(async_client(ok, "t").is_ok());
let bad = url::Url::parse("ftp://forge.example/").unwrap();
assert!(async_client(bad, &StaticToken::new("t")).is_err());
assert!(async_client(bad, "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!(raw_blocking_client("t", &TimeoutPolicy::CLI).is_ok());
let err = raw_blocking_client("a\nb", &TimeoutPolicy::CLI).unwrap_err();
assert!(matches!(err, RawClientError::AuthHeader(_)));
}
}

View file

@ -9,7 +9,7 @@
use std::time::Duration;
use forge_client::{StaticToken, TimeoutPolicy};
use forge_client::TimeoutPolicy;
use forgejo_api::structs::{NotifyGetListQuery, NotifyReadThreadQuery};
use forgejo_api::{Forgejo, ForgejoError};
use hive_forge_notify::notify::{HTTP_TIMEOUT_SECS, UNREAD_FETCH_LIMIT};
@ -38,7 +38,7 @@ impl ForgejoSource {
return None;
}
};
match forge_client::async_client(parsed, &StaticToken::new(token)) {
match forge_client::async_client(parsed, token) {
Ok(forge) => Some(Self {
forge: Box::new(forge),
base_url: base_url.to_owned(),

View file

@ -9,7 +9,7 @@
use std::path::PathBuf;
use anyhow::{Context, Result, anyhow, bail};
use forge_client::{StaticToken, TimeoutPolicy};
use forge_client::TimeoutPolicy;
use forgejo_api::ForgejoError;
use reqwest::blocking::{Client as HttpClient, Response};
use reqwest::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
@ -88,7 +88,6 @@ impl Client {
.or_else(|| std::env::var("HIVE_FORGE_REPO").ok());
let url = url::Url::parse(&base).with_context(|| format!("parse HIVE_FORGE_URL {base}"))?;
let token = StaticToken::new(token);
let api = forge_client::sync_client(url, &token).context("build forgejo client")?;
let web = forge_client::raw_blocking_client(&token, &TIMEOUTS)?;

View file

@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context as _, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::Forgejo;
use forgejo_api::structs::{ActionRun, ListActionRunsQuery, RepoSearchQuery};
use swarm_queue_client::{ClientSecret, QueueConfig};
@ -85,11 +85,8 @@ async fn main() -> Result<()> {
state_file: PathBuf::from(state_dir).join("cursor.json"),
};
let forge = async_client(
cfg.forge_url.clone(),
&StaticToken::new(forge_token().await?),
)
.context("building the forge client")?;
let forge = async_client(cfg.forge_url.clone(), &forge_token().await?)
.context("building the forge client")?;
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()

View file

@ -18,7 +18,7 @@ use std::collections::BTreeSet;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::structs::{AccessToken, CreateAccessTokenOption};
use forgejo_api::{ApiErrorKind, ForgejoError};
use reqwest::StatusCode;
@ -243,7 +243,7 @@ impl Client {
)
.await?;
let as_agent = async_client(self.url.clone(), &StaticToken::new(&credential.value))
let as_agent = async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?;
let me = as_agent
.user_get_current()

View file

@ -9,7 +9,7 @@
use std::sync::{Arc, Mutex};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::{ApiErrorKind, Forgejo, ForgejoError};
use futures_util::future::BoxFuture;
use reqwest::StatusCode;
@ -33,7 +33,7 @@ impl Api {
/// `url` is not http(s), or the token is not ASCII.
pub(crate) fn new(url: url::Url, token: StoredSecret) -> Result<Self, ForgejoError> {
let current = token.current();
let api = Arc::new(async_client(url.clone(), &StaticToken::new(&current))?);
let api = Arc::new(async_client(url.clone(), &current)?);
Ok(Self {
url,
token,
@ -46,7 +46,7 @@ impl Api {
let token = self.token.current();
let mut built = self.built.lock().expect("unpoisoned");
if built.0 != token {
let api = Arc::new(async_client(self.url.clone(), &StaticToken::new(&token))?);
let api = Arc::new(async_client(self.url.clone(), &token)?);
*built = (token.clone(), api);
}
Ok((token, Arc::clone(&built.1)))

View file

@ -15,7 +15,7 @@
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::structs::RepoSearchQuery;
use swarm_secret_client::builder::forge_token_path;
use swarm_secret_client::forge;
@ -93,7 +93,7 @@ impl Client {
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &StaticToken::new(&credential.value))
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await

View file

@ -17,7 +17,7 @@
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::structs::{
CreateTeamOption, CreateTeamOptionPermission, EditTeamOption, EditTeamOptionPermission,
RepoSearchQuery, Team, TeamPermission,
@ -124,7 +124,7 @@ impl Client {
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &StaticToken::new(&credential.value))
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await

View file

@ -20,7 +20,7 @@
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::Forgejo;
use forgejo_api::structs::{
ChangeFileOperation, ChangeFileOperationOperation, ChangeFilesOptions, CreatePullReviewOptions,
@ -123,7 +123,7 @@ impl Client {
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &StaticToken::new(&credential.value))
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await
@ -222,7 +222,7 @@ impl Client {
else {
bail!("nothing at {path}: the classifier's forge token is not minted yet");
};
async_client(self.url.clone(), &StaticToken::new(&credential.value))
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the classifier's token")
}
@ -463,7 +463,7 @@ mod tests {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let forge = async_client(url, &StaticToken::new("stub-token")).unwrap();
let forge = async_client(url, "stub-token").unwrap();
let commit = BranchCommit {
base: "main".to_owned(),
branch: "review-classifier/alice-0a1b2c3d".to_owned(),

View file

@ -19,7 +19,7 @@
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::structs::{
AccessToken, CreateTeamOption, CreateTeamOptionPermission, EditTeamOption,
EditTeamOptionPermission, RepoSearchQuery, Team, TeamPermission,
@ -175,7 +175,7 @@ impl Client {
)
.await?;
async_client(self.url.clone(), &StaticToken::new(&credential.value))
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await

View file

@ -21,7 +21,7 @@ use std::time::Duration;
use anyhow::{Context, Result};
use base64::Engine as _;
use forge_client::{StaticToken, async_client};
use forge_client::async_client;
use forgejo_api::structs::{CreateAccessTokenOption, UpdateUserAvatarOption};
use sha2::{Digest as _, Sha256};
@ -177,7 +177,7 @@ impl Client {
.sha1
.filter(|v| !v.is_empty())
.with_context(|| format!("the forge created {login}'s token but returned no value"))?;
let uploaded = async_client(self.url.clone(), &StaticToken::new(&token))
let uploaded = async_client(self.url.clone(), &token)
.context("building a forge client with the avatar token")?
.user_update_avatar(UpdateUserAvatarOption {
image: Some(base64::engine::general_purpose::STANDARD.encode(image)),

View file

@ -2542,8 +2542,7 @@ mod tests {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
drop(listener);
let forge =
forge_client::async_client(url, &forge_client::StaticToken::new("stub-token")).unwrap();
let forge = forge_client::async_client(url, "stub-token").unwrap();
forge.user_get_current().await.expect_err("nothing listens")
}