From e4244f02d861a5c20ea06e134ba3f3947a3fca15 Mon Sep 17 00:00:00 2001 From: kosmos Date: Sat, 14 Nov 2026 13:25:40 +0000 Subject: [PATCH] fix(forge): a gitea comment names its thread without issue_url MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `comment_event` read the thread number from `issue_url` alone and failed the whole poll when it could not. The instance behind git.vhaudiquet.fr sends `issue_url: ""` on every row of the repo-wide `/issues/comments` feed, so the first comment row failed the pass with malformed forge response: comment issue_url without a thread number: and kept failing on every poll since the watch was created — 5296 consecutive failures, no event ever reported, no comment, no pull request, nothing. The feed being broken was invisible: a watch that has never polled once looks exactly like a quiet repository. The number now comes from the first URL that carries one (`issue_url`, then `pull_request_url`, then `html_url`), and a fragment is dropped first: a comment's `html_url` points at the comment (`…/pulls/1#issuecomment-164`), not at its thread. `is_pr` reads the same three URLs, so a PR comment whose `issue_url` is blank still lands on the pull request's sequence. A row with no number anywhere is still a loud parse error — the fallbacks must not degrade into a silently skipped event. --- .../rhema-forge-integration/src/event.rs | 66 +++++++++++ .../rhema-forge-integration/src/gitea.rs | 104 ++++++++++++++++-- .../rhema-forge-integration/src/watcher.rs | 20 +++- .../rhema-forge-integration/tests/gitea.rs | 52 +++++++++ 4 files changed, 229 insertions(+), 13 deletions(-) diff --git a/integrations/rhema-forge-integration/src/event.rs b/integrations/rhema-forge-integration/src/event.rs index 43c023a..89ffb14 100644 --- a/integrations/rhema-forge-integration/src/event.rs +++ b/integrations/rhema-forge-integration/src/event.rs @@ -380,6 +380,44 @@ impl Timestamp { pub fn epoch_secs(&self) -> i64 { self.secs } + + /// The instant `millis` milliseconds past the Unix epoch, in the + /// canonical `YYYY-MM-DDThh:mm:ss[.mmm]Z` spelling. + /// + /// This is how a cursor is born without a forge: a subsystem that + /// starts watching *now* (rather than replaying a feed's history) + /// needs a `since` spelled the way the forges spell theirs, and this + /// is the one place that conversion lives. + pub fn from_epoch_millis(millis: i64) -> Option { + let secs = millis.div_euclid(1000); + let sub_millis = millis.rem_euclid(1000); + let (days, of_day) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (year, month, day) = civil_from_days(days); + let (hour, minute, second) = (of_day / 3_600, (of_day / 60) % 60, of_day % 60); + let raw = if sub_millis == 0 { + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z") + } else { + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{sub_millis:03}Z") + }; + Self::parse(&raw) + } +} + +/// The civil date `days` days past 1970-01-01, as `(year, month, day)` — +/// the inverse of [`days_from_civil`] (Howard Hinnant's algorithm). +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let day_of_era = z - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let mp = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if month <= 2 { year + 1 } else { year }; + (year, month as u32, day as u32) } /// A run of ASCII digits at `range`, as its number. @@ -524,4 +562,32 @@ mod tests { .expect("deserializes"); assert_eq!(round, event); } + + #[test] + fn a_timestamp_is_born_from_epoch_millis() { + // The whole-second spelling the forges send, and the fractional + // one GitLab sends: both round-trip back to the same instant. + let whole = + Timestamp::from_epoch_millis(1_791_417_600_000).expect("a millis instant parses"); + assert_eq!(whole.raw(), "2026-10-08T00:00:00Z"); + assert_eq!(whole.epoch_secs(), 1_791_417_600); + + let fractional = + Timestamp::from_epoch_millis(1_791_417_600_081).expect("a millis instant parses"); + assert_eq!(fractional.raw(), "2026-10-08T00:00:00.081Z"); + assert_eq!(fractional.epoch_secs(), whole.epoch_secs()); + + // The epoch itself, and a leap day, so the civil-date inverse is + // exercised somewhere other than "today". + assert_eq!( + Timestamp::from_epoch_millis(0).expect("parses").raw(), + "1970-01-01T00:00:00Z" + ); + assert_eq!( + Timestamp::from_epoch_millis(1_709_164_800_000) + .expect("parses") + .raw(), + "2024-02-29T00:00:00Z" + ); + } } diff --git a/integrations/rhema-forge-integration/src/gitea.rs b/integrations/rhema-forge-integration/src/gitea.rs index ed336b3..bff7f1a 100644 --- a/integrations/rhema-forge-integration/src/gitea.rs +++ b/integrations/rhema-forge-integration/src/gitea.rs @@ -477,20 +477,17 @@ fn review_event( /// The comment event a repo-wide comments row carries. fn comment_event(row: &WireComment, repo: &RepoRef) -> Result, ForgeError> { let id = required(row.id, "comment id")?; - let issue_url = required(row.issue_url.clone(), "comment issue_url")?; - let number = parent_number(&issue_url).ok_or_else(|| { + let number = comment_parent(row).ok_or_else(|| { ForgeError::Parse(format!( - "comment issue_url without a thread number: {issue_url}" + "comment {id} names no thread: issue_url {:?}, pull_request_url {:?}, html_url {:?}", + row.issue_url, row.pull_request_url, row.html_url )) })?; let timestamp = required( row.updated_at.clone().or_else(|| row.created_at.clone()), "comment timestamp", )?; - let is_pr = row - .pull_request_url - .as_deref() - .is_some_and(|url| !url.is_empty()); + let is_pr = comment_is_pr(row); Ok(Some(ForgeEvent { id: format!("gitea:comment:{id}"), kind: EventKind::Comment, @@ -505,9 +502,45 @@ fn comment_event(row: &WireComment, repo: &RepoRef) -> Result })) } -/// The parent thread number: a forge thread URL's trailing segment. +/// Every URL a comment row carries, most specific first. +fn comment_urls(row: &WireComment) -> [Option<&str>; 3] { + [ + row.issue_url.as_deref(), + row.pull_request_url.as_deref(), + row.html_url.as_deref(), + ] +} + +/// The thread number a comment row names. +/// +/// `issue_url` is the field the API documents for it, but it is not +/// reliable: the instance behind `git.vhaudiquet.fr` (28.3.0) sends it +/// as an empty string on every row of the repo-wide `/issues/comments` +/// feed, while `pull_request_url` and `html_url` stay populated. The +/// number is therefore read from the first URL that carries one, in +/// order of directness. +fn comment_parent(row: &WireComment) -> Option { + comment_urls(row).into_iter().flatten().find_map(parent_number) +} + +/// [`comment_parent`]'s "is it a pull request" half: `pull_request_url` +/// is set exactly on PR conversation comments, and stays set on the +/// instances whose `issue_url` is blank — but a row that lost both still +/// says so in its `html_url` path. +fn comment_is_pr(row: &WireComment) -> bool { + comment_urls(row) + .into_iter() + .flatten() + .any(|url| url.contains("/pulls/") || url.contains("/pull/")) +} + +/// The parent thread number: a forge thread URL's trailing segment, +/// with any fragment dropped first — a comment's `html_url` points at +/// the comment (`…/pulls/1#issuecomment-164`), and its fragment is not +/// a number at all. fn parent_number(url: &str) -> Option { - url.trim_end_matches('/').rsplit('/').next()?.parse().ok() + let path = url.split('#').next()?; + path.trim_end_matches('/').rsplit('/').next()?.parse().ok() } /// The fixed [`NotificationReason::Other`] spelling every reason-less @@ -895,4 +928,57 @@ mod tests { .expect("comment carries an event"); assert!(!event.is_pr); } + + #[test] + fn a_comment_with_a_blank_issue_url_still_names_its_thread() { + // git.vhaudiquet.fr (28.3.0) sends `issue_url: ""` on every row + // of the repo-wide comments feed. The poll used to fail on the + // first such row, which is why that watch never reported a single + // event: a PR comment must still resolve to its pull request. + let comment: WireComment = serde_json::from_str( + r#"{"id": 164, "user": {"login": "alice"}, "body": "thanks", + "created_at": "2026-10-19T08:14:39Z", + "updated_at": "2026-10-19T08:14:39Z", + "issue_url": "", + "pull_request_url": "https://forge.example/acme/widgets/pulls/3", + "html_url": "https://forge.example/acme/widgets/pulls/3#issuecomment-164"}"#, + ) + .expect("comment fixture parses"); + let event = comment_event(&comment, &repo()) + .expect("a blank issue_url is not a parse failure") + .expect("comment carries an event"); + assert_eq!(event.number, 3); + assert!(event.is_pr); + } + + #[test] + fn a_comment_with_only_an_html_url_reads_the_thread_off_its_path() { + // The last resort: no issue_url and no pull_request_url. The + // html_url points at the comment, so the fragment has to go + // before the trailing segment means anything. + let comment: WireComment = serde_json::from_str( + r#"{"id": 165, "created_at": "2026-10-19T09:00:00Z", + "updated_at": "2026-10-19T09:00:00Z", + "html_url": "https://forge.example/acme/widgets/issues/7#issuecomment-165"}"#, + ) + .expect("comment fixture parses"); + let event = comment_event(&comment, &repo()) + .expect("maps") + .expect("comment carries an event"); + assert_eq!(event.number, 7); + assert!(!event.is_pr); + } + + #[test] + fn a_comment_whose_urls_name_no_thread_is_still_loud() { + // The fallbacks must not degrade into a silent skip: a row with + // no number anywhere is a vocabulary gap, and the poll says so. + let comment: WireComment = serde_json::from_str( + r#"{"id": 166, "created_at": "2026-10-19T09:00:00Z", + "issue_url": "", "html_url": "https://forge.example/acme/widgets/issues/"}"#, + ) + .expect("comment fixture parses"); + let err = comment_event(&comment, &repo()).expect_err("no thread number names a thread"); + assert!(matches!(err, ForgeError::Parse(_)), "got {err:?}"); + } } diff --git a/integrations/rhema-forge-integration/src/watcher.rs b/integrations/rhema-forge-integration/src/watcher.rs index 596d163..3bd4d44 100644 --- a/integrations/rhema-forge-integration/src/watcher.rs +++ b/integrations/rhema-forge-integration/src/watcher.rs @@ -177,12 +177,24 @@ impl Watcher { .cloned() } - /// One poll of `repo`: the page's events are ingested in feed order - /// and the cursor advances to the page's. Returns how many events were - /// fed to the dispatcher — replayed ids included, they dedup there. + /// One poll of `repo` from the watcher's own cursor. pub async fn poll(&self, forge: &dyn Forge, repo: &RepoRef) -> Result { let since = self.cursor(repo); - let page = forge.poll(repo, since.as_ref()).await?; + self.poll_since(forge, repo, since.as_ref()).await + } + + /// One poll of `repo` from an explicit `since`, for the embedder that + /// keeps the cursor somewhere durable: the page's events are ingested + /// in feed order and the watcher's cursor advances to the page's. + /// Returns how many events were fed to the dispatcher — replayed ids + /// included, they dedup there while they sit in an inbox. + pub async fn poll_since( + &self, + forge: &dyn Forge, + repo: &RepoRef, + since: Option<&Timestamp>, + ) -> Result { + let page = forge.poll(repo, since).await?; let now = SystemClock.now_millis(); let mut fed = 0; for event in &page.events { diff --git a/integrations/rhema-forge-integration/tests/gitea.rs b/integrations/rhema-forge-integration/tests/gitea.rs index 248d2c4..b721835 100644 --- a/integrations/rhema-forge-integration/tests/gitea.rs +++ b/integrations/rhema-forge-integration/tests/gitea.rs @@ -557,3 +557,55 @@ async fn notifications_poll_maps_the_subject_feed() { assert_eq!(note.repo, RepoRef::new("acme", "widgets")); assert_eq!(note.title.as_deref(), Some("Fix the gate")); } + +/// The instance behind `git.vhaudiquet.fr` sends `issue_url: ""` on every +/// row of the repo-wide comments feed. A poll with one such row used to +/// fail outright, so the watch it fed never reported anything at all. +#[tokio::test] +async fn poll_survives_a_comments_feed_with_blank_issue_urls() { + let server = MockServer::start().await; + for (endpoint, body) in [ + ("/api/v1/repos/acme/widgets/issues", json!([])), + ("/api/v1/repos/acme/widgets/pulls", json!([])), + ] { + Mock::given(method("GET")) + .and(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(&server) + .await; + } + Mock::given(method("GET")) + .and(path("/api/v1/repos/acme/widgets/issues/comments")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + { "id": 164, "user": { "login": "alice" }, "body": "thanks", + "created_at": "2026-10-19T08:14:39Z", + "updated_at": "2026-10-19T08:14:39Z", + "issue_url": "", + "pull_request_url": "https://forge.example/acme/widgets/pulls/1", + "html_url": "https://forge.example/acme/widgets/pulls/1#issuecomment-164" }, + { "id": 165, "user": { "login": "bob" }, "body": "still broken", + "created_at": "2026-10-19T09:00:00Z", + "updated_at": "2026-10-19T09:00:00Z", + "issue_url": "", + "pull_request_url": Value::Null, + "html_url": "https://forge.example/acme/widgets/issues/2#issuecomment-165" } + ]))) + .mount(&server) + .await; + + let since = Timestamp::parse(SINCE).expect("cursor parses"); + let page = forge(&server) + .poll(&RepoRef::new("acme", "widgets"), Some(&since)) + .await + .expect("a blank issue_url is not a poll failure"); + + let summary: Vec<(EventKind, u64, bool)> = page + .events + .iter() + .map(|event| (event.kind, event.number, event.is_pr)) + .collect(); + assert_eq!( + summary, + vec![(EventKind::Comment, 1, true), (EventKind::Comment, 2, false)] + ); +}