From dcedaf282f80b1f04a86e2ff71be1d15aa1f78aa Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Wed, 18 Nov 2026 07:38:34 -0500 Subject: [PATCH 01/14] feat(logic): records, time helpers and validated config Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- Cargo.lock | 202 ++++++++++++++++++++++++++ Cargo.toml | 8 + crates/logic/Cargo.toml | 14 ++ crates/logic/src/config.rs | 273 +++++++++++++++++++++++++++++++++++ crates/logic/src/lib.rs | 7 + crates/logic/src/record.rs | 56 +++++++ crates/logic/src/time.rs | 16 ++ crates/logic/tests/config.rs | 168 +++++++++++++++++++++ crates/logic/tests/record.rs | 43 ++++++ crates/logic/tests/time.rs | 29 ++++ rustfmt.toml | 1 + 11 files changed, 817 insertions(+) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/logic/Cargo.toml create mode 100644 crates/logic/src/config.rs create mode 100644 crates/logic/src/lib.rs create mode 100644 crates/logic/src/record.rs create mode 100644 crates/logic/src/time.rs create mode 100644 crates/logic/tests/config.rs create mode 100644 crates/logic/tests/record.rs create mode 100644 crates/logic/tests/time.rs create mode 100644 rustfmt.toml diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0cb657c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,202 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "mailroom-logic" +version = "0.1.0" +dependencies = [ + "chrono", + "pollster", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e79a491 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +resolver = "2" +members = ["crates/logic"] + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 diff --git a/crates/logic/Cargo.toml b/crates/logic/Cargo.toml new file mode 100644 index 0000000..146ee17 --- /dev/null +++ b/crates/logic/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "mailroom-logic" +version = "0.1.0" +edition = "2021" +license = "MIT" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +chrono = { version = "0.4", default-features = false, features = ["alloc"] } +schemars = "1" + +[dev-dependencies] +pollster = "0.4" diff --git a/crates/logic/src/config.rs b/crates/logic/src/config.rs new file mode 100644 index 0000000..a4351d9 --- /dev/null +++ b/crates/logic/src/config.rs @@ -0,0 +1,273 @@ +//! Validated mailroom configuration (the `MAILROOM` var). + +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::fmt; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::record::{Kind, Src}; + +const MIN_EVERY_SECS: u32 = 60; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default = "default_retain_days")] + pub retain_days: u32, + pub agents: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AgentConfig { + pub sources: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SourceConfig { + Discord(DiscordSource), + Github(GithubSource), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DiscordSource { + pub broker: String, + #[serde(default = "default_discord_every")] + pub every_secs: u32, + pub channels: Vec, + #[serde(default = "default_true")] + pub reactions: bool, + #[serde(default = "default_true")] + pub skip_self: bool, + #[serde(default)] + pub keep: Keep, + #[serde(default)] + pub rules: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GithubSource { + pub broker: String, + #[serde(default = "default_github_every")] + pub every_secs: u32, + pub repos: Vec, + #[serde(default)] + pub review_label: Option, + #[serde(default = "default_true")] + pub skip_self: bool, + #[serde(default)] + pub keep: Keep, + #[serde(default)] + pub rules: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Keep { + #[default] + All, + Tagged, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Rule { + pub when: When, + pub then: Then, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct When { + pub kind: Vec, + pub actor: Vec, + pub actor_not: Vec, + #[serde(rename = "ref")] + pub reference: Vec, + pub tag: Vec, + pub body_contains: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Then { + Drop, + Tag(String), +} + +fn default_retain_days() -> u32 { + 30 +} +fn default_discord_every() -> u32 { + 120 +} +fn default_github_every() -> u32 { + 300 +} +fn default_true() -> bool { + true +} + +/// A configuration problem; `Display` prints the message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigError(pub String); + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for ConfigError {} + +impl Config { + /// Deserializes, then validates. + pub fn parse(json: &str) -> Result { + let config: Config = + serde_json::from_str(json).map_err(|e| ConfigError(format!("invalid config: {e}")))?; + config.validate()?; + Ok(config) + } + + pub fn validate(&self) -> Result<(), ConfigError> { + if self.agents.is_empty() { + return Err(ConfigError("agents: must not be empty".into())); + } + for (name, agent) in &self.agents { + let valid_name = (1..=32).contains(&name.len()) + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + if !valid_name { + return Err(ConfigError(format!( + "agent {name:?}: name must be 1-32 chars of a-z, 0-9, '-'" + ))); + } + for (i, source) in agent.sources.iter().enumerate() { + validate_source(name, i, source)?; + } + } + Ok(()) + } +} + +fn validate_source(agent: &str, index: usize, source: &SourceConfig) -> Result<(), ConfigError> { + let at = format!("agent {agent:?} source {index}"); + let fail = |field: &str, msg: String| Err(ConfigError(format!("{at}: {field}: {msg}"))); + + let broker = source.broker(); + if broker.is_empty() + || !broker + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + return fail( + "broker", + format!("{broker:?} must be non-empty and only A-Z, 0-9, '_'"), + ); + } + if source.every_secs() < MIN_EVERY_SECS { + return fail( + "every_secs", + format!("{} is below the minimum of {MIN_EVERY_SECS}", source.every_secs()), + ); + } + + let mut seen = BTreeSet::new(); + match source { + SourceConfig::Discord(d) => { + if d.channels.is_empty() { + return fail("channels", "must not be empty".into()); + } + for c in &d.channels { + if !(5..=25).contains(&c.len()) || !c.bytes().all(|b| b.is_ascii_digit()) { + return fail("channels", format!("{c:?} must be 5-25 ASCII digits")); + } + if !seen.insert(c) { + return fail("channels", format!("duplicate {c:?}")); + } + } + } + SourceConfig::Github(g) => { + if g.repos.is_empty() { + return fail("repos", "must not be empty".into()); + } + for r in &g.repos { + let ok = matches!(r.split_once('/'), Some((o, n)) if !o.is_empty() && !n.is_empty() && !n.contains('/')); + if !ok { + return fail("repos", format!("{r:?} must be owner/name")); + } + if !seen.insert(r) { + return fail("repos", format!("duplicate {r:?}")); + } + } + if g.review_label.as_deref() == Some("") { + return fail("review_label", "must not be empty".into()); + } + } + } + for rule in source.rules() { + if rule.then == Then::Tag(String::new()) { + return fail("rules", "tag must not be empty".into()); + } + } + Ok(()) +} + +impl SourceConfig { + pub fn broker(&self) -> &str { + match self { + SourceConfig::Discord(d) => &d.broker, + SourceConfig::Github(g) => &g.broker, + } + } + + pub fn every_secs(&self) -> u32 { + match self { + SourceConfig::Discord(d) => d.every_secs, + SourceConfig::Github(g) => g.every_secs, + } + } + + pub fn src(&self) -> Src { + match self { + SourceConfig::Discord(_) => Src::Discord, + SourceConfig::Github(_) => Src::Github, + } + } + + pub fn keep(&self) -> Keep { + match self { + SourceConfig::Discord(d) => d.keep, + SourceConfig::Github(g) => g.keep, + } + } + + pub fn rules(&self) -> &[Rule] { + match self { + SourceConfig::Discord(d) => &d.rules, + SourceConfig::Github(g) => &g.rules, + } + } + + /// "discord::" or "github::/", in config order. + pub fn target_keys(&self) -> Vec { + match self { + SourceConfig::Discord(d) => d + .channels + .iter() + .map(|c| format!("discord:{}:{c}", d.broker)) + .collect(), + SourceConfig::Github(g) => g + .repos + .iter() + .map(|r| format!("github:{}:{r}", g.broker)) + .collect(), + } + } +} diff --git a/crates/logic/src/lib.rs b/crates/logic/src/lib.rs new file mode 100644 index 0000000..5bd8e8e --- /dev/null +++ b/crates/logic/src/lib.rs @@ -0,0 +1,7 @@ +//! Pure-Rust logic for mailroom: records, time helpers and configuration. + +pub mod config; +pub mod record; +pub mod time; + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/logic/src/record.rs b/crates/logic/src/record.rs new file mode 100644 index 0000000..3676d3c --- /dev/null +++ b/crates/logic/src/record.rs @@ -0,0 +1,56 @@ +//! Inbox record types. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Src { + Discord, + Github, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Message, + Reaction, + Gap, + Issue, + Pr, + IssueComment, + ReviewComment, + Review, + Event, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct NewRecord { + pub src: Src, + pub kind: Kind, + pub id: String, + pub ts: String, + pub actor: String, + #[serde(rename = "ref")] + pub reference: String, + pub title: String, + pub body: String, + pub url: String, + pub tags: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Record { + pub seq: i64, + pub ts_ingest: String, + #[serde(flatten)] + pub new: NewRecord, +} + +/// At most `max` chars; when cut, `suffix` is appended after the cut. +pub fn truncate(text: &str, max: usize, suffix: &str) -> String { + match text.char_indices().nth(max) { + None => text.to_string(), + Some((byte, _)) => format!("{}{}", &text[..byte], suffix), + } +} diff --git a/crates/logic/src/time.rs b/crates/logic/src/time.rs new file mode 100644 index 0000000..d56843a --- /dev/null +++ b/crates/logic/src/time.rs @@ -0,0 +1,16 @@ +//! ISO-8601 UTC helpers. + +use chrono::{DateTime, Utc}; + +/// Formats epoch seconds as `2026-11-18T10:05:00Z`. Out-of-range input yields the Unix epoch. +pub fn iso(epoch_secs: i64) -> String { + DateTime::::from_timestamp(epoch_secs, 0) + .unwrap_or_default() + .format("%Y-%m-%dT%H:%M:%SZ") + .to_string() +} + +/// Parses an RFC 3339 timestamp (`Z` or numeric offset, optional fractions) to epoch seconds. +pub fn epoch(iso: &str) -> Option { + DateTime::parse_from_rfc3339(iso).ok().map(|d| d.timestamp()) +} diff --git a/crates/logic/tests/config.rs b/crates/logic/tests/config.rs new file mode 100644 index 0000000..f446724 --- /dev/null +++ b/crates/logic/tests/config.rs @@ -0,0 +1,168 @@ +use mailroom_logic::config::*; + +const GOOD: &str = r#"{ + "retain_days": 30, + "agents": { + "claude": { + "sources": [ + { "type": "discord", "broker": "DISCORD_CLAUDE", "every_secs": 120, + "channels": ["1566796119839875999"], + "reactions": true, "skip_self": true, "keep": "all", + "rules": [ + { "when": { "kind": ["reaction"], "actor_not": ["Lothrop"] }, "then": "drop" }, + { "when": { "body_contains": ["kharon"] }, "then": { "tag": "kharon" } } + ] }, + { "type": "github", "broker": "GITHUB", "every_secs": 300, + "repos": ["CycleFive/kharon"], "review_label": "review:claude", + "skip_self": true, "keep": "tagged", "rules": [] } + ] + }, + "manus": { "sources": [ + { "type": "discord", "broker": "DISCORD_MANUS", "channels": ["1566796119839875999"] } + ] } + } +}"#; + +fn with_source(src: &str) -> String { + format!(r#"{{"agents":{{"claude":{{"sources":[{src}]}}}}}}"#) +} + +fn err(json: &str) -> String { + Config::parse(json).unwrap_err().to_string() +} + +#[test] +fn parses_spec_example_with_defaults() { + let c = Config::parse(GOOD).unwrap(); + assert_eq!(c.retain_days, 30); + let SourceConfig::Discord(d) = &c.agents["claude"].sources[0] else { + panic!() + }; + assert_eq!( + (d.every_secs, d.reactions, d.skip_self, d.keep), + (120, true, true, Keep::All) + ); + assert_eq!(d.rules[0].then, Then::Drop); + assert_eq!(d.rules[1].then, Then::Tag("kharon".into())); + assert_eq!( + c.agents["claude"].sources[0].target_keys(), + vec!["discord:DISCORD_CLAUDE:1566796119839875999"] + ); + assert_eq!( + c.agents["claude"].sources[1].target_keys(), + vec!["github:GITHUB:CycleFive/kharon"] + ); +} + +#[test] +fn minimal_discord_source_gets_defaults() { + let c = Config::parse(&with_source( + r#"{"type":"discord","broker":"B","channels":["12345"]}"#, + )) + .unwrap(); + assert_eq!(c.retain_days, 30); + let s = &c.agents["claude"].sources[0]; + let SourceConfig::Discord(d) = s else { panic!() }; + assert_eq!( + (d.every_secs, d.reactions, d.skip_self, d.keep), + (120, true, true, Keep::All) + ); + assert!(d.rules.is_empty()); + assert_eq!( + (s.broker(), s.every_secs(), s.src(), s.keep()), + ("B", 120, mailroom_logic::record::Src::Discord, Keep::All) + ); + assert!(s.rules().is_empty()); +} + +#[test] +fn minimal_github_source_gets_defaults() { + let c = Config::parse(&with_source(r#"{"type":"github","broker":"G","repos":["a/b"]}"#)).unwrap(); + assert_eq!(c.agents["claude"].sources[0].every_secs(), 300); +} + +#[test] +fn rejects_unknown_field() { + let e = err(&with_source( + r#"{"type":"discord","broker":"B","chanels":["12345"]}"#, + )); + assert!(e.contains("chanels"), "{e}"); +} + +#[test] +fn rejects_bad_agent_name() { + let e = err(r#"{"agents":{"Claude":{"sources":[]}}}"#); + assert!(e.contains("Claude"), "{e}"); +} + +#[test] +fn rejects_short_interval() { + let e = err(&with_source( + r#"{"type":"discord","broker":"B","every_secs":30,"channels":["12345"]}"#, + )); + assert!(e.contains("every_secs") && e.contains("claude"), "{e}"); +} + +#[test] +fn rejects_non_numeric_channel() { + let e = err(&with_source( + r#"{"type":"discord","broker":"B","channels":["general"]}"#, + )); + assert!(e.contains("general"), "{e}"); +} + +#[test] +fn rejects_bad_repo() { + for repo in ["kharon", "a/b/c", "/b", "a/"] { + let e = err(&with_source(&format!( + r#"{{"type":"github","broker":"G","repos":["{repo}"]}}"# + ))); + assert!(e.contains(repo), "{e}"); + } +} + +#[test] +fn rejects_duplicate_target() { + let e = err(&with_source( + r#"{"type":"discord","broker":"B","channels":["12345","12345"]}"#, + )); + assert!(e.contains("12345"), "{e}"); + assert!(Config::parse(&with_source( + r#"{"type":"github","broker":"G","repos":["a/b","a/b"]}"# + )) + .is_err()); +} + +#[test] +fn rejects_empty_agents() { + assert!(Config::parse(r#"{"agents":{}}"#).is_err()); +} + +#[test] +fn rejects_bad_broker_and_empty_tag_and_label() { + assert!(Config::parse(&with_source( + r#"{"type":"discord","broker":"bad-name","channels":["12345"]}"# + )) + .is_err()); + assert!(Config::parse(&with_source( + r#"{"type":"discord","broker":"","channels":["12345"]}"# + )) + .is_err()); + assert!(Config::parse(&with_source( + r#"{"type":"discord","broker":"B","channels":["12345"],"rules":[{"when":{},"then":{"tag":""}}]}"# + )) + .is_err()); + assert!(Config::parse(&with_source( + r#"{"type":"github","broker":"G","repos":["a/b"],"review_label":""}"# + )) + .is_err()); +} + +#[test] +fn then_serializes_as_spec() { + assert_eq!(serde_json::to_string(&Then::Drop).unwrap(), r#""drop""#); + assert_eq!( + serde_json::to_string(&Then::Tag("x".into())).unwrap(), + r#"{"tag":"x"}"# + ); +} diff --git a/crates/logic/tests/record.rs b/crates/logic/tests/record.rs new file mode 100644 index 0000000..6b46323 --- /dev/null +++ b/crates/logic/tests/record.rs @@ -0,0 +1,43 @@ +use mailroom_logic::record::*; + +#[test] +fn record_serializes_in_muse_shape() { + let r = Record { + seq: 12, + ts_ingest: "2026-11-18T10:05:00Z".into(), + new: NewRecord { + src: Src::Discord, + kind: Kind::Message, + id: "dc:1".into(), + ts: "t".into(), + actor: "Nyx".into(), + reference: "#general".into(), + title: "".into(), + body: "hi".into(), + url: "u".into(), + tags: vec!["routed:mention".into()], + }, + }; + assert_eq!( + serde_json::to_string(&r).unwrap(), + r##"{"seq":12,"ts_ingest":"2026-11-18T10:05:00Z","src":"discord","kind":"message","id":"dc:1","ts":"t","actor":"Nyx","ref":"#general","title":"","body":"hi","url":"u","tags":["routed:mention"]}"## + ); +} + +#[test] +fn kinds_are_snake_case() { + assert_eq!( + serde_json::to_string(&Kind::IssueComment).unwrap(), + r#""issue_comment""# + ); + assert_eq!(serde_json::to_string(&Kind::Pr).unwrap(), r#""pr""#); +} + +#[test] +fn truncate_counts_chars_not_bytes() { + let s = "🙂".repeat(2001); + let t = truncate(&s, 2000, ""); + assert_eq!(t.chars().count(), 2000); + assert_eq!(truncate("abcdef", 3, " [...]"), "abc [...]"); + assert_eq!(truncate("abc", 3, " [...]"), "abc"); +} diff --git a/crates/logic/tests/time.rs b/crates/logic/tests/time.rs new file mode 100644 index 0000000..e791857 --- /dev/null +++ b/crates/logic/tests/time.rs @@ -0,0 +1,29 @@ +use mailroom_logic::time::{epoch, iso}; + +#[test] +fn iso_round_trips() { + assert_eq!(epoch(&iso(1795000000)), Some(1795000000)); + assert_eq!(iso(1795000000).len(), 20); +} + +#[test] +fn formats_known_instant() { + assert_eq!( + epoch("2026-11-18T10:05:00Z").map(iso).as_deref(), + Some("2026-11-18T10:05:00Z") + ); +} + +#[test] +fn offset_and_fractions() { + assert_eq!( + epoch("2026-11-18T10:04:40.123000+00:00"), + epoch("2026-11-18T10:04:40Z") + ); + assert!(epoch("2026-11-18T10:04:40Z").is_some()); +} + +#[test] +fn garbage_is_none() { + assert_eq!(epoch("nope"), None); +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..284d219 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 110 From f963238c40172570364e3ba669056c3c98070a6b Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Wed, 18 Nov 2026 07:40:10 -0500 Subject: [PATCH 02/14] feat(logic): mechanical filter rules Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- crates/logic/src/filter.rs | 48 +++++++++++++ crates/logic/src/lib.rs | 1 + crates/logic/tests/filter.rs | 133 +++++++++++++++++++++++++++++++++++ 3 files changed, 182 insertions(+) create mode 100644 crates/logic/src/filter.rs create mode 100644 crates/logic/tests/filter.rs diff --git a/crates/logic/src/filter.rs b/crates/logic/src/filter.rs new file mode 100644 index 0000000..6236eb8 --- /dev/null +++ b/crates/logic/src/filter.rs @@ -0,0 +1,48 @@ +//! Mechanical rule engine: decides which records are kept and which extra tags they get. + +use crate::config::{Keep, Rule, Then, When}; +use crate::record::NewRecord; + +/// Rules first to last, then `keep`. Built-in tags are already on the records. +pub fn apply(records: Vec, rules: &[Rule], keep: Keep) -> Vec { + records + .into_iter() + .filter_map(|record| run_rules(record, rules)) + .filter(|record| keep == Keep::All || !record.tags.is_empty()) + .collect() +} + +fn run_rules(mut record: NewRecord, rules: &[Rule]) -> Option { + for rule in rules { + if !matches(&rule.when, &record) { + continue; + } + match &rule.then { + Then::Drop => return None, + Then::Tag(tag) => { + if !record.tags.contains(tag) { + record.tags.push(tag.clone()); + } + } + } + } + Some(record) +} + +/// Empty lists are "no condition"; a non-empty list matches if any element does; +/// all non-empty conditions must match. +pub fn matches(when: &When, record: &NewRecord) -> bool { + let actor_is = + |a: &String| a.eq_ignore_ascii_case(&record.actor) || a.to_lowercase() == record.actor.to_lowercase(); + (when.kind.is_empty() || when.kind.contains(&record.kind)) + && (when.actor.is_empty() || when.actor.iter().any(actor_is)) + && (when.actor_not.is_empty() || !when.actor_not.iter().any(actor_is)) + && (when.reference.is_empty() || when.reference.contains(&record.reference)) + && (when.tag.is_empty() || when.tag.iter().any(|t| record.tags.contains(t))) + && (when.body_contains.is_empty() || { + let haystack = format!("{}\n{}", record.title, record.body).to_lowercase(); + when.body_contains + .iter() + .any(|needle| haystack.contains(&needle.to_lowercase())) + }) +} diff --git a/crates/logic/src/lib.rs b/crates/logic/src/lib.rs index 5bd8e8e..64363ac 100644 --- a/crates/logic/src/lib.rs +++ b/crates/logic/src/lib.rs @@ -1,6 +1,7 @@ //! Pure-Rust logic for mailroom: records, time helpers and configuration. pub mod config; +pub mod filter; pub mod record; pub mod time; diff --git a/crates/logic/tests/filter.rs b/crates/logic/tests/filter.rs new file mode 100644 index 0000000..7d011ef --- /dev/null +++ b/crates/logic/tests/filter.rs @@ -0,0 +1,133 @@ +use mailroom_logic::config::{Keep, Rule, Then, When}; +use mailroom_logic::filter::{apply, matches}; +use mailroom_logic::record::{Kind, NewRecord, Src}; + +fn rec(kind: Kind, actor: &str, body: &str, tags: &[&str]) -> NewRecord { + NewRecord { + src: Src::Discord, + kind, + id: "1".into(), + ts: "2026-01-01T00:00:00Z".into(), + actor: actor.into(), + reference: "chan".into(), + title: String::new(), + body: body.into(), + url: String::new(), + tags: tags.iter().map(|t| t.to_string()).collect(), + } +} + +fn tag_rule(when: When, tag: &str) -> Rule { + Rule { + when, + then: Then::Tag(tag.into()), + } +} + +#[test] +fn empty_when_matches_everything() { + assert!(matches(&When::default(), &rec(Kind::Message, "x", "y", &[]))); +} + +#[test] +fn conditions_are_anded_and_lists_are_ored() { + let rules = [Rule { + when: When { + kind: vec![Kind::Reaction], + actor_not: vec!["Lothrop".into()], + ..When::default() + }, + then: Then::Drop, + }]; + let input = vec![ + rec(Kind::Reaction, "Nyx", "", &[]), + rec(Kind::Reaction, "lothrop", "", &[]), + rec(Kind::Message, "Nyx", "", &[]), + ]; + let out = apply(input, &rules, Keep::All); + assert_eq!(out.len(), 2); + assert_eq!(out[0].actor, "lothrop"); + assert_eq!(out[1].kind, Kind::Message); +} + +#[test] +fn body_contains_is_case_insensitive_over_title_and_body() { + let mut r = rec(Kind::Message, "a", "nothing", &[]); + r.title = "KHARON is here".into(); + let when = When { + body_contains: vec!["kharon".into()], + ..When::default() + }; + assert!(matches(&when, &r)); + let when = When { + body_contains: vec!["absent".into(), "NOTHING".into()], + ..When::default() + }; + assert!(matches(&when, &r)); + let when = When { + body_contains: vec!["absent".into()], + ..When::default() + }; + assert!(!matches(&when, &r)); +} + +#[test] +fn tag_rule_adds_once_and_later_rule_sees_it() { + let rules = [ + tag_rule(When::default(), "a"), + tag_rule( + When { + tag: vec!["a".into()], + ..When::default() + }, + "b", + ), + tag_rule(When::default(), "a"), + ]; + let out = apply(vec![rec(Kind::Message, "x", "", &[])], &rules, Keep::All); + assert_eq!(out[0].tags, vec!["a", "b"]); +} + +#[test] +fn drop_stops_later_rules() { + let rules = [ + Rule { + when: When::default(), + then: Then::Drop, + }, + tag_rule(When::default(), "a"), + ]; + let out = apply(vec![rec(Kind::Message, "x", "", &[])], &rules, Keep::All); + assert!(out.is_empty()); +} + +#[test] +fn keep_tagged_removes_untagged_after_rules() { + let rules = [tag_rule( + When { + actor: vec!["NYX".into()], + ..When::default() + }, + "hit", + )]; + let input = vec![ + rec(Kind::Message, "other", "", &[]), + rec(Kind::Message, "nyx", "", &[]), + rec(Kind::Message, "pre", "", &["builtin"]), + ]; + let out = apply(input, &rules, Keep::Tagged); + assert_eq!(out.len(), 2); + assert_eq!(out[0].actor, "nyx"); + assert_eq!(out[1].actor, "pre"); +} + +#[test] +fn order_is_preserved() { + let input: Vec<_> = ["a", "b", "c"] + .iter() + .map(|a| rec(Kind::Message, a, "", &[])) + .collect(); + let out = apply(input, &[], Keep::All); + let actors: Vec<_> = out.iter().map(|r| r.actor.as_str()).collect(); + assert_eq!(actors, ["a", "b", "c"]); +} From 0591437be0a7b85cc162bb7d38da85bf237e8310 Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Wed, 18 Nov 2026 07:40:13 -0500 Subject: [PATCH 03/14] refactor(logic): simplify actor comparison Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- crates/logic/src/filter.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/logic/src/filter.rs b/crates/logic/src/filter.rs index 6236eb8..afba700 100644 --- a/crates/logic/src/filter.rs +++ b/crates/logic/src/filter.rs @@ -32,8 +32,8 @@ fn run_rules(mut record: NewRecord, rules: &[Rule]) -> Option { /// Empty lists are "no condition"; a non-empty list matches if any element does; /// all non-empty conditions must match. pub fn matches(when: &When, record: &NewRecord) -> bool { - let actor_is = - |a: &String| a.eq_ignore_ascii_case(&record.actor) || a.to_lowercase() == record.actor.to_lowercase(); + let actor = record.actor.to_lowercase(); + let actor_is = |a: &String| a.to_lowercase() == actor; (when.kind.is_empty() || when.kind.contains(&record.kind)) && (when.actor.is_empty() || when.actor.iter().any(actor_is)) && (when.actor_not.is_empty() || !when.actor_not.iter().any(actor_is)) From 6d8b23c93d434cae82304d494f19b0ff49bbe04d Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Wed, 18 Nov 2026 07:42:28 -0500 Subject: [PATCH 04/14] feat(logic): feed trait and Discord channel poller Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- crates/logic/src/discord.rs | 389 ++++++++++++++++++++++++++++++ crates/logic/src/feed.rs | 75 ++++++ crates/logic/src/lib.rs | 2 + crates/logic/tests/discord.rs | 309 ++++++++++++++++++++++++ crates/logic/tests/support/mod.rs | 63 +++++ 5 files changed, 838 insertions(+) create mode 100644 crates/logic/src/discord.rs create mode 100644 crates/logic/src/feed.rs create mode 100644 crates/logic/tests/discord.rs create mode 100644 crates/logic/tests/support/mod.rs diff --git a/crates/logic/src/discord.rs b/crates/logic/src/discord.rs new file mode 100644 index 0000000..79bb623 --- /dev/null +++ b/crates/logic/src/discord.rs @@ -0,0 +1,389 @@ +//! Polls one Discord channel: new messages and new reactions since the previous state. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::config::DiscordSource; +use crate::feed::{get_json, FeedClient, Identity, Poll, PollError}; +use crate::record::{truncate, Kind, NewRecord, Src}; + +const PAGE: usize = 50; +const MAX_PAGES: usize = 5; +const PAGE_LIMIT: &str = "50"; +const BODY_MAX: usize = 2000; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DiscordState { + pub channel_name: String, + pub guild_id: String, + pub watermark: u64, + /// message id -> emoji key -> reactor user ids + pub reactions: BTreeMap>>, +} + +#[derive(Deserialize)] +struct Channel { + #[serde(default)] + name: String, + #[serde(default)] + guild_id: Option, +} + +#[derive(Deserialize)] +struct Message { + id: String, + #[serde(default, rename = "type")] + kind: u32, + #[serde(default)] + timestamp: String, + #[serde(default)] + content: String, + #[serde(default)] + author: User, + #[serde(default)] + mentions: Vec, + #[serde(default)] + referenced_message: Option, + #[serde(default)] + attachments: Vec, + #[serde(default)] + embeds: Vec, + #[serde(default)] + reactions: Vec, +} + +#[derive(Deserialize, Default)] +struct User { + #[serde(default)] + id: String, + #[serde(default)] + username: String, + #[serde(default)] + global_name: Option, +} + +impl User { + fn display(&self) -> String { + match self.global_name.as_deref() { + Some(g) if !g.is_empty() => g.to_string(), + _ => self.username.clone(), + } + } +} + +#[derive(Deserialize, Default)] +struct UserId { + #[serde(default)] + id: String, +} + +#[derive(Deserialize)] +struct Referenced { + #[serde(default)] + author: UserId, +} + +#[derive(Deserialize)] +struct Attachment {} + +#[derive(Deserialize)] +struct Embed { + #[serde(default)] + title: Option, +} + +#[derive(Deserialize)] +struct ReactionSummary { + #[serde(default)] + count: usize, + emoji: Emoji, +} + +#[derive(Deserialize)] +struct Emoji { + #[serde(default)] + id: Option, + #[serde(default)] + name: Option, +} + +impl Emoji { + /// The unicode character, or `name:id` for a custom emoji. + fn key(&self) -> String { + let name = self.name.as_deref().unwrap_or(""); + match &self.id { + Some(id) => format!("{name}:{id}"), + None => name.to_string(), + } + } + + /// The unicode character, or `:name:` for a custom emoji. + fn body(&self) -> String { + let name = self.name.as_deref().unwrap_or(""); + match &self.id { + Some(_) => format!(":{name}:"), + None => name.to_string(), + } + } +} + +/// An emoji on a page-1 message, as last seen. +struct Seen { + key: String, + body: String, + count: usize, +} + +fn parse_id(id: &str) -> Result { + id.parse() + .map_err(|_| PollError(format!("unparsable Discord id {id:?}"))) +} + +/// Percent-encodes every byte outside the unreserved set. +fn encode(key: &str) -> String { + let mut out = String::new(); + for b in key.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +async fn fetch_reactors( + feed: &impl FeedClient, + channel_id: &str, + message_id: &str, + key: &str, +) -> Result, PollError> { + let path = format!( + "/channels/{channel_id}/messages/{message_id}/reactions/{}", + encode(key) + ); + Ok(get_json(feed, &path, &[("limit", "100")]).await?) +} + +fn jump_url(guild_id: &str, channel_id: &str, message_id: &str) -> String { + format!("https://discord.com/channels/{guild_id}/{channel_id}/{message_id}") +} + +pub async fn poll_channel( + feed: &impl FeedClient, + me: &Identity, + channel_id: &str, + opts: &DiscordSource, + prev: Option, + now: &str, +) -> Result, PollError> { + let messages_path = format!("/channels/{channel_id}/messages"); + + let Some(prev) = prev else { + let channel: Channel = get_json(feed, &format!("/channels/{channel_id}"), &[]).await?; + let page: Vec = get_json(feed, &messages_path, &[("limit", PAGE_LIMIT)]).await?; + let mut watermark = 0; + for m in &page { + watermark = watermark.max(parse_id(&m.id)?); + } + let mut reactions = BTreeMap::new(); + if opts.reactions { + for m in &page { + for r in &m.reactions { + let key = r.emoji.key(); + let users = fetch_reactors(feed, channel_id, &m.id, &key).await?; + let ids = users.into_iter().map(|u| u.id).collect(); + reactions + .entry(m.id.clone()) + .or_insert_with(BTreeMap::new) + .insert(key, ids); + } + } + } + return Ok(Poll { + records: Vec::new(), + state: DiscordState { + channel_name: channel.name, + guild_id: channel.guild_id.unwrap_or_else(|| "@me".to_string()), + watermark, + reactions, + }, + }); + }; + + // Page 1, then older pages while every message so far has been new. + let first: Vec = get_json(feed, &messages_path, &[("limit", PAGE_LIMIT)]).await?; + let mut ids = Vec::with_capacity(first.len()); + for m in &first { + ids.push(parse_id(&m.id)?); + } + let mut new: Vec<(u64, Message)> = Vec::new(); + let mut seen_max = ids.iter().copied().max().unwrap_or(0); + let mut full_and_new = first.len() == PAGE && ids.iter().all(|&i| i > prev.watermark); + let mut lowest = ids.iter().copied().min(); + let mut pages = 1; + // Page 1's messages (new and old) are the ones whose reactions are tracked. + let page_one_info: Vec<(String, Vec)> = first + .iter() + .map(|m| { + ( + m.id.clone(), + m.reactions + .iter() + .map(|r| Seen { + key: r.emoji.key(), + body: r.emoji.body(), + count: r.count, + }) + .collect(), + ) + }) + .collect(); + for (id, m) in ids.iter().copied().zip(first) { + if id > prev.watermark { + new.push((id, m)); + } + } + + let mut gap = false; + while full_and_new { + if pages == MAX_PAGES { + gap = true; + break; + } + let before = lowest.unwrap_or(0).to_string(); + let page: Vec = get_json( + feed, + &messages_path, + &[("limit", PAGE_LIMIT), ("before", &before)], + ) + .await?; + pages += 1; + let mut page_ids = Vec::with_capacity(page.len()); + for m in &page { + page_ids.push(parse_id(&m.id)?); + } + seen_max = seen_max.max(page_ids.iter().copied().max().unwrap_or(0)); + full_and_new = page.len() == PAGE && page_ids.iter().all(|&i| i > prev.watermark); + if let Some(l) = page_ids.iter().copied().min() { + lowest = Some(lowest.map_or(l, |c| c.min(l))); + } + for (id, m) in page_ids.into_iter().zip(page) { + if id > prev.watermark { + new.push((id, m)); + } + } + } + new.sort_by_key(|(id, _)| *id); + + let guild_id = &prev.guild_id; + let reference = format!("#{}", prev.channel_name); + let mut records = Vec::new(); + + if gap { + let newest = new.last().map(|(id, _)| *id).unwrap_or(0); + let oldest = lowest.unwrap_or(0); + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Gap, + id: format!("dc:gap:{channel_id}:{newest}"), + ts: now.to_string(), + actor: String::new(), + reference: reference.clone(), + title: "messages may have been skipped".to_string(), + body: String::new(), + url: jump_url(guild_id, channel_id, &oldest.to_string()), + tags: Vec::new(), + }); + } + + for (id, m) in &new { + if m.kind != 0 && m.kind != 19 { + continue; + } + if opts.skip_self && m.author.id == me.id { + continue; + } + let mut body = truncate(&m.content, BODY_MAX, ""); + if !m.attachments.is_empty() { + body.push_str(&format!("\n[{} attachment(s)]", m.attachments.len())); + } + for title in m.embeds.iter().filter_map(|e| e.title.as_deref()) { + body.push_str(&format!("\n[embed] {title}")); + } + let mut tags = Vec::new(); + if m.mentions.iter().any(|u| u.id == me.id) { + tags.push("routed:mention".to_string()); + } + if m.referenced_message + .as_ref() + .is_some_and(|r| r.author.id == me.id) + { + tags.push("routed:reply".to_string()); + } + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Message, + id: format!("dc:{id}"), + ts: m.timestamp.clone(), + actor: m.author.display(), + reference: reference.clone(), + title: String::new(), + body, + url: jump_url(guild_id, channel_id, &m.id), + tags, + }); + } + + let mut reactions: BTreeMap>> = BTreeMap::new(); + if opts.reactions { + for (message_id, emojis) in &page_one_info { + for Seen { key, body, count } in emojis { + let stored = prev + .reactions + .get(message_id) + .and_then(|m| m.get(key)) + .cloned() + .unwrap_or_default(); + let list = if *count > stored.len() { + let users = fetch_reactors(feed, channel_id, message_id, key).await?; + for u in &users { + if stored.contains(&u.id) || (opts.skip_self && u.id == me.id) { + continue; + } + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Reaction, + id: format!("dc:react:{message_id}:{key}:{}", u.id), + ts: now.to_string(), + actor: u.display(), + reference: reference.clone(), + title: String::new(), + body: body.clone(), + url: jump_url(guild_id, channel_id, message_id), + tags: Vec::new(), + }); + } + users.into_iter().map(|u| u.id).collect() + } else { + stored + }; + reactions + .entry(message_id.clone()) + .or_default() + .insert(key.clone(), list); + } + } + } + + Ok(Poll { + records, + state: DiscordState { + channel_name: prev.channel_name.clone(), + guild_id: prev.guild_id.clone(), + watermark: prev.watermark.max(seen_max), + reactions, + }, + }) +} diff --git a/crates/logic/src/feed.rs b/crates/logic/src/feed.rs new file mode 100644 index 0000000..9ec3505 --- /dev/null +++ b/crates/logic/src/feed.rs @@ -0,0 +1,75 @@ +//! The upstream-read abstraction shared by the pollers. + +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::record::NewRecord; + +/// Who the bot is on the upstream service. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Identity { + pub id: String, + pub login: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FeedError { + Status { status: u16, message: String }, + Transport(String), + Decode(String), +} + +impl fmt::Display for FeedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FeedError::Status { status, message } => write!(f, "upstream status {status}: {message}"), + FeedError::Transport(m) => write!(f, "transport error: {m}"), + FeedError::Decode(m) => write!(f, "decode error: {m}"), + } + } +} + +impl std::error::Error for FeedError {} + +#[allow(async_fn_in_trait)] +pub trait FeedClient { + /// GET an upstream API path (e.g. "/channels/1/messages"); returns the response body text. + async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result; +} + +/// GETs `path` and deserializes the body; a body that is not valid JSON for `T` is a +/// `FeedError::Decode` naming the path. +pub async fn get_json( + feed: &impl FeedClient, + path: &str, + query: &[(&str, &str)], +) -> Result { + let body = feed.get(path, query).await?; + serde_json::from_str(&body).map_err(|e| FeedError::Decode(format!("{path}: {e}"))) +} + +/// The result of one poll: records to append and the state to persist (only on `Ok`). +pub struct Poll { + pub records: Vec, + pub state: S, +} + +#[derive(Debug)] +pub struct PollError(pub String); + +impl fmt::Display for PollError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for PollError {} + +impl From for PollError { + fn from(e: FeedError) -> Self { + PollError(e.to_string()) + } +} diff --git a/crates/logic/src/lib.rs b/crates/logic/src/lib.rs index 64363ac..c4fa78c 100644 --- a/crates/logic/src/lib.rs +++ b/crates/logic/src/lib.rs @@ -1,6 +1,8 @@ //! Pure-Rust logic for mailroom: records, time helpers and configuration. pub mod config; +pub mod discord; +pub mod feed; pub mod filter; pub mod record; pub mod time; diff --git a/crates/logic/tests/discord.rs b/crates/logic/tests/discord.rs new file mode 100644 index 0000000..4fae5d1 --- /dev/null +++ b/crates/logic/tests/discord.rs @@ -0,0 +1,309 @@ +mod support; + +use mailroom_logic::config::DiscordSource; +use mailroom_logic::discord::{poll_channel, DiscordState}; +use mailroom_logic::feed::{Identity, Poll}; +use mailroom_logic::record::Kind; +use pollster::block_on; +use std::collections::BTreeMap; +use support::FakeFeed; + +const C: &str = "555"; +const G: &str = "777"; +const NOW: &str = "2026-11-18T12:00:00Z"; +const MSGS: &str = "/channels/555/messages?limit=50"; + +fn me() -> Identity { + Identity { + id: "42".into(), + login: "bot".into(), + name: "Bot".into(), + } +} + +fn opts(reactions: bool, skip_self: bool) -> DiscordSource { + let json = + format!(r#"{{"broker":"B","channels":["{C}"],"reactions":{reactions},"skip_self":{skip_self}}}"#); + serde_json::from_str(&json).unwrap() +} + +fn state(watermark: u64) -> DiscordState { + DiscordState { + channel_name: "general".into(), + guild_id: G.into(), + watermark, + reactions: BTreeMap::new(), + } +} + +fn msg(id: &str, author: &str, content: &str) -> String { + format!( + r#"{{"id":"{id}","type":0,"timestamp":"2026-11-18T11:00:00+00:00","content":"{content}","author":{{"id":"{author}","username":"user{author}","global_name":null}},"mentions":[],"attachments":[],"embeds":[]}}"# + ) +} + +fn page(msgs: &[String]) -> String { + format!("[{}]", msgs.join(",")) +} + +fn poll(feed: &FakeFeed, o: &DiscordSource, prev: Option) -> Poll { + block_on(poll_channel(feed, &me(), C, o, prev, NOW)).unwrap() +} + +fn feed_with(messages_json: &str) -> FakeFeed { + let f = FakeFeed::new(); + f.on(MSGS, messages_json); + f +} + +#[test] +fn first_contact_records_position_and_emits_nothing() { + let f = feed_with(&page(&[msg("30", "1", "b"), msg("20", "1", "a")])); + f.on("/channels/555", r#"{"name":"general","guild_id":"777"}"#); + let p = poll(&f, &opts(true, true), None); + assert!(p.records.is_empty()); + assert_eq!(p.state.watermark, 30); + assert_eq!(p.state.channel_name, "general"); + assert_eq!(p.state.guild_id, "777"); +} + +#[test] +fn first_contact_on_empty_channel_sets_watermark_zero() { + let f = feed_with("[]"); + f.on("/channels/555", r#"{"name":"general"}"#); + let p = poll(&f, &opts(true, true), None); + assert_eq!(p.state.watermark, 0); + assert_eq!(p.state.guild_id, "@me"); +} + +#[test] +fn delta_emits_only_messages_above_watermark_oldest_first() { + let f = feed_with(&page(&[ + msg("30", "1", "c"), + msg("20", "1", "b"), + msg("10", "1", "a"), + ])); + let p = poll(&f, &opts(true, true), Some(state(10))); + let ids: Vec<_> = p.records.iter().map(|r| r.id.as_str()).collect(); + assert_eq!(ids, ["dc:20", "dc:30"]); + assert_eq!(p.state.watermark, 30); + assert_eq!(p.records[0].reference, "#general"); + assert_eq!(p.records[0].actor, "user1"); + assert_eq!(p.records[0].kind, Kind::Message); +} + +#[test] +fn snowflakes_compare_numerically() { + let f = feed_with(&page(&[msg("10000", "1", "x"), msg("999", "1", "y")])); + let p = poll(&f, &opts(true, true), Some(state(1000))); + assert_eq!(p.records.len(), 1); + assert_eq!(p.records[0].id, "dc:10000"); +} + +#[test] +fn own_messages_are_skipped_but_advance_watermark() { + let f = feed_with(&page(&[msg("30", "42", "mine"), msg("20", "1", "theirs")])); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records.len(), 1); + assert_eq!(p.state.watermark, 30); +} + +#[test] +fn skip_self_false_keeps_own_messages() { + let f = feed_with(&page(&[msg("30", "42", "mine")])); + let p = poll(&f, &opts(true, false), Some(state(10))); + assert_eq!(p.records.len(), 1); +} + +#[test] +fn mention_and_reply_tags() { + let m = r#"[{"id":"30","type":19,"timestamp":"t","content":"yo","author":{"id":"1","username":"u","global_name":"Una"},"mentions":[{"id":"42"}],"referenced_message":{"author":{"id":"42"}}}]"#; + let f = feed_with(m); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records[0].tags, ["routed:mention", "routed:reply"]); + assert_eq!(p.records[0].actor, "Una"); +} + +#[test] +fn empty_content_still_yields_record_and_mention_tag() { + let m = r#"[{"id":"30","type":0,"timestamp":"t","content":"","author":{"id":"1","username":"u"},"mentions":[{"id":"42"}]}]"#; + let f = feed_with(m); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records[0].body, ""); + assert_eq!(p.records[0].tags, ["routed:mention"]); +} + +#[test] +fn body_truncates_at_2000_chars_on_char_boundary() { + let long = "\u{1F600}".repeat(2001); + let f = feed_with(&page(&[msg("30", "1", &long)])); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records[0].body.chars().count(), 2000); +} + +#[test] +fn attachments_and_embed_titles_are_noted() { + let m = r#"[{"id":"30","type":0,"timestamp":"t","content":"hi","author":{"id":"1","username":"u"},"attachments":[{},{}],"embeds":[{"title":"Title"},{}]}]"#; + let f = feed_with(m); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records[0].body, "hi\n[2 attachment(s)]\n[embed] Title"); +} + +#[test] +fn system_messages_are_ignored() { + let m = r#"[{"id":"30","type":7,"timestamp":"t","content":"","author":{"id":"1","username":"u"}}]"#; + let f = feed_with(m); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert!(p.records.is_empty()); + assert_eq!(p.state.watermark, 30); +} + +fn run_of(from: u64, count: u64) -> Vec { + (0..count) + .map(|i| msg(&(from + count - 1 - i).to_string(), "1", "m")) + .collect() +} + +#[test] +fn full_page_of_new_messages_pages_back() { + // page 1: ids 1050..=1101 minus -> 50 messages 1051..=1100; page 2: 3 messages + let f = feed_with(&page(&run_of(1051, 50))); + f.on( + "/channels/555/messages?limit=50&before=1051", + &page(&run_of(1048, 3)), + ); + let p = poll(&f, &opts(true, true), Some(state(1000))); + assert_eq!(p.records.len(), 53); + assert_eq!(p.records[0].id, "dc:1048"); + assert!(f + .calls() + .contains(&"/channels/555/messages?limit=50&before=1051".to_string())); +} + +#[test] +fn five_full_pages_emits_gap_record() { + let f = feed_with(&page(&run_of(1201, 50))); + for (before, from) in [(1201, 1151), (1151, 1101), (1101, 1051), (1051, 1001)] { + f.on( + &format!("/channels/555/messages?limit=50&before={before}"), + &page(&run_of(from, 50)), + ); + } + let p = poll(&f, &opts(true, true), Some(state(1000))); + let gaps: Vec<_> = p.records.iter().filter(|r| r.kind == Kind::Gap).collect(); + assert_eq!(gaps.len(), 1); + assert_eq!(gaps[0].id, "dc:gap:555:1250"); + assert_eq!(gaps[0].title, "messages may have been skipped"); + assert_eq!(gaps[0].url, "https://discord.com/channels/777/555/1001"); + assert_eq!(p.records.iter().filter(|r| r.kind == Kind::Message).count(), 250); + assert_eq!(p.state.watermark, 1250); +} + +fn with_reaction(emoji: &str, count: u32) -> String { + format!( + r#"[{{"id":"30","type":0,"timestamp":"t","content":"x","author":{{"id":"1","username":"u"}},"reactions":[{{"count":{count},"emoji":{emoji}}}]}}]"# + ) +} + +const CHECK: &str = r#"{"id":null,"name":"✅"}"#; +const CHECK_PATH: &str = "/channels/555/messages/30/reactions/%E2%9C%85?limit=100"; + +fn state_with_reactors(key: &str, ids: &[&str]) -> DiscordState { + let mut s = state(30); + s.reactions.insert( + "30".into(), + BTreeMap::from([(key.to_string(), ids.iter().map(|i| i.to_string()).collect())]), + ); + s +} + +#[test] +fn new_reaction_yields_one_record_per_new_reactor() { + let f = feed_with(&with_reaction(CHECK, 2)); + f.on( + CHECK_PATH, + r#"[{"id":"1","username":"a"},{"id":"2","username":"b","global_name":"Bee"}]"#, + ); + let p = poll(&f, &opts(true, true), Some(state_with_reactors("✅", &["1"]))); + assert_eq!(p.records.len(), 1); + let r = &p.records[0]; + assert_eq!(r.kind, Kind::Reaction); + assert_eq!(r.id, "dc:react:30:✅:2"); + assert_eq!(r.body, "✅"); + assert_eq!(r.actor, "Bee"); + assert_eq!(r.ts, NOW); + assert_eq!(r.url, "https://discord.com/channels/777/555/30"); + assert_eq!(p.state.reactions["30"]["✅"], ["1", "2"]); +} + +#[test] +fn first_contact_snapshots_existing_reactors() { + let f = feed_with(&with_reaction(CHECK, 1)); + f.on("/channels/555", r#"{"name":"general","guild_id":"777"}"#); + f.on(CHECK_PATH, r#"[{"id":"1","username":"a"}]"#); + let p = poll(&f, &opts(true, true), None); + assert!(p.records.is_empty()); + assert_eq!(p.state.reactions["30"]["✅"], ["1"]); + + let f2 = feed_with(&with_reaction(CHECK, 2)); + f2.on( + CHECK_PATH, + r#"[{"id":"1","username":"a"},{"id":"3","username":"c"}]"#, + ); + let p2 = poll(&f2, &opts(true, true), Some(p.state)); + assert_eq!(p2.records.len(), 1); + assert_eq!(p2.records[0].id, "dc:react:30:✅:3"); +} + +#[test] +fn custom_emoji_key_and_body() { + let f = feed_with(&with_reaction(r#"{"id":"123","name":"party"}"#, 1)); + f.on( + "/channels/555/messages/30/reactions/party%3A123?limit=100", + r#"[{"id":"1","username":"a"}]"#, + ); + let p = poll(&f, &opts(true, true), Some(state(30))); + assert_eq!(p.records[0].id, "dc:react:30:party:123:1"); + assert_eq!(p.records[0].body, ":party:"); +} + +#[test] +fn reactions_false_makes_no_reaction_calls() { + let f = feed_with(&with_reaction(CHECK, 3)); + let p = poll(&f, &opts(false, true), Some(state(10))); + assert_eq!(p.records.len(), 1); + assert!(f.calls().iter().all(|c| !c.contains("/reactions/"))); +} + +#[test] +fn own_reaction_is_skipped() { + let f = feed_with(&with_reaction(CHECK, 2)); + f.on( + CHECK_PATH, + r#"[{"id":"42","username":"bot"},{"id":"2","username":"b"}]"#, + ); + let p = poll(&f, &opts(true, true), Some(state(30))); + assert_eq!(p.records.len(), 1); + assert_eq!(p.records[0].id, "dc:react:30:✅:2"); +} + +#[test] +fn upstream_error_returns_err() { + let f = FakeFeed::new(); + f.fail(MSGS, 429); + assert!(block_on(poll_channel(&f, &me(), C, &opts(true, true), Some(state(1)), NOW)).is_err()); +} + +#[test] +fn non_json_body_returns_err() { + let f = feed_with(""); + let r = block_on(poll_channel(&f, &me(), C, &opts(true, true), Some(state(1)), NOW)); + assert!(r.is_err()); +} + +#[test] +fn jump_url_shape() { + let f = feed_with(&page(&[msg("30", "1", "x")])); + let p = poll(&f, &opts(true, true), Some(state(10))); + assert_eq!(p.records[0].url, "https://discord.com/channels/777/555/30"); +} diff --git a/crates/logic/tests/support/mod.rs b/crates/logic/tests/support/mod.rs new file mode 100644 index 0000000..659dece --- /dev/null +++ b/crates/logic/tests/support/mod.rs @@ -0,0 +1,63 @@ +//! A fake `FeedClient` that knows nothing about any upstream service. +#![allow(dead_code)] + +use std::cell::RefCell; +use std::collections::BTreeMap; + +use mailroom_logic::feed::{FeedClient, FeedError}; + +enum Reply { + Body(String), + Status(u16), +} + +#[derive(Default)] +pub struct FakeFeed { + replies: RefCell>, + calls: RefCell>, +} + +impl FakeFeed { + pub fn new() -> Self { + Self::default() + } + + /// Registers a body for `path?k=v&k=v` (or just `path`). + pub fn on(&self, path_and_query: &str, body: &str) { + self.replies + .borrow_mut() + .insert(path_and_query.to_string(), Reply::Body(body.to_string())); + } + + pub fn fail(&self, path_and_query: &str, status: u16) { + self.replies + .borrow_mut() + .insert(path_and_query.to_string(), Reply::Status(status)); + } + + pub fn calls(&self) -> Vec { + self.calls.borrow().clone() + } +} + +impl FeedClient for FakeFeed { + async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result { + let mut key = path.to_string(); + for (i, (k, v)) in query.iter().enumerate() { + key.push(if i == 0 { '?' } else { '&' }); + key.push_str(&format!("{k}={v}")); + } + self.calls.borrow_mut().push(key.clone()); + match self.replies.borrow().get(&key) { + Some(Reply::Body(b)) => Ok(b.clone()), + Some(Reply::Status(status)) => Err(FeedError::Status { + status: *status, + message: format!("fake failure for {key}"), + }), + None => Err(FeedError::Status { + status: 404, + message: format!("no fake registered for {key}"), + }), + } + } +} From 0c1d2cbc159b09143b55ffb8ae25c285887ae9c9 Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Wed, 18 Nov 2026 07:45:07 -0500 Subject: [PATCH 05/14] feat(logic): GitHub repo poller Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- crates/logic/src/github.rs | 465 ++++++++++++++++++++++++++++++++++ crates/logic/src/lib.rs | 1 + crates/logic/tests/github.rs | 469 +++++++++++++++++++++++++++++++++++ 3 files changed, 935 insertions(+) create mode 100644 crates/logic/src/github.rs create mode 100644 crates/logic/tests/github.rs diff --git a/crates/logic/src/github.rs b/crates/logic/src/github.rs new file mode 100644 index 0000000..b8038fd --- /dev/null +++ b/crates/logic/src/github.rs @@ -0,0 +1,465 @@ +//! Polls one GitHub repository: new issues, pull requests, comments, reviews and events. + +use serde::{Deserialize, Serialize}; + +use crate::config::GithubSource; +use crate::feed::{get_json, FeedClient, Identity, Poll, PollError}; +use crate::record::{truncate, Kind, NewRecord, Src}; +use crate::time::{epoch, iso}; + +const PER_PAGE: &str = "50"; +const BODY_MAX: usize = 600; +const BODY_SUFFIX: &str = " [...]"; +/// `last_check_at` is stored this many seconds early so nothing falls between polls. +const OVERLAP_SECS: i64 = 60; +const EVENT_KINDS: [&str; 6] = [ + "assigned", + "labeled", + "review_requested", + "closed", + "merged", + "reopened", +]; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GithubState { + pub last_issue_number: u64, + pub last_pr_number: u64, + pub last_issue_comment_id: u64, + pub last_review_comment_id: u64, + pub last_event_id: u64, + /// ISO time of the last successful poll, stored 60 s early. + pub last_check_at: String, +} + +#[derive(Deserialize, Default)] +struct User { + #[serde(default)] + login: String, +} + +#[derive(Deserialize)] +struct Label { + #[serde(default)] + name: String, +} + +/// An entry of `/issues` or `/pulls`; the fields not present on one are defaulted. +#[derive(Deserialize)] +struct Item { + number: u64, + #[serde(default)] + title: String, + #[serde(default)] + body: Option, + #[serde(default)] + html_url: String, + #[serde(default)] + created_at: String, + #[serde(default)] + updated_at: String, + #[serde(default)] + user: User, + #[serde(default)] + assignees: Vec, + #[serde(default)] + labels: Vec