config.rs 9.1 KB

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