//! 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, /// 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, } impl ForgePage { /// Folds collected events into a page: sorts them and advances the /// cursor past everything seen. pub(crate) fn finish(mut events: Vec, 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; /// 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; /// 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; /// 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, 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); } }