Skip to main content

octo_notify/
lib.rs

1//! # octo-notify
2//!
3//! A focused Rust client for the GitHub Notifications API: complete, typed coverage of every
4//! endpoint, plus a polling engine for building applications on the notifications inbox. It is
5//! not a general GitHub client.
6//!
7//! ## Layers
8//!
9//! 1. **Typed client** ([`Client`]): every Notifications endpoint, conditional requests
10//!    (`If-Modified-Since` / `304`), rate-limit accounting, pagination, and forward-compatible
11//!    models.
12//! 2. **App engine** ([`Poller`](crate::app::Poller)): the inbox as an async
13//!    [`Stream`](futures::Stream) of [`Event`](crate::app::Event)s, with client-side filters.
14//! 3. **State** ([`StateStore`](crate::app::StateStore)): dedupe across restarts.
15//!
16//! Layers 2 and 3 need the `stream` feature, which is on by default.
17//!
18//! ## Authentication
19//!
20//! The notifications inbox is user-scoped, so authentication is a single bearer token. A classic
21//! PAT needs the `notifications` scope (or `repo` to also read issue and commit subjects); a
22//! fine-grained PAT needs the read-only "Notifications" account permission.
23//!
24//! ```no_run
25//! use octo_notify::{Auth, Client};
26//!
27//! # fn main() -> octo_notify::Result<()> {
28//! let client = Client::new(Auth::from_env()?)?; // GITHUB_TOKEN or GH_TOKEN
29//! let explicit = Client::new(Auth::token("ghp_example"))?;
30//! # let _ = (client, explicit);
31//! # Ok(())
32//! # }
33//! ```
34//!
35//! Tokens come from a [`TokenProvider`], so credentials that expire can refresh themselves. The
36//! `token-refresh` feature adds `RefreshingToken` for GitHub App user-to-server tokens. Override
37//! the base URL for GitHub Enterprise Server:
38//!
39//! ```no_run
40//! # use octo_notify::{Auth, Client};
41//! # fn main() -> octo_notify::Result<()> {
42//! let client = Client::builder()
43//!     .auth(Auth::from_env()?)
44//!     .base_url("https://ghe.example.com/api/v3")
45//!     .user_agent("my-app/1.0")
46//!     .build()?;
47//! # let _ = client;
48//! # Ok(())
49//! # }
50//! ```
51//!
52//! ## Listing notifications
53//!
54//! `client.notifications()` lists the inbox; `client.repo(owner, name).notifications()` scopes to
55//! one repository. A single `send()` returns a [`Listing`] (which may be [`Listing::NotModified`]
56//! when the request is conditional); `all()` collects every page and `stream()` yields items
57//! across pages.
58//!
59//! ```no_run
60//! use octo_notify::{Auth, Client, Listing, Reason};
61//!
62//! # async fn run() -> octo_notify::Result<()> {
63//! let client = Client::new(Auth::from_env()?)?;
64//! let listing = client.notifications().list().participating(true).send().await?;
65//! if let Listing::Modified(page) = listing {
66//!     for n in &page.items {
67//!         if matches!(n.reason, Reason::Mention) {
68//!             println!("{} - {}", n.repository.full_name, n.subject.title);
69//!         }
70//!     }
71//! }
72//! # Ok(())
73//! # }
74//! ```
75//!
76//! ## Threads and subscriptions
77//!
78//! `client.thread(id)` operates on one thread: fetch it, mark it read or done (one-way), and
79//! manage its subscription.
80//!
81//! ```no_run
82//! # use octo_notify::{Auth, Client};
83//! # async fn run() -> octo_notify::Result<()> {
84//! let client = Client::new(Auth::from_env()?)?;
85//! let thread = client.thread("123456789");
86//! let notification = thread.get().await?;
87//! thread.mark_read().await?;
88//! thread.set_subscription(true).await?; // ignore future notifications
89//! # let _ = notification;
90//! # Ok(())
91//! # }
92//! ```
93//!
94//! ## Watching the inbox
95//!
96//! [`Client::poller`] builds a [`Poller`](crate::app::Poller) that yields an async stream of
97//! [`Event`](crate::app::Event)s. By default it watches the whole inbox, obeys the server poll
98//! interval, and dedupes through an in-memory store. Filter by reason, subject type, repository,
99//! or a predicate.
100//!
101//! ```no_run
102//! use futures::StreamExt;
103//! use octo_notify::app::Event;
104//! use octo_notify::{Auth, Client, Reason};
105//!
106//! # async fn run() -> octo_notify::Result<()> {
107//! let client = Client::new(Auth::from_env()?)?;
108//! let mut events = Box::pin(client.poller().reasons([Reason::ReviewRequested]).build().stream());
109//! while let Some(event) = events.next().await {
110//!     match event? {
111//!         Event::New(n) => println!("new: {}", n.subject.title),
112//!         Event::Updated(n) => println!("updated: {}", n.subject.title),
113//!     }
114//! }
115//! # Ok(())
116//! # }
117//! ```
118//!
119//! Persist state across restarts with the `file-store` feature and `JsonFileStore`:
120//!
121//! ```ignore
122//! use octo_notify::app::JsonFileStore;
123//!
124//! let store = JsonFileStore::open("/var/cache/octo-notify.json")?;
125//! let poller = client.poller().store(store).build();
126//! ```
127//!
128//! ### Robustness contract
129//!
130//! - **Transient vs fatal errors:** network blips, 5xx, and rate limits back off and retry; only
131//!   fatal errors (for example `401`) end the stream.
132//! - **At-least-once delivery:** events emit in ascending `updated_at`; per-thread seen state
133//!   commits after delivery and the `Last-Modified` watermark advances only after the full tick,
134//!   so a crash re-emits rather than drops. Dedupe downstream on `(id, updated_at)`.
135//! - **Pagination vs conditional requests:** the `If-Modified-Since` check applies to page 1; on
136//!   a change, all pages are fetched before classification, so the inbox is never half-read.
137//! - **Shutdown:** drop the stream, or pass a `CancellationToken` for cooperative shutdown.
138//!
139//! ## Bulk actions
140//!
141//! Mark many threads read or done concurrently, with a bounded worker count and per-item results.
142//!
143//! ```no_run
144//! # use octo_notify::{Auth, Client, ThreadId};
145//! # async fn run() -> octo_notify::Result<()> {
146//! let client = Client::new(Auth::from_env()?)?;
147//! let ids = [ThreadId::from("1"), ThreadId::from("2")];
148//! for (id, result) in client.mark_done_each(ids, 8).await {
149//!     if let Err(e) = result {
150//!         eprintln!("{id}: {e}");
151//!     }
152//! }
153//! # Ok(())
154//! # }
155//! ```
156//!
157//! ## Errors and rate limits
158//!
159//! Every fallible call returns [`Result`]. [`Error`] distinguishes API errors, primary and
160//! secondary rate limits ([`Error::RateLimited`] with [`RateLimitKind`]), authentication
161//! failures, and deserialization problems. A `304` is success, not an error: it surfaces as
162//! [`Listing::NotModified`]. With the `retry` feature, `RetryPolicy` makes one-shot calls wait
163//! out rate limits automatically.
164//!
165//! ## Feature flags
166//!
167//! | Feature | Default | Description |
168//! |---|---|---|
169//! | `rustls` | yes | TLS via rustls |
170//! | `native-tls` | no | TLS via the platform's native stack |
171//! | `stream` | yes | The poller engine and `stream()` pagination |
172//! | `file-store` | no | `JsonFileStore`, file-backed state for cross-restart dedupe |
173//! | `sqlite-store` | no | `SqliteStore`, SQLite-backed state |
174//! | `token-refresh` | no | `RefreshingToken` for expiring credentials |
175//! | `retry` | no | `RetryPolicy` for auto-retrying rate-limited calls |
176//! | `tracing` | no | Structured `tracing` instrumentation of requests and the poller |
177//! | `cli` | no | The `octo-notify` command-line binary (`cargo install octo-notify --features cli`) |
178//!
179//! With the `tracing` feature on, install any `tracing` subscriber (for example
180//! `tracing-subscriber`) in your application to see request, rate-limit, and poller events.
181
182#![forbid(unsafe_code)]
183#![warn(missing_docs)]
184
185/// Emit a `tracing` debug event when the `tracing` feature is on; a no-op otherwise.
186macro_rules! tdebug {
187    ($($arg:tt)*) => {{
188        #[cfg(feature = "tracing")]
189        ::tracing::debug!($($arg)*);
190    }};
191}
192/// Emit a `tracing` warn event when the `tracing` feature is on; a no-op otherwise.
193macro_rules! twarn {
194    ($($arg:tt)*) => {{
195        #[cfg(feature = "tracing")]
196        ::tracing::warn!($($arg)*);
197    }};
198}
199
200#[cfg(feature = "stream")]
201pub mod app;
202pub mod auth;
203#[cfg(feature = "cli")]
204pub mod cli;
205mod client;
206pub mod endpoints;
207pub mod error;
208pub mod models;
209pub mod pagination;
210pub mod rate_limit;
211
212#[cfg(feature = "token-refresh")]
213pub use auth::RefreshingToken;
214pub use auth::{Auth, TokenProvider};
215#[cfg(feature = "retry")]
216pub use client::RetryPolicy;
217pub use client::{Client, ClientBuilder};
218pub use endpoints::{
219    ListNotifications, ListSubscriptions, MarkAllRead, NotificationsHandler, RepoHandler,
220    RepoNotificationsHandler, ThreadHandler,
221};
222pub use error::{Error, RateLimitKind, Result};
223pub use models::{
224    MinimalRepository, Notification, Reason, RepositorySubscription, SimpleUser, Subject,
225    SubjectType, ThreadId, ThreadSubscription,
226};
227pub use pagination::{Listing, NotModified, Page};
228pub use rate_limit::RateLimit;
229pub use secrecy::SecretString;
230
231/// Common imports for downstream apps: `use octo_notify::prelude::*;`.
232pub mod prelude {
233    pub use crate::{
234        Auth, Client, Error, Listing, Notification, Page, Reason, Result, Subject, SubjectType,
235    };
236}