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
2 changed files with 502 additions and 214 deletions

View file

@ -9,8 +9,9 @@
use std::time::Duration;
use forge_client::{StaticToken, TimeoutPolicy};
use forgejo_api::structs::{NotifyGetListQuery, NotifyReadThreadQuery};
use forgejo_api::{Auth, Forgejo, ForgejoError};
use forgejo_api::{Forgejo, ForgejoError};
use hive_forge_notify::notify::{HTTP_TIMEOUT_SECS, UNREAD_FETCH_LIMIT};
use hive_forge_notify::source::Source;
use tracing::{debug, warn};
@ -22,6 +23,7 @@ pub struct ForgejoSource {
/// out over plain `reqwest`.
pub base_url: String,
pub token: String,
timeouts: TimeoutPolicy,
}
impl ForgejoSource {
@ -36,11 +38,12 @@ impl ForgejoSource {
return None;
}
};
match Forgejo::new(Auth::Token(token), parsed) {
match forge_client::async_client(parsed, &StaticToken::new(token)) {
Ok(forge) => Some(Self {
forge: Box::new(forge),
base_url: base_url.to_owned(),
token: token.to_owned(),
timeouts: TimeoutPolicy::json_only(Duration::from_secs(HTTP_TIMEOUT_SECS)),
}),
Err(e) => {
warn!("forge_notify: failed to build forge client: {e}");
@ -93,9 +96,7 @@ impl Source for ForgejoSource {
.notify_get_list(query)
.page_size(u32::try_from(UNREAD_FETCH_LIMIT).unwrap_or(u32::MAX))
.response_type::<String>();
let raw = match tokio::time::timeout(Duration::from_secs(HTTP_TIMEOUT_SECS), request.send())
.await
{
let raw = match self.timeouts.bound_json(request.send()).await {
Ok(Ok(raw)) => raw,
Ok(Err(ForgejoError::UnexpectedStatusCode(status))) => {
debug!("forge_notify: poll status {status}");
@ -135,7 +136,7 @@ impl Source for ForgejoSource {
.forge
.notify_read_thread(thread_id, NotifyReadThreadQuery { to_status: None })
.response_type::<String>();
match tokio::time::timeout(Duration::from_secs(HTTP_TIMEOUT_SECS), request.send()).await {
match self.timeouts.bound_json(request.send()).await {
Err(_) => {
warn!(%id, "forge_notify: mark-read request failed — notification will resurface");
}

View file

@ -31,10 +31,9 @@ use std::path::Path;
use std::time::Duration;
use backon::{ConstantBuilder, Retryable as _};
use forge_client::{NotificationThread, parse_rfc3339};
use forgejo_api::structs::NotifySubjectType;
use serde::{Deserialize, Deserializer};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use tracing::{debug, warn};
use crate::source::Source;
@ -1073,122 +1072,6 @@ async fn fetch_inline_review_tail<S: Source>(
render_inline_comments(pr_number, &groups)
}
/// Parse an RFC 3339 timestamp as Forgejo emits them
/// (`2026-06-13T11:18:42+02:00` or `...Z`, optionally with fractional
/// seconds). Returns `None` on any shape `time` doesn't recognise so
/// callers can fall back gracefully.
fn parse_rfc3339(s: &str) -> Option<OffsetDateTime> {
OffsetDateTime::parse(s, &Rfc3339).ok()
}
/// Minimal, drift-tolerant view of a Forgejo notification thread —
/// deliberately NOT `forgejo_api::structs::NotificationThread`. That crate
/// (0.11.0) lags the running `pkgs.forgejo` release, and one field
/// type/shape drift in the upstream struct fails the WHOLE parse, so every
/// notification is dropped, never dedup'd / marked-read, and redelivered
/// forever. This local struct carries only the fields `forge_notify` reads,
/// each optional + lenient, so unknown or reshaped upstream fields can't
/// break notification read-state again.
#[derive(Debug, Deserialize)]
struct NotificationThread {
/// Thread id as a **string**, whichever host it came from: Forgejo
/// sends a JSON number, GitHub sends a quoted string. It is only ever
/// used as an opaque key (dedupe map, todo key, mark-read path
/// segment), so normalising to `String` at the parse boundary is
/// cheaper than carrying the difference through every call site.
#[serde(default, deserialize_with = "de_opt_id")]
id: Option<String>,
#[serde(default, deserialize_with = "de_opt_rfc3339")]
updated_at: Option<OffsetDateTime>,
#[serde(default)]
subject: Option<NotificationSubject>,
#[serde(default)]
repository: Option<NotificationRepo>,
}
#[derive(Debug, Deserialize)]
struct NotificationSubject {
#[serde(default)]
title: Option<String>,
#[serde(rename = "type", default, deserialize_with = "de_opt_subject_type")]
r#type: Option<NotifySubjectType>,
#[serde(default, deserialize_with = "de_opt_url")]
html_url: Option<url::Url>,
#[serde(default, deserialize_with = "de_opt_url")]
url: Option<url::Url>,
#[serde(default, deserialize_with = "de_opt_url")]
latest_comment_url: Option<url::Url>,
#[serde(default, deserialize_with = "de_opt_url")]
latest_comment_html_url: Option<url::Url>,
}
#[derive(Debug, Deserialize)]
struct NotificationRepo {
#[serde(default)]
full_name: Option<String>,
}
/// Deserialize an optional Forgejo subject `type`, mapping any unknown or
/// missing value to `None` instead of failing the parse — so a new Forgejo
/// subject type can never break notification read-state.
fn de_opt_subject_type<'de, D>(d: D) -> Result<Option<NotifySubjectType>, D::Error>
where
D: Deserializer<'de>,
{
Ok(
Option::<String>::deserialize(d)?.and_then(|s| match s.as_str() {
// Forgejo says `Pull`; GitHub says `PullRequest` for the same
// thing. Both map to the same label, so a GitHub PR doesn't
// render as the `?` unknown-type fallback.
"Pull" | "PullRequest" => Some(NotifySubjectType::Pull),
"Issue" => Some(NotifySubjectType::Issue),
"Commit" => Some(NotifySubjectType::Commit),
"Repository" => Some(NotifySubjectType::Repository),
_ => None,
}),
)
}
/// Deserialize an optional notification thread id from either a JSON
/// number (Forgejo) or a JSON string (GitHub), normalising both to
/// `String`. Anything else — including a `null` or an unexpected shape —
/// degrades to `None` rather than failing the parse, keeping the "one bad
/// field can never break notification read-state" property the rest of
/// this struct is built around.
fn de_opt_id<'de, D>(d: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
Ok(match Option::<serde_json::Value>::deserialize(d)? {
Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s),
Some(serde_json::Value::Number(n)) => Some(n.to_string()),
_ => None,
})
}
/// Deserialize an optional URL, mapping a blank or unparseable value to
/// `None` (Forgejo marshals empty strings for absent URLs, which a plain
/// `Option<Url>` would reject).
fn de_opt_url<'de, D>(d: D) -> Result<Option<url::Url>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<String>::deserialize(d)?
.filter(|s| !s.is_empty())
.and_then(|s| url::Url::parse(&s).ok()))
}
/// Deserialize an optional RFC 3339 timestamp, mapping any unrecognised
/// shape to `None` via the module's tolerant [`parse_rfc3339`].
fn de_opt_rfc3339<'de, D>(d: D) -> Result<Option<OffsetDateTime>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<String>::deserialize(d)?
.as_deref()
.and_then(parse_rfc3339))
}
/// One notification from the poll page: the lenient thread plus two raw
/// fields the typed struct can't carry faithfully.
struct PolledNotification {