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

View file

@ -0,0 +1,179 @@
//! The drift-tolerant notification thread.
//!
//! Deliberately NOT `forgejo_api::structs::NotificationThread`: that struct
//! lags the running Forgejo, and one reshaped field fails the whole parse, so
//! every notification on the page is dropped. Every field here is optional
//! and degrades to `None` on an unknown or reshaped value, so a schema change
//! cannot break a notification call. Fields are the union of what
//! `hive-forge` and `hive-forge-notify` read.
use forgejo_api::structs::NotifySubjectType;
use serde::{Deserialize, Deserializer};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
/// One notification thread.
#[derive(Debug, Deserialize)]
pub struct NotificationThread {
/// Thread id as a string, whichever host sent it: Forgejo sends a JSON
/// number, GitHub a quoted string. Only ever an opaque key.
#[serde(default, deserialize_with = "de_opt_id")]
pub id: Option<String>,
#[serde(default, deserialize_with = "de_opt_rfc3339")]
pub updated_at: Option<OffsetDateTime>,
#[serde(default)]
pub subject: Option<NotificationSubject>,
#[serde(default)]
pub repository: Option<NotificationRepo>,
}
#[derive(Debug, Deserialize)]
pub struct NotificationSubject {
#[serde(default)]
pub title: Option<String>,
/// `Pull` and GitHub's `PullRequest` both map to
/// [`NotifySubjectType::Pull`]; an unknown type is `None`.
#[serde(rename = "type", default, deserialize_with = "de_opt_subject_type")]
pub r#type: Option<NotifySubjectType>,
#[serde(default, deserialize_with = "de_opt_url")]
pub html_url: Option<url::Url>,
/// The API URL; ends in the issue/PR number.
#[serde(default, deserialize_with = "de_opt_url")]
pub url: Option<url::Url>,
#[serde(default, deserialize_with = "de_opt_url")]
pub latest_comment_url: Option<url::Url>,
#[serde(default, deserialize_with = "de_opt_url")]
pub latest_comment_html_url: Option<url::Url>,
}
#[derive(Debug, Deserialize)]
pub struct NotificationRepo {
#[serde(default)]
pub full_name: Option<String>,
}
/// Parse an RFC 3339 timestamp as Forgejo emits them (`+02:00` or `Z`,
/// optionally with fractional seconds). `None` on any shape `time` does not
/// recognise.
#[must_use]
pub fn parse_rfc3339(s: &str) -> Option<OffsetDateTime> {
OffsetDateTime::parse(s, &Rfc3339).ok()
}
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() {
"Pull" | "PullRequest" => Some(NotifySubjectType::Pull),
"Issue" => Some(NotifySubjectType::Issue),
"Commit" => Some(NotifySubjectType::Commit),
"Repository" => Some(NotifySubjectType::Repository),
_ => None,
}),
)
}
/// A JSON number or a non-empty JSON string, as a `String`; anything else is
/// `None`.
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,
})
}
/// A blank or unparseable URL is `None` (Forgejo marshals empty strings for
/// absent URLs).
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()))
}
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))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn full_payload_parses_every_field() {
let t: NotificationThread = serde_json::from_value(json!({
"id": 42,
"updated_at": "2026-06-13T11:18:42+02:00",
"subject": {
"title": "t",
"type": "Pull",
"html_url": "http://f/o/r/pulls/7",
"url": "http://f/api/v1/repos/o/r/pulls/7",
"latest_comment_url": "http://f/api/v1/repos/o/r/issues/comments/1",
"latest_comment_html_url": "http://f/o/r/pulls/7/files",
},
"repository": { "full_name": "o/r" },
}))
.unwrap();
assert_eq!(t.id.as_deref(), Some("42"));
assert!(t.updated_at.is_some());
let s = t.subject.unwrap();
assert_eq!(s.r#type, Some(NotifySubjectType::Pull));
assert_eq!(s.url.unwrap().path(), "/api/v1/repos/o/r/pulls/7");
assert!(s.latest_comment_html_url.is_some());
assert_eq!(t.repository.unwrap().full_name.as_deref(), Some("o/r"));
}
#[test]
fn drifted_payload_still_parses_with_the_fields_it_can() {
// Reshaped values the struct tolerates: blank or malformed URLs, nulls, a new
// subject type, unparseable timestamp, extra keys, GitHub-style string id.
let t: NotificationThread = serde_json::from_value(json!({
"id": "abc",
"updated_at": "yesterday",
"unread": "maybe",
"subject": {
"title": null,
"type": "Discussion",
"state": "merged",
"url": "",
"html_url": "not a url",
"latest_comment_url": null,
},
"repository": { "full_name": null, "new_field": {} },
"new_top_level": [1, 2],
}))
.unwrap();
assert_eq!(t.id.as_deref(), Some("abc"));
assert!(t.updated_at.is_none());
let s = t.subject.unwrap();
assert!(s.r#type.is_none() && s.url.is_none() && s.html_url.is_none());
}
#[test]
fn empty_object_parses() {
let t: NotificationThread = serde_json::from_value(json!({})).unwrap();
assert!(t.id.is_none() && t.subject.is_none() && t.repository.is_none());
}
#[test]
fn github_pull_request_type_maps_to_pull() {
let s: NotificationSubject =
serde_json::from_value(json!({ "type": "PullRequest" })).unwrap();
assert_eq!(s.r#type, Some(NotifySubjectType::Pull));
}
}