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        let mapped = self
122            .target_to_repo
123            .keys()
124            .filter(|(channel, _)| channel == "discord")
125            .map(|(_, id)| id.clone());
126        mapped
127            .chain(self.general.get("discord").cloned())
128            .chain(self.control.get("discord").cloned())
129            .collect()
130    }
131
132    /// List all configured project repos.
133    pub fn projects(&self) -> &[String] {
134        &self.project_list
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn test_router() -> ChannelRouter {
143        let global = GlobalChannelConfig {
144            telegram_general_topic_id: Some("1".to_string()),
145            discord_general_channel_id: Some("9999".to_string()),
146            ..Default::default()
147        };
148        let projects = vec![
149            (
150                "owner/orch".to_string(),
151                ProjectChannelConfig {
152                    telegram_topic_id: Some("42".to_string()),
153                    discord_channel_id: Some("1111".to_string()),
154                },
155            ),
156            (
157                "owner/bean".to_string(),
158                ProjectChannelConfig {
159                    telegram_topic_id: Some("87".to_string()),
160                    discord_channel_id: Some("2222".to_string()),
161                },
162            ),
163        ];
164        ChannelRouter::new(&global, &projects)
165    }
166
167    #[test]
168    fn resolve_telegram_topic_to_project() {
169        let router = test_router();
170        assert_eq!(router.resolve_project("telegram", "42"), Some("owner/orch"));
171        assert_eq!(router.resolve_project("telegram", "87"), Some("owner/bean"));
172        assert_eq!(router.resolve_project("telegram", "99"), None);
173    }
174
175    #[test]
176    fn resolve_discord_channel_to_project() {
177        let router = test_router();
178        assert_eq!(
179            router.resolve_project("discord", "1111"),
180            Some("owner/orch")
181        );
182        assert_eq!(
183            router.resolve_project("discord", "2222"),
184            Some("owner/bean")
185        );
186    }
187
188    #[test]
189    fn is_general_channel() {
190        let router = test_router();
191        assert!(router.is_general("telegram", "1"));
192        assert!(router.is_general("discord", "9999"));
193        assert!(!router.is_general("telegram", "42"));
194        assert!(!router.is_general("discord", "1111"));
195    }
196
197    #[test]
198    fn is_control_channel() {
199        let global = GlobalChannelConfig {
200            telegram_general_topic_id: Some("1".to_string()),
201            discord_general_channel_id: Some("9999".to_string()),
202            control_telegram_topic_id: Some("55".to_string()),
203            control_discord_channel_id: Some("77".to_string()),
204        };
205        let router = ChannelRouter::new(&global, &[]);
206        assert!(router.is_control_channel("telegram", "55"));
207        assert!(router.is_control_channel("discord", "77"));
208        assert!(!router.is_control_channel("telegram", "1")); // general, not control
209        assert!(!router.is_control_channel("discord", "9999")); // general, not control
210        assert!(!router.is_control_channel("telegram", "42")); // project channel
211        assert!(!router.is_control_channel("slack", "55")); // unknown channel
212    }
213
214    #[test]
215    fn control_channel_unconfigured_returns_false() {
216        let router = test_router(); // no control fields set
217        assert!(!router.is_control_channel("telegram", "1"));
218        assert!(!router.is_control_channel("discord", "9999"));
219    }
220
221    #[test]
222    fn target_for_project() {
223        let router = test_router();
224        assert_eq!(
225            router.target_for_project("owner/orch", "telegram"),
226            Some("42")
227        );
228        assert_eq!(
229            router.target_for_project("owner/bean", "discord"),
230            Some("2222")
231        );
232        assert_eq!(router.target_for_project("owner/unknown", "telegram"), None);
233    }
234
235    #[test]
236    fn projects_list() {
237        let router = test_router();
238        assert_eq!(router.projects().len(), 2);
239        assert!(router.projects().contains(&"owner/orch".to_string()));
240        assert!(router.projects().contains(&"owner/bean".to_string()));
241    }
242
243    #[test]
244    fn unmapped_target_returns_none() {
245        let router = test_router();
246        assert_eq!(router.resolve_project("telegram", "1"), None); // General is not a project
247        assert_eq!(router.resolve_project("slack", "anything"), None);
248    }
249
250    #[test]
251    fn project_with_custom_config_doesnt_affect_others() {
252        let global = GlobalChannelConfig {
253            telegram_general_topic_id: Some("1".into()),
254            discord_general_channel_id: None,
255            ..Default::default()
256        };
257        let projects = vec![
258            (
259                "owner/orch".into(),
260                ProjectChannelConfig {
261                    telegram_topic_id: Some("42".into()),
262                    ..Default::default()
263                },
264            ),
265            (
266                "owner/bean".into(),
267                ProjectChannelConfig {
268                    telegram_topic_id: Some("87".into()),
269                    ..Default::default()
270                },
271            ),
272        ];
273        let router = ChannelRouter::new(&global, &projects);
274        // Custom bot_token on orch should not affect bean's routing
275        assert_eq!(router.resolve_project("telegram", "42"), Some("owner/orch"));
276        assert_eq!(router.resolve_project("telegram", "87"), Some("owner/bean"));
277        // Reverse lookup also works
278        assert_eq!(
279            router.target_for_project("owner/orch", "telegram"),
280            Some("42")
281        );
282        assert_eq!(
283            router.target_for_project("owner/bean", "telegram"),
284            Some("87")
285        );
286        // General still resolves
287        assert!(router.is_general("telegram", "1"));
288        // Projects list includes both
289        assert_eq!(router.projects().len(), 2);
290    }
291}