config.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. use crate::changelogs::ChangelogFormat;
  2. use crate::github::GithubClient;
  3. use std::collections::{HashMap, HashSet};
  4. use std::fmt;
  5. use std::sync::{Arc, RwLock};
  6. use std::time::{Duration, Instant};
  7. static CONFIG_FILE_NAME: &str = "triagebot.toml";
  8. const REFRESH_EVERY: Duration = Duration::from_secs(2 * 60); // Every two minutes
  9. lazy_static::lazy_static! {
  10. static ref CONFIG_CACHE:
  11. RwLock<HashMap<String, (Result<Arc<Config>, ConfigurationError>, Instant)>> =
  12. RwLock::new(HashMap::new());
  13. }
  14. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  15. #[serde(rename_all = "kebab-case")]
  16. pub(crate) struct Config {
  17. pub(crate) relabel: Option<RelabelConfig>,
  18. pub(crate) assign: Option<AssignConfig>,
  19. pub(crate) ping: Option<PingConfig>,
  20. pub(crate) nominate: Option<NominateConfig>,
  21. pub(crate) prioritize: Option<PrioritizeConfig>,
  22. pub(crate) major_change: Option<MajorChangeConfig>,
  23. pub(crate) glacier: Option<GlacierConfig>,
  24. pub(crate) close: Option<CloseConfig>,
  25. pub(crate) autolabel: Option<AutolabelConfig>,
  26. pub(crate) notify_zulip: Option<NotifyZulipConfig>,
  27. pub(crate) github_releases: Option<GitHubReleasesConfig>,
  28. }
  29. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  30. pub(crate) struct NominateConfig {
  31. // team name -> label
  32. pub(crate) teams: HashMap<String, String>,
  33. }
  34. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  35. pub(crate) struct PingConfig {
  36. // team name -> message
  37. // message will have the cc string appended
  38. #[serde(flatten)]
  39. teams: HashMap<String, PingTeamConfig>,
  40. }
  41. impl PingConfig {
  42. pub(crate) fn get_by_name(&self, team: &str) -> Option<(&str, &PingTeamConfig)> {
  43. if let Some((team, cfg)) = self.teams.get_key_value(team) {
  44. return Some((team, cfg));
  45. }
  46. for (name, cfg) in self.teams.iter() {
  47. if cfg.alias.contains(team) {
  48. return Some((name, cfg));
  49. }
  50. }
  51. None
  52. }
  53. }
  54. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  55. pub(crate) struct PingTeamConfig {
  56. pub(crate) message: String,
  57. #[serde(default)]
  58. pub(crate) alias: HashSet<String>,
  59. pub(crate) label: Option<String>,
  60. }
  61. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  62. pub(crate) struct AssignConfig {
  63. #[serde(default)]
  64. _empty: (),
  65. }
  66. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  67. #[serde(rename_all = "kebab-case")]
  68. pub(crate) struct RelabelConfig {
  69. #[serde(default)]
  70. pub(crate) allow_unauthenticated: Vec<String>,
  71. }
  72. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  73. pub(crate) struct PrioritizeConfig {
  74. pub(crate) label: String,
  75. }
  76. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  77. pub(crate) struct AutolabelConfig {
  78. #[serde(flatten)]
  79. pub(crate) labels: HashMap<String, AutolabelLabelConfig>,
  80. }
  81. impl AutolabelConfig {
  82. pub(crate) fn get_by_trigger(&self, trigger: &str) -> Vec<(&str, &AutolabelLabelConfig)> {
  83. let mut results = Vec::new();
  84. for (label, cfg) in self.labels.iter() {
  85. if cfg.trigger_labels.iter().any(|l| l == trigger) {
  86. results.push((label.as_str(), cfg));
  87. }
  88. }
  89. results
  90. }
  91. }
  92. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  93. pub(crate) struct AutolabelLabelConfig {
  94. pub(crate) trigger_labels: Vec<String>,
  95. #[serde(default)]
  96. pub(crate) exclude_labels: Vec<String>,
  97. }
  98. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  99. pub(crate) struct NotifyZulipConfig {
  100. #[serde(flatten)]
  101. pub(crate) labels: HashMap<String, NotifyZulipLabelConfig>,
  102. }
  103. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  104. pub(crate) struct NotifyZulipLabelConfig {
  105. pub(crate) zulip_stream: u64,
  106. pub(crate) topic: String,
  107. pub(crate) message_on_add: Option<String>,
  108. pub(crate) message_on_remove: Option<String>,
  109. #[serde(default)]
  110. pub(crate) required_labels: Vec<String>,
  111. }
  112. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  113. pub(crate) struct MajorChangeConfig {
  114. pub(crate) zulip_ping: String,
  115. pub(crate) second_label: String,
  116. pub(crate) meeting_label: String,
  117. pub(crate) zulip_stream: u64,
  118. pub(crate) open_extra_text: Option<String>,
  119. }
  120. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  121. pub(crate) struct GlacierConfig {}
  122. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  123. pub(crate) struct CloseConfig {}
  124. pub(crate) async fn get(gh: &GithubClient, repo: &str) -> Result<Arc<Config>, ConfigurationError> {
  125. if let Some(config) = get_cached_config(repo) {
  126. log::trace!("returning config for {} from cache", repo);
  127. config
  128. } else {
  129. log::trace!("fetching fresh config for {}", repo);
  130. let res = get_fresh_config(gh, repo).await;
  131. CONFIG_CACHE
  132. .write()
  133. .unwrap()
  134. .insert(repo.to_string(), (res.clone(), Instant::now()));
  135. res
  136. }
  137. }
  138. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  139. #[serde(rename_all = "kebab-case")]
  140. pub(crate) struct GitHubReleasesConfig {
  141. pub(crate) format: ChangelogFormat,
  142. pub(crate) project_name: String,
  143. pub(crate) changelog_path: String,
  144. pub(crate) changelog_branch: String,
  145. }
  146. fn get_cached_config(repo: &str) -> Option<Result<Arc<Config>, ConfigurationError>> {
  147. let cache = CONFIG_CACHE.read().unwrap();
  148. cache.get(repo).and_then(|(config, fetch_time)| {
  149. if fetch_time.elapsed() < REFRESH_EVERY {
  150. Some(config.clone())
  151. } else {
  152. None
  153. }
  154. })
  155. }
  156. async fn get_fresh_config(
  157. gh: &GithubClient,
  158. repo: &str,
  159. ) -> Result<Arc<Config>, ConfigurationError> {
  160. let contents = gh
  161. .raw_file(repo, "master", CONFIG_FILE_NAME)
  162. .await
  163. .map_err(|e| ConfigurationError::Http(Arc::new(e)))?
  164. .ok_or(ConfigurationError::Missing)?;
  165. let config = Arc::new(toml::from_slice::<Config>(&contents).map_err(ConfigurationError::Toml)?);
  166. log::debug!("fresh configuration for {}: {:?}", repo, config);
  167. Ok(config)
  168. }
  169. #[derive(Clone, Debug)]
  170. pub enum ConfigurationError {
  171. Missing,
  172. Toml(toml::de::Error),
  173. Http(Arc<anyhow::Error>),
  174. }
  175. impl std::error::Error for ConfigurationError {}
  176. impl fmt::Display for ConfigurationError {
  177. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  178. match self {
  179. ConfigurationError::Missing => write!(
  180. f,
  181. "This repository is not enabled to use triagebot.\n\
  182. Add a `triagebot.toml` in the root of the master branch to enable it."
  183. ),
  184. ConfigurationError::Toml(e) => {
  185. write!(f, "Malformed `triagebot.toml` in master branch.\n{}", e)
  186. }
  187. ConfigurationError::Http(_) => {
  188. write!(f, "Failed to query configuration for this repository.")
  189. }
  190. }
  191. }
  192. }
  193. #[cfg(test)]
  194. mod tests {
  195. use super::*;
  196. #[test]
  197. fn sample() {
  198. let config = r#"
  199. [relabel]
  200. allow-unauthenticated = [
  201. "C-*"
  202. ]
  203. [assign]
  204. [ping.compiler]
  205. message = """\
  206. So many people!\
  207. """
  208. label = "T-compiler"
  209. [ping.wg-meta]
  210. message = """\
  211. Testing\
  212. """
  213. [nominate.teams]
  214. compiler = "T-compiler"
  215. release = "T-release"
  216. core = "T-core"
  217. infra = "T-infra"
  218. "#;
  219. let config = toml::from_str::<Config>(&config).unwrap();
  220. let mut ping_teams = HashMap::new();
  221. ping_teams.insert(
  222. "compiler".to_owned(),
  223. PingTeamConfig {
  224. message: "So many people!".to_owned(),
  225. label: Some("T-compiler".to_owned()),
  226. alias: HashSet::new(),
  227. },
  228. );
  229. ping_teams.insert(
  230. "wg-meta".to_owned(),
  231. PingTeamConfig {
  232. message: "Testing".to_owned(),
  233. label: None,
  234. alias: HashSet::new(),
  235. },
  236. );
  237. let mut nominate_teams = HashMap::new();
  238. nominate_teams.insert("compiler".to_owned(), "T-compiler".to_owned());
  239. nominate_teams.insert("release".to_owned(), "T-release".to_owned());
  240. nominate_teams.insert("core".to_owned(), "T-core".to_owned());
  241. nominate_teams.insert("infra".to_owned(), "T-infra".to_owned());
  242. assert_eq!(
  243. config,
  244. Config {
  245. relabel: Some(RelabelConfig {
  246. allow_unauthenticated: vec!["C-*".into()],
  247. }),
  248. assign: Some(AssignConfig { _empty: () }),
  249. ping: Some(PingConfig { teams: ping_teams }),
  250. nominate: Some(NominateConfig {
  251. teams: nominate_teams
  252. }),
  253. prioritize: None,
  254. major_change: None,
  255. glacier: None,
  256. close: None,
  257. autolabel: None,
  258. notify_zulip: None,
  259. github_releases: None,
  260. }
  261. );
  262. }
  263. }