use std::collections::BTreeSet;
use crate::identity::StableFaceId;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleCategory {
Responsibility,
Shape,
Protocol,
Route,
Style,
Delivery,
}
impl RuleCategory {
pub fn label(&self) -> &'static str {
match self {
Self::Responsibility => "responsibility",
Self::Shape => "shape",
Self::Protocol => "protocol",
Self::Route => "route",
Self::Style => "style",
Self::Delivery => "delivery",
}
}
pub fn parse_label(text: &str) -> Option<Self> {
[
Self::Responsibility,
Self::Shape,
Self::Protocol,
Self::Route,
Self::Style,
Self::Delivery,
]
.into_iter()
.find(|category| category.label() == text)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleOrigin {
AcceptedPolicy,
AdoptedSpecimen,
DerivedCandidate,
}
impl RuleOrigin {
pub fn label(&self) -> &'static str {
match self {
Self::AcceptedPolicy => "accepted_policy",
Self::AdoptedSpecimen => "adopted_specimen",
Self::DerivedCandidate => "derived_candidate",
}
}
pub fn parse_label(text: &str) -> Option<Self> {
[
Self::AcceptedPolicy,
Self::AdoptedSpecimen,
Self::DerivedCandidate,
]
.into_iter()
.find(|origin| origin.label() == text)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Polarity {
Require,
Forbid,
}
impl Polarity {
pub fn label(&self) -> &'static str {
match self {
Self::Require => "require",
Self::Forbid => "forbid",
}
}
pub fn parse_label(text: &str) -> Option<Self> {
[Self::Require, Self::Forbid]
.into_iter()
.find(|polarity| polarity.label() == text)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleState {
Proposed,
Accepted,
Stale,
Conflicted,
Retired,
}
impl RuleState {
pub fn label(&self) -> &'static str {
match self {
Self::Proposed => "proposed",
Self::Accepted => "accepted",
Self::Stale => "stale",
Self::Conflicted => "conflicted",
Self::Retired => "retired",
}
}
pub fn parse_label(text: &str) -> Option<Self> {
[
Self::Proposed,
Self::Accepted,
Self::Stale,
Self::Conflicted,
Self::Retired,
]
.into_iter()
.find(|state| state.label() == text)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleScope {
pub roles: Vec<String>,
pub selector: String,
pub configurations: Vec<String>,
pub projection: String,
}
impl RuleScope {
pub fn refuses(
&self,
roles: &[String],
selector: &str,
configuration: &str,
projection: &str,
) -> Option<&'static str> {
if !self.roles.is_empty() && !self.roles.iter().any(|role| roles.contains(role)) {
return Some("the subject's role is not one this rule speaks about");
}
if self.selector != selector {
return Some("the subject is not the entity this rule selects");
}
if !self.configurations.is_empty()
&& !self
.configurations
.iter()
.any(|known| known == configuration)
{
return Some("the subject is not under a configuration this rule was accepted for");
}
if self.projection != projection {
return Some(
"the subject is under a different projection than the one this rule speaks about",
);
}
None
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleException {
pub scope: String,
pub reason: String,
pub authority: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleBinding {
pub stable: StableFaceId,
pub path: String,
pub source: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleRecord {
pub rule_id: String,
pub revision: u64,
pub category: RuleCategory,
pub origin: RuleOrigin,
pub authority_ref: Option<String>,
pub scope: RuleScope,
pub object: Option<RuleBinding>,
pub requirement: String,
pub polarity: Polarity,
pub expects: Option<(String, String)>,
pub exceptions: Vec<RuleException>,
pub sources: Vec<(String, String)>,
pub state: RuleState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Standing {
Constrains,
NotConstraining(&'static str),
}
impl RuleRecord {
pub fn accept(&mut self, authority_ref: &str, revision: u64) -> Result<(), String> {
if authority_ref.trim().is_empty() {
return Err(
"accepting a rule needs an authority: a controller's acceptance event, not a model's own word"
.to_owned(),
);
}
if self.origin == RuleOrigin::DerivedCandidate {
return Err(
"a candidate derived from one repair is not a project rule; it must be reviewed as an adopted specimen or an accepted policy first"
.to_owned(),
);
}
self.authority_ref = Some(authority_ref.to_owned());
self.revision = revision;
self.state = RuleState::Accepted;
Ok(())
}
pub fn retire(&mut self, reason: &str, revision: u64) -> Result<(), String> {
if reason.trim().is_empty() {
return Err(
"retiring a rule needs a reason: the record is what the next reader has".to_owned(),
);
}
self.revision = revision;
self.state = RuleState::Retired;
Ok(())
}
pub fn standing(&self, current: &[(String, String)]) -> Standing {
match self.state {
RuleState::Proposed => {
return Standing::NotConstraining("a proposal is not a constraint");
}
RuleState::Retired => {
return Standing::NotConstraining("this rule was withdrawn on purpose");
}
RuleState::Conflicted => {
return Standing::NotConstraining(
"two accepted rules contradict each other and a person has to resolve them",
);
}
RuleState::Accepted | RuleState::Stale => {}
}
for (path, accepted) in &self.sources {
match current.iter().find(|(current, _)| current == path) {
None => {
return Standing::NotConstraining(
"a source this rule was accepted against is no longer here",
);
}
Some((_, digest)) if digest != accepted => {
return Standing::NotConstraining(
"a source this rule was accepted against changed",
);
}
Some(_) => {}
}
}
if self.state == RuleState::Stale {
return Standing::Constrains;
}
Standing::Constrains
}
pub fn exception_for(&self, scope: &str) -> Option<&RuleException> {
self.exceptions
.iter()
.find(|exception| exception.scope == scope && !exception.authority.trim().is_empty())
}
pub fn contradicts(&self, other: &Self) -> bool {
let same_commitment = self.requirement == other.requirement
|| (self.expects.is_some() && self.expects == other.expects);
self.rule_id != other.rule_id
&& self.scope == other.scope
&& same_commitment
&& self.polarity != other.polarity
}
}
pub fn conflicted(rules: &[RuleRecord]) -> Vec<String> {
let mut ids: BTreeSet<String> = BTreeSet::new();
for (index, rule) in rules.iter().enumerate() {
if rule.state != RuleState::Accepted {
continue;
}
for other in rules.iter().skip(index + 1) {
if other.state == RuleState::Accepted && rule.contradicts(other) {
ids.insert(rule.rule_id.clone());
ids.insert(other.rule_id.clone());
}
}
}
ids.into_iter().collect()
}
#[cfg(test)]
#[path = "rules_tests.rs"]
mod rules_tests;