config.rs 8.7 KB

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