add shared forge-client crate; hive-forge and hive-forge-notify use it
This commit is contained in:
parent
687683a4f0
commit
e59e41ec90
3 changed files with 502 additions and 214 deletions
|
|
@ -19,6 +19,9 @@ clap-markdown = "0.1"
|
|||
# not about the workspace. See the pin note on `forgejo-api` in the root
|
||||
# `Cargo.toml`.
|
||||
forgejo-api = { workspace = true, features = ["sync"] }
|
||||
# Client construction, the CLI timeout policy and the drift-tolerant
|
||||
# notification thread, shared with hive-forge-notify.
|
||||
forge-client = { workspace = true, features = ["sync"] }
|
||||
# The review rule `pr assign-reviewer` shares with swarm-controller.
|
||||
hive-types.workspace = true
|
||||
url.workspace = true
|
||||
|
|
|
|||
|
|
@ -9,26 +9,20 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use forgejo_api::{Auth, ForgejoError};
|
||||
use forge_client::{StaticToken, TimeoutPolicy};
|
||||
use forgejo_api::ForgejoError;
|
||||
use reqwest::blocking::{Client as HttpClient, Response};
|
||||
use reqwest::header::{
|
||||
ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, HeaderMap, HeaderValue,
|
||||
};
|
||||
use reqwest::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Bound on reaching the forge.
|
||||
const HTTP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
/// Whole-request budget for a small JSON call (an `/api/v1` GET, or the
|
||||
/// run-view log streamer's snapshot POST).
|
||||
const JSON_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
/// Whole-request budget for a GET that downloads a file body — an
|
||||
/// attachment, an Actions artifact zip, or a persisted job log. Sized
|
||||
/// for a large-but-live transfer rather than a JSON call:
|
||||
/// `reqwest::blocking` has no separate read/idle timeout, so this bounds
|
||||
/// the whole download rather than cutting it off partway through like
|
||||
/// [`JSON_TIMEOUT`] would.
|
||||
pub(crate) const DOWNLOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(10);
|
||||
/// The CLI's timeout policy: connect bound, JSON-call budget (an `/api/v1`
|
||||
/// GET, or the run-view log streamer's snapshot POST) and download budget
|
||||
/// (an attachment, an Actions artifact zip, or a persisted job log; it bounds
|
||||
/// the whole transfer because `reqwest::blocking` has no idle timeout).
|
||||
const TIMEOUTS: TimeoutPolicy = TimeoutPolicy::CLI;
|
||||
const JSON_TIMEOUT: std::time::Duration = TIMEOUTS.json;
|
||||
pub(crate) const DOWNLOAD_TIMEOUT: std::time::Duration = TIMEOUTS.download;
|
||||
|
||||
/// Forgejo client pair: the typed `/api/v1` client plus a raw
|
||||
/// `reqwest` client for web-router-only routes.
|
||||
|
|
@ -94,20 +88,9 @@ 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 api = forgejo_api::sync::Forgejo::new(Auth::Token(&token), url)
|
||||
.context("build forgejo client")?;
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
let auth = format!("token {token}");
|
||||
let mut auth_val = HeaderValue::from_str(&auth).context("auth header")?;
|
||||
auth_val.set_sensitive(true);
|
||||
headers.insert(AUTHORIZATION, auth_val);
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
let web = HttpClient::builder()
|
||||
.default_headers(headers)
|
||||
.connect_timeout(HTTP_CONNECT_TIMEOUT)
|
||||
.build()
|
||||
.context("build reqwest client")?;
|
||||
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)?;
|
||||
|
||||
Ok(Self {
|
||||
api,
|
||||
|
|
@ -576,7 +559,8 @@ impl std::error::Error for WebStatusError {}
|
|||
/// `op` failed with `e`; a timeout names the bound that fired.
|
||||
fn http_context(op: &str, e: &reqwest::Error, budget: std::time::Duration) -> String {
|
||||
if e.is_connect() && e.is_timeout() {
|
||||
format!("{op}: connect timed out after {HTTP_CONNECT_TIMEOUT:?}")
|
||||
let connect = TIMEOUTS.connect.unwrap_or_default();
|
||||
format!("{op}: connect timed out after {connect:?}")
|
||||
} else if e.is_timeout() {
|
||||
format!("{op}: timed out after {budget:?}")
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
//! `forge cli: agents keep commenting without reading prev comments`.)
|
||||
|
||||
use anyhow::Result;
|
||||
use forge_client::NotificationThread;
|
||||
use forgejo_api::structs::NotifyReadThreadQuery;
|
||||
|
||||
use crate::client::{Client, index, split_repo};
|
||||
|
|
@ -33,38 +34,13 @@ const MAX_PAGES: u32 = 5;
|
|||
/// notification (nothing to read / already read). Repo-scoped so a bare
|
||||
/// number can't false-match another repo. Errors only on transport /
|
||||
/// non-2xx — callers degrade open on `Err`.
|
||||
/// Minimal, drift-tolerant view of a Forgejo notification thread — only
|
||||
/// the two fields the read-before-comment guard needs: `id` (to mark the
|
||||
/// thread read) and `subject.url` (to match the thread to an issue/PR
|
||||
/// number). Both `#[serde(default)]` so a schema change anywhere else in
|
||||
/// the notification object can't break this deserialize. This is the
|
||||
/// deliberate replacement for `forgejo-api`'s strict `NotificationThread`,
|
||||
/// whose schema drift vs the running (latest-line) Forgejo was breaking
|
||||
/// the whole notifications call — silently disabling the guard and
|
||||
/// wedging notification read-state (so wakes kept redelivering).
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Notification {
|
||||
#[serde(default)]
|
||||
id: Option<i64>,
|
||||
#[serde(default)]
|
||||
subject: Option<Subject>,
|
||||
}
|
||||
|
||||
/// The one notification-subject field the guard reads: the API `url`,
|
||||
/// which ends in the issue/PR number (see [`subject_matches`]).
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Subject {
|
||||
#[serde(default)]
|
||||
url: Option<String>,
|
||||
}
|
||||
|
||||
pub fn unread_thread_id(client: &Client, repo: &str, number: u64) -> Result<Option<u64>> {
|
||||
let (owner, name) = split_repo(repo)?;
|
||||
let limit = PAGE_SIZE.to_string();
|
||||
let path = format!("/repos/{owner}/{name}/notifications");
|
||||
for page in 1..=MAX_PAGES {
|
||||
let page_str = page.to_string();
|
||||
let threads: Vec<Notification> = client.get_api_json(
|
||||
let threads: Vec<NotificationThread> = client.get_api_json(
|
||||
&path,
|
||||
&[("all", "false"), ("page", &page_str), ("limit", &limit)],
|
||||
)?;
|
||||
|
|
@ -72,10 +48,10 @@ pub fn unread_thread_id(client: &Client, repo: &str, number: u64) -> Result<Opti
|
|||
let subject_url = n
|
||||
.subject
|
||||
.as_ref()
|
||||
.and_then(|s| s.url.as_deref())
|
||||
.unwrap_or("");
|
||||
.and_then(|s| s.url.as_ref())
|
||||
.map_or("", url::Url::as_str);
|
||||
if subject_matches(subject_url, number) {
|
||||
return Ok(n.id.and_then(|id| u64::try_from(id).ok()));
|
||||
return Ok(n.id.as_deref().and_then(|id| id.parse().ok()));
|
||||
}
|
||||
}
|
||||
// Last (short) page reached — stop.
|
||||
|
|
@ -123,36 +99,7 @@ pub fn subject_matches(subject_url: &str, number: u64) -> bool {
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Notification, subject_matches};
|
||||
|
||||
#[test]
|
||||
fn notification_deserializes_leniently_from_drifted_json() {
|
||||
// A payload carrying fields the guard doesn't model (which would
|
||||
// break `forgejo-api`'s strict struct) plus a missing subject —
|
||||
// must still yield `id` + `subject.url` and never fail to parse.
|
||||
let json = serde_json::json!([
|
||||
{
|
||||
"id": 42,
|
||||
"unread": true,
|
||||
"pinned": false,
|
||||
"subject": {
|
||||
"title": "whatever",
|
||||
"url": "https://forge/api/v1/repos/o/r/issues/7", // lint:allow: test fixture, not a real forge link
|
||||
"type": "SomeFutureSubjectTypeWeDoNotKnow"
|
||||
},
|
||||
"some_new_field": { "nested": 1 }
|
||||
},
|
||||
{ "id": 43 }
|
||||
]);
|
||||
let ns: Vec<Notification> = serde_json::from_value(json).expect("lenient deser");
|
||||
assert_eq!(ns[0].id, Some(42));
|
||||
assert_eq!(
|
||||
ns[0].subject.as_ref().and_then(|s| s.url.as_deref()),
|
||||
Some("https://forge/api/v1/repos/o/r/issues/7") // lint:allow: test fixture, not a real forge link
|
||||
);
|
||||
assert_eq!(ns[1].id, Some(43));
|
||||
assert!(ns[1].subject.is_none());
|
||||
}
|
||||
use super::subject_matches;
|
||||
|
||||
#[test]
|
||||
fn matches_issue_subject_url() {
|
||||
|
|
|
|||
Loading…
Reference in a new issue