Skip to main content

orch/channels/
routing.rs

1//! Channel-to-project routing map.
2//!
3//! Built at engine startup from per-project `.orch.yml` configs.
4//! Provides reverse lookup: (channel, topic/channel_id) → repo.
5
6use std::collections::HashMap;
7
8/// Per-project channel configuration, read from `.orch.yml`.
9#[derive(Debug, Clone, Default)]
10pub struct ProjectChannelConfig {
11    pub telegram_topic_id: Option<String>,
12    pub discord_channel_id: Option<String>,
13}
14
15/// Global channel configuration from `~/.orch/config.yml`.
16#[derive(Debug, Clone, Default)]
17pub struct GlobalChannelConfig {
18    pub telegram_general_topic_id: Option<String>,
19    pub discord_general_channel_id: Option<String>,
20    /// Telegram topic ID for the control session (from `control.channels.telegram.topic_id`).
21    pub control_telegram_topic_id: Option<String>,
22    /// Discord channel ID for the control session (from `control.channels.discord.channel_id`).
23    pub control_discord_channel_id: Option<String>,
24}
25
26/// Maps channel targets to projects and vice versa.
27#[derive(Debug)]
28pub struct ChannelRouter {
29    /// (channel_name, topic_or_channel_id) → repo
30    target_to_repo: HashMap<(String, String), String>,
31    /// repo → { channel_name: topic_or_channel_id }
32    repo_to_targets: HashMap<String, HashMap<String, String>>,
33    /// General channel IDs per channel type
34    general: HashMap<String, String>,
35    /// Control session channel IDs per channel type
36    control: HashMap<String, String>,
37    /// All configured project repos
38    project_list: Vec<String>,
39}
40
41impl ChannelRouter {
42    /// Build router from global config + per-project configs.
43    pub fn new(global: &GlobalChannelConfig, projects: &[(String, ProjectChannelConfig)]) -> Self {
44        let mut target_to_repo = HashMap::new();
45        let mut repo_to_targets: HashMap<String, HashMap<String, String>> = HashMap::new();
46        let mut general = HashMap::new();
47        let mut control = HashMap::new();
48        let mut project_list = Vec::new();
49
50        if let Some(ref id) = global.telegram_general_topic_id {
51            general.insert("telegram".to_string(), id.clone());
52        }
53        if let Some(ref id) = global.discord_general_channel_id {
54            general.insert("discord".to_string(), id.clone());
55        }
56        if let Some(ref id) = global.control_telegram_topic_id {
57            control.insert("telegram".to_string(), id.clone());
58        }
59        if let Some(ref id) = global.control_discord_channel_id {
60            control.insert("discord".to_string(), id.clone());
61        }
62
63        for (repo, config) in projects {
64            project_list.push(repo.clone());
65            let mut targets = HashMap::new();
66
67            if let Some(ref topic_id) = config.telegram_topic_id {
68                target_to_repo.insert(("telegram".to_string(), topic_id.clone()), repo.clone());
69                targets.insert("telegram".to_string(), topic_id.clone());
70            }
71
72            if let Some(ref channel_id) = config.discord_channel_id {
73                target_to_repo.insert(("discord".to_string(), channel_id.clone()), repo.clone());
74                targets.insert("discord".to_string(), channel_id.clone());
75            }
76
77            repo_to_targets.insert(repo.clone(), targets);
78        }
79
80        Self {
81            target_to_repo,
82            repo_to_targets,
83            general,
84            control,
85            project_list,
86        }
87    }
88
89    /// Resolve which project a channel message belongs to.
90    /// Returns None if the target isn't mapped (e.g., General channel).
91    pub fn resolve_project(&self, channel: &str, topic_or_channel_id: &str) -> Option<&str> {
92        self.target_to_repo
93            .get(&(channel.to_string(), topic_or_channel_id.to_string()))
94            .map(String::as_str)
95    }
96
97    /// Check if a target is the General channel.
98    pub fn is_general(&self, channel: &str, topic_or_channel_id: &str) -> bool {
99        self.general
100            .get(channel)
101            .is_some_and(|id| id == topic_or_channel_id)
102    }
103
104    /// Check if a target is the configured control session channel.
105    pub fn is_control_channel(&self, channel: &str, topic_or_channel_id: &str) -> bool {
106        self.control
107            .get(channel)
108            .is_some_and(|id| id == topic_or_channel_id)
109    }
110
111    /// Get the target (topic/channel ID) for a project on a given channel.
112    pub fn target_for_project(&self, repo: &str, channel: &str) -> Option<&str> {
113        self.repo_to_targets
114            .get(repo)
115            .and_then(|targets| targets.get(channel))
116            .map(String::as_str)
117    }
118
119    /// Every Discord channel ID the router knows: project, general and control
120    pub fn discord_channel_ids(&self) -> Vec<String> {
121        self.channel_ids("discord")
122    }
123
124    /// Every Slack channel ID the router knows: project, general and control
125    pub fn slack_channel_ids(&self) -> Vec<String> {
126        self.channel_ids("slack")
127    }
128
129    fn channel_ids(&self, platform: &str) -> Vec<String> {
130        let mapped = self
131            .target_to_repo
132            .keys()
133            .filter(|(channel, _)| channel == platform)
134            .map(|(_, id)| id.clone());
135        mapped
136            .chain(self.general.get(platform).cloned())
137            .chain(self.control.get(platform).cloned())
138            .collect()
139    }
140
141    /// List all configured project repos.
142    pub fn projects(&self) -> &[String] {
143        &self.project_list
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    fn test_router() -> ChannelRouter {
152        let global = GlobalChannelConfig {
153            telegram_general_topic_id: Some("1".to_string()),
154            discord_general_channel_id: Some("9999".to_string()),
155            ..Default::default()
156        };
157        let projects = vec![
158            (
159                "owner/orch".to_string(),
160                ProjectChannelConfig {
161                    telegram_topic_id: Some("42".to_string()),
162                    discord_channel_id: Some("1111".to_string()),
163                },
164            ),
165            (
166                "owner/bean".to_string(),
167                ProjectChannelConfig {
168                    telegram_topic_id: Some("87".to_string()),
169                    discord_channel_id: Some("2222".to_string()),
170                },
171            ),
172        ];
173        ChannelRouter::new(&global, &projects)
174    }
175
176    #[test]
177    fn resolve_telegram_topic_to_project() {
178        let router = test_router();
179        assert_eq!(router.resolve_project("telegram", "42"), Some("owner/orch"));
180        assert_eq!(router.resolve_project("telegram", "87"), Some("owner/bean"));
181        assert_eq!(router.resolve_project("telegram", "99"), None);
182    }
183
184    #[test]
185    fn resolve_discord_channel_to_project() {
186        let router = test_router();
187        assert_eq!(
188            router.resolve_project("discord", "1111"),
189            Some("owner/orch")
190        );
191        assert_eq!(
192            router.resolve_project("discord", "2222"),
193            Some("owner/bean")
194        );
195    }
196
197    #[test]
198    fn is_general_channel() {
199        let router = test_router();
200        assert!(router.is_general("telegram", "1"));
201        assert!(router.is_general("discord", "9999"));
202        assert!(!router.is_general("telegram", "42"));
203        assert!(!router.is_general("discord", "1111"));
204    }
205
206    #[test]
207    fn is_control_channel() {
208        let global = GlobalChannelConfig {
209            telegram_general_topic_id: Some("1".to_string()),
210            discord_general_channel_id: Some("9999".to_string()),
211            control_telegram_topic_id: Some("55".to_string()),
212            control_discord_channel_id: Some("77".to_string()),
213        };
214        let router = ChannelRouter::new(&global, &[]);
215        assert!(router.is_control_channel("telegram", "55"));
216        assert!(router.is_control_channel("discord", "77"));
217        assert!(!router.is_control_channel("telegram", "1")); // general, not control
218        assert!(!router.is_control_channel("discord", "9999")); // general, not control
219        assert!(!router.is_control_channel("telegram", "42")); // project channel
220        assert!(!router.is_control_channel("slack", "55")); // unknown channel
221    }
222
223    #[test]
224    fn control_channel_unconfigured_returns_false() {
225        let router = test_router(); // no control fields set
226        assert!(!router.is_control_channel("telegram", "1"));
227        assert!(!router.is_control_channel("discord", "9999"));
228    }
229
230    #[test]
231    fn target_for_project() {
232        let router = test_router();
233        assert_eq!(
234            router.target_for_project("owner/orch", "telegram"),
235            Some("42")
236        );
237        assert_eq!(
238            router.target_for_project("owner/bean", "discord"),
239            Some("2222")
240        );
241        assert_eq!(router.target_for_project("owner/unknown", "telegram"), None);
242    }
243
244    #[test]
245    fn projects_list() {
246        let router = test_router();
247        assert_eq!(router.projects().len(), 2);
248        assert!(router.projects().contains(&"owner/orch".to_string()));
249        assert!(router.projects().contains(&"owner/bean".to_string()));
250    }
251
252    #[test]
253    fn unmapped_target_returns_none() {
254        let router = test_router();
255        assert_eq!(router.resolve_project("telegram", "1"), None); // General is not a project
256        assert_eq!(router.resolve_project("slack", "anything"), None);
257    }
258
259    #[test]
260    fn project_with_custom_config_doesnt_affect_others() {
261        let global = GlobalChannelConfig {
262            telegram_general_topic_id: Some("1".into()),
263            discord_general_channel_id: None,
264            ..Default::default()
265        };
266        let projects = vec![
267            (
268                "owner/orch".into(),
269                ProjectChannelConfig {
270                    telegram_topic_id: Some("42".into()),
271                    ..Default::default()
272                },
273            ),
274            (
275                "owner/bean".into(),
276                ProjectChannelConfig {
277                    telegram_topic_id: Some("87".into()),
278                    ..Default::default()
279                },
280            ),
281        ];
282        let router = ChannelRouter::new(&global, &projects);
283        // Custom bot_token on orch should not affect bean's routing
284        assert_eq!(router.resolve_project("telegram", "42"), Some("owner/orch"));
285        assert_eq!(router.resolve_project("telegram", "87"), Some("owner/bean"));
286        // Reverse lookup also works
287        assert_eq!(
288            router.target_for_project("owner/orch", "telegram"),
289            Some("42")
290        );
291        assert_eq!(
292            router.target_for_project("owner/bean", "telegram"),
293            Some("87")
294        );
295        // General still resolves
296        assert!(router.is_general("telegram", "1"));
297        // Projects list includes both
298        assert_eq!(router.projects().len(), 2);
299    }
300}