use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};
use tokio::sync::watch;
use crate::api;
use crate::sync::lock;
#[derive(Debug, PartialEq, Eq)]
pub struct Policy {
revision: u64,
setting: api::JobActions,
repositories: BTreeSet<String>,
reruns: BTreeSet<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Allowed {
pub setting: api::JobActions,
pub repositories: BTreeSet<String>,
pub reruns: BTreeSet<String>,
}
impl Allowed {
pub fn of(config: &crate::config::Config) -> Allowed {
let repositories = config.repositories.iter();
Allowed {
setting: api::JobActions::configured(config.github.job_actions),
repositories: repositories
.clone()
.map(|repository| repository.name.clone())
.collect(),
reruns: repositories
.filter(|repository| repository.rerun_runner_faults)
.map(|repository| repository.name.clone())
.collect(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Denied {
Off,
NotConfigured,
RerunsOff,
}
impl Policy {
fn of(revision: u64, allowed: Allowed) -> Policy {
Policy {
revision,
setting: allowed.setting,
repositories: allowed.repositories,
reruns: allowed.reruns,
}
}
pub fn revision(&self) -> u64 {
self.revision
}
pub fn allows(&self, repository: &str) -> Result<(), Denied> {
if self.setting != api::JobActions::On {
return Err(Denied::Off);
}
if !self.repositories.contains(repository) {
return Err(Denied::NotConfigured);
}
Ok(())
}
pub fn reruns(&self, repository: &str) -> Result<(), Denied> {
self.allows(repository)?;
if !self.reruns.contains(repository) {
return Err(Denied::RerunsOff);
}
Ok(())
}
}
#[derive(Debug)]
pub struct Policies {
current: Mutex<Arc<Policy>>,
revisions: watch::Sender<u64>,
}
impl Policies {
pub fn new(allowed: Allowed) -> Policies {
Policies {
current: Mutex::new(Arc::new(Policy::of(1, allowed))),
revisions: watch::Sender::new(1),
}
}
pub fn now(&self) -> Arc<Policy> {
lock(&self.current).clone()
}
pub fn replace(&self, allowed: Allowed) {
let mut current = lock(&self.current);
if current.setting == allowed.setting
&& current.repositories == allowed.repositories
&& current.reruns == allowed.reruns
{
return;
}
*current = Arc::new(Policy::of(current.revision + 1, allowed));
self.revisions.send_replace(current.revision);
}
pub async fn moved(&self, revision: u64) {
let mut revisions = self.revisions.subscribe();
let _ = revisions.wait_for(|now| *now != revision).await;
}
}