Files
rhema-claw/integrations/rhema-forge-integration/src/forge.rs
T
kosmos f779415b2b fix(forge): consume a decided account notification
The account feed is at-least-once in a way the dedup ids do not cover.
`since` is inclusive at the boundary and `NotificationPage::finish`
advances its cursor only to the newest row seen, so a row the poll cannot
get past — anything at or before the cursor, which is every poll — comes
back for as long as the forge still considers it unread. Nothing marked
it read, and the daemon's cursor map is in memory, so a restart asked for
the whole unread feed again.

The result is a re-dispatch loop: the same notification id re-triaged
every pass, a fresh turn for a thread that already has one, and a second
comment on that thread if the first turn ever finished inside its lease.
Observed live on `vhaudiquet/orcaslicer-snap#10`: key revision 1 → 2 at
the 00:35 poll, `inbox_depth: 0`, no outcome — a re-dispatch of a turn
that was already running.

So consume what the poll decides:

- `Forge::mark_read` — a new default no-op on the trait, implemented for
  GitHub as `PUT /notifications/threads/{id}`;
- `Notification::read_key` carries what that route keys on (GitHub keys
  on the notification id, which the dedup id embeds only as text), and
  defaults on deserialize so a payload already in an inbox still decodes;
- `poll_account` marks each row read once it is triaged — dispatched,
  surfaced, or ignored; best-effort, since an unread row costs a repeat
  and never a lost event.

Gitea and GitLab keep the no-op: neither has an account watch here yet.
2026-11-22 01:34:11 +00:00

201 lines
7.9 KiB
Rust

//! The forge client contract: one trait, three calls.
//!
//! [`Forge`] is the whole surface a consumer needs: poll a repo's
//! activity against a cursor, post a comment, and fetch a thread
//! snapshot so an answering handler can orient without a second API
//! round-trip. Implementations are cheap to clone and share — the
//! reqwest client inside is reference-counted — and object-safe so a
//! backend can be swapped without generics.
//!
//! Polls are at-least-once. The forges' `since`-style filters match rows
//! at-or-after the cursor, so boundary rows repeat across polls, and a
//! row that changes between a backend's feeds can surface twice under
//! different ids. Both are harmless under the RSD dedup: consumers must
//! treat the event `id` as the only dedup key, never `(repo, number)`.
use async_trait::async_trait;
use crate::error::ForgeError;
use crate::event::{
ForgeEvent, ForgeThreadKind, Notification, NotificationPage, RepoRef, Snapshot, Timestamp,
};
/// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)]
pub struct ForgePage {
/// The events, oldest first, ties broken by id — a deterministic
/// order regardless of which feed produced an event.
pub events: Vec<ForgeEvent>,
/// The cursor for the next poll: the newest event time seen, never
/// earlier than the poll's `since`. `None` only when the poll had no
/// anchor and came back empty — the repo is simply quiet.
pub cursor: Option<Timestamp>,
}
impl ForgePage {
/// Folds collected events into a page: sorts them and advances the
/// cursor past everything seen.
pub(crate) fn finish(mut events: Vec<ForgeEvent>, since: Option<&Timestamp>) -> Self {
events.sort_by(|a, b| (&a.timestamp, &a.id).cmp(&(&b.timestamp, &b.id)));
let mut cursor = since.cloned();
for timestamp in events.iter().map(|event| &event.timestamp) {
cursor = Some(match cursor {
Some(current) if current >= *timestamp => current,
_ => timestamp.clone(),
});
}
Self { events, cursor }
}
}
/// A forge backend: the client for one REST dialect.
#[async_trait]
pub trait Forge: Send + Sync {
/// Recent activity for `repo`, oldest first, all pages collected.
///
/// `since` anchors the poll: `None` lists from the beginning (a first
/// poll); `Some(cursor)` asks for rows at-or-after the cursor, whose
/// boundary rows may repeat — their stable ids make the repetition
/// dedupable downstream, never duplicated work.
async fn poll(
&self,
repo: &RepoRef,
since: Option<&Timestamp>,
) -> Result<ForgePage, ForgeError>;
/// Posts `body` as a new comment on the thread `kind` + `number`
/// name.
///
/// On GitLab the kind picks the sequence the iid is read against:
/// issues and merge requests are numbered independently, and only
/// the named one is addressed — a miss surfaces as a 404, never a
/// silent post to the other sequence. GitHub and Gitea share one
/// number space across issues and pull requests (every pull request
/// is an issue there), so they accept the kind for signature
/// uniformity and either value addresses the same thread.
async fn comment(
&self,
repo: &RepoRef,
kind: ForgeThreadKind,
number: u64,
body: &str,
) -> Result<(), ForgeError>;
/// The thread's current state, so a handler can orient without a
/// second API round-trip. `kind` selects the sequence `number` is
/// read against, under the same rules as [`Forge::comment`].
async fn snapshot(
&self,
repo: &RepoRef,
kind: ForgeThreadKind,
number: u64,
) -> Result<Snapshot, ForgeError>;
/// The account's notification feed: everything addressed to the
/// account this client authenticates as, across every repository it
/// can see — the account-scoped counterpart of [`Forge::poll`],
/// whose feeds are repo-scoped. `since` anchors the poll with the
/// same at-least-once semantics as `poll`: boundary rows repeat, and
/// the stable ids make the repetition dedupable downstream.
async fn notifications(
&self,
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// Marks `notification` read on the forge, so the account's feed
/// stops returning it.
///
/// The feed is at-least-once: `since` is inclusive at the boundary
/// and the cursor only ever advances to the newest row seen, so a row
/// that the poll cannot get past — anything at or before the cursor,
/// every poll — comes back for as long as the forge considers it
/// unread. Dedup ids absorb a repeat *within* one pass, but a row
/// re-read on the next pass is a fresh event with the same id, and a
/// restart drops the in-memory cursor entirely and asks for the whole
/// unread feed again. Deciding a row is therefore not the same as
/// consuming it; this is the call that consumes it.
///
/// The default is a no-op: a backend with no read route repeats its
/// rows, which its dedup ids absorb — noisier, never wrong.
async fn mark_read(&self, _notification: &Notification) -> Result<(), ForgeError> {
Ok(())
}
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
/// A consumer that must recognize its own handle (to see an @-mention
/// in a body, and to ignore its own replies) cannot always read it off
/// its credential: a token pasted into a watch row, or an environment
/// variable, names nobody. `None` is the honest default — a backend
/// with no such route simply cannot say who it is — and a backend that
/// can say answers with its `/user` row.
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::EventKind;
use serde_json::json;
fn event(id: &str, at: &str) -> ForgeEvent {
ForgeEvent {
id: id.to_owned(),
kind: EventKind::Comment,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: None,
body: None,
url: None,
timestamp: Timestamp::parse(at).expect("timestamp parses"),
raw: json!({}),
}
}
#[test]
fn events_sort_oldest_first_with_id_ties() {
let page = ForgePage::finish(
vec![
event("b", "2026-10-08T00:00:00Z"),
event("z", "2026-10-07T00:00:00Z"),
event("a", "2026-10-08T00:00:00Z"),
],
None,
);
let ids: Vec<&str> = page.events.iter().map(|event| event.id.as_str()).collect();
assert_eq!(ids, ["z", "a", "b"]);
}
#[test]
fn the_cursor_never_goes_backwards() {
// A since newer than everything seen holds: the next poll repeats
// the boundary instead of re-listing old history.
let since = Timestamp::parse("2026-10-09T00:00:00Z").expect("parses");
let page = ForgePage::finish(vec![event("a", "2026-10-08T00:00:00Z")], Some(&since));
assert_eq!(page.cursor, Some(since));
let page = ForgePage::finish(
vec![event("a", "2026-10-10T00:00:00Z")],
Some(&Timestamp::parse("2026-10-09T00:00:00Z").expect("parses")),
);
assert_eq!(
page.cursor,
Some(Timestamp::parse("2026-10-10T00:00:00Z").expect("parses"))
);
}
#[test]
fn empty_pages_keep_or_drop_the_cursor_depending_on_the_anchor() {
let since = Timestamp::parse("2026-10-09T00:00:00Z").expect("parses");
let page = ForgePage::finish(vec![], Some(&since));
assert_eq!(page.cursor, Some(since));
let page = ForgePage::finish(vec![], None);
assert_eq!(page.cursor, None);
}
}