use std::collections::BTreeSet;
use std::fmt;
use serde_json::Value;
use crate::contract::Contract;
use crate::descriptor::InterfaceEntry;
use crate::grammar::{IfaceId, InstanceId};
pub const PROFILE: &str = "redundancy.v1";
pub const NAME: &str = "redundancy";
pub const ELECTION: &str = "redundancy.election";
pub const VOCABULARY: &[&str] = &["election"];
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Election {
Claim,
External,
}
impl Election {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Claim => "claim",
Self::External => "external",
}
}
#[must_use]
pub fn parse(v: &Value) -> Option<Self> {
match v.as_str() {
Some("claim") => Some(Self::Claim),
Some("external") => Some(Self::External),
_ => None,
}
}
}
impl fmt::Display for Election {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
NotUsed,
Value,
Disagrees,
Tokenless,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotUsed => "not_used",
Self::Value => "value",
Self::Disagrees => "disagrees",
Self::Tokenless => "tokenless",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotUsed => "redundancy.election is written, and uses does not list redundancy.v1",
Self::Value => "redundancy.election is the string claim or external",
Self::Disagrees => "every resource of a governed interface resolves to one election",
Self::Tokenless => {
"a governed interface is never tokenless: its incumbent is the holder of its token"
}
}
}
}
impl fmt::Display for Invalid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.says())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
NotGoverned,
Invalid(Vec<Invalid>),
Governed(Election),
}
impl Declaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotGoverned => "not_governed",
Self::Invalid(_) => "invalid",
Self::Governed(_) => "governed",
}
}
#[must_use]
pub fn election(&self) -> Option<Election> {
match self {
Self::Governed(e) => Some(*e),
_ => None,
}
}
}
#[must_use]
pub fn declaration<'a, U, A>(uses: U, annotations: A, tokenless: bool) -> Declaration
where
U: IntoIterator<Item = &'a IfaceId>,
A: IntoIterator<Item = &'a std::collections::BTreeMap<String, Value>>,
{
let mut governed = false;
let mut another_major = false;
for u in uses {
if u.name() == NAME {
if u.major() == 1 {
governed = true;
} else {
another_major = true;
}
}
}
if another_major && !governed {
return Declaration::NotGoverned;
}
let values: Vec<Option<&Value>> = annotations.into_iter().map(|a| a.get(ELECTION)).collect();
let carried = values.iter().any(Option::is_some);
if !governed && !carried {
return Declaration::NotGoverned;
}
let mut why = Vec::new();
if !governed {
why.push(Invalid::NotUsed);
}
let mut elections = BTreeSet::new();
let mut wrong = false;
for v in &values {
match v {
None => {
elections.insert(Election::Claim);
}
Some(v) => match Election::parse(v) {
Some(e) => {
elections.insert(e);
}
None => wrong = true,
},
}
}
if wrong {
why.push(Invalid::Value);
}
if elections.len() > 1 {
why.push(Invalid::Disagrees);
}
if governed && tokenless {
why.push(Invalid::Tokenless);
}
if why.is_empty() {
Declaration::Governed(elections.into_iter().next().unwrap_or(Election::Claim))
} else {
Declaration::Invalid(why)
}
}
#[must_use]
pub fn declaration_of(c: &Contract, tokenless: bool) -> Declaration {
declaration(
&c.uses,
c.resources.iter().map(|r| &r.annotations),
tokenless,
)
}
#[must_use]
pub fn is_governed(c: &Contract) -> bool {
c.uses.iter().any(|u| u.name() == NAME && u.major() == 1)
}
#[must_use]
pub fn lower(a: &InstanceId, b: &InstanceId) -> bool {
a.as_str() < b.as_str()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Listing {
Unread,
NotListed,
Listed { standby: bool },
}
impl Listing {
#[must_use]
pub fn lists(self) -> bool {
matches!(self, Self::Listed { .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Seen {
pub id: InstanceId,
pub token: bool,
pub descriptor: Listing,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Read {
pub complete: bool,
pub instances: Vec<Seen>,
}
impl Read {
#[must_use]
pub fn holders(&self) -> Vec<&InstanceId> {
let set: BTreeSet<&InstanceId> = self
.instances
.iter()
.filter(|s| s.token)
.map(|s| &s.id)
.collect();
set.into_iter().collect()
}
#[must_use]
pub fn get(&self, id: &InstanceId) -> Option<&Seen> {
self.instances.iter().find(|s| &s.id == id)
}
fn holders_owned(&self) -> Vec<InstanceId> {
self.holders().into_iter().cloned().collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mark {
Serving,
Standby,
}
impl Mark {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Serving => "serving",
Self::Standby => "standby",
}
}
}
#[must_use]
pub fn mark(e: &InterfaceEntry) -> Mark {
if e.standby {
Mark::Standby
} else {
Mark::Serving
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Governance {
Governed(Election),
NotGoverned,
NoContract,
Disagree,
}
impl Governance {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Governed(e) => e.as_str(),
Self::NotGoverned => "not_governed",
Self::NoContract => "no_contract",
Self::Disagree => "disagree",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
match s {
"claim" => Some(Self::Governed(Election::Claim)),
"external" => Some(Self::Governed(Election::External)),
"not_governed" => Some(Self::NotGoverned),
"no_contract" => Some(Self::NoContract),
"disagree" => Some(Self::Disagree),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MarkFinding {
Malformed,
StandbyTokenless,
GovernedTokenless,
NotGoverned,
}
impl MarkFinding {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Malformed => "malformed",
Self::StandbyTokenless => "standby_tokenless",
Self::GovernedTokenless => "governed_tokenless",
Self::NotGoverned => "not_governed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkRead {
pub mark: Option<Mark>,
pub findings: Vec<MarkFinding>,
}
#[must_use]
pub fn read_mark(entry: &Value, governance: Governance) -> MarkRead {
let malformed = MarkRead {
mark: None,
findings: vec![MarkFinding::Malformed],
};
let Some(o) = entry.as_object() else {
return malformed;
};
let flag = |name: &str, absent: bool| match o.get(name) {
None => Some(absent),
Some(Value::Bool(b)) => Some(*b),
Some(_) => None,
};
let (Some(standby), Some(token)) = (flag("standby", false), flag("token", true)) else {
return malformed;
};
let mut findings = Vec::new();
if standby && !token {
findings.push(MarkFinding::StandbyTokenless);
}
if matches!(governance, Governance::Governed(_)) && !token {
findings.push(MarkFinding::GovernedTokenless);
}
if standby && governance == Governance::NotGoverned {
findings.push(MarkFinding::NotGoverned);
}
MarkRead {
mark: Some(if standby {
Mark::Standby
} else {
Mark::Serving
}),
findings,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Why {
Incumbent(InstanceId),
Incomplete,
OwnClaimMissing,
DescriptorUnread(InstanceId),
LowerCandidate(InstanceId),
NoLock,
}
impl Why {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Incumbent(_) => "incumbent",
Self::Incomplete => "incomplete",
Self::OwnClaimMissing => "own_claim_missing",
Self::DescriptorUnread(_) => "descriptor_unread",
Self::LowerCandidate(_) => "lower_candidate",
Self::NoLock => "no_lock",
}
}
#[must_use]
pub fn instance(&self) -> Option<&InstanceId> {
match self {
Self::Incumbent(i) | Self::DescriptorUnread(i) | Self::LowerCandidate(i) => Some(i),
Self::Incomplete | Self::OwnClaimMissing | Self::NoLock => None,
}
}
#[must_use]
pub fn retries(&self) -> bool {
!matches!(self, Self::Incumbent(_) | Self::NoLock)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
TakeOver,
StandBy(Why),
}
impl Decision {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::TakeOver => "take_over",
Self::StandBy(_) => "stand_by",
}
}
}
fn premises(own: &InstanceId, read: &Read) -> Option<Why> {
if let Some(h) = read.holders().into_iter().find(|h| *h != own) {
return Some(Why::Incumbent(h.clone()));
}
if !read.complete {
return Some(Why::Incomplete);
}
if read.get(own).is_none() {
return Some(Why::OwnClaimMissing);
}
None
}
#[must_use]
pub fn elect(own: &InstanceId, read: &Read) -> Decision {
if let Some(why) = premises(own, read) {
return Decision::StandBy(why);
}
let lowest = read
.instances
.iter()
.filter(|s| lower(&s.id, own) && s.descriptor != Listing::NotListed)
.min_by(|a, b| a.id.cmp(&b.id));
match lowest {
Some(s) if s.descriptor == Listing::Unread => {
Decision::StandBy(Why::DescriptorUnread(s.id.clone()))
}
Some(s) => Decision::StandBy(Why::LowerCandidate(s.id.clone())),
None => Decision::TakeOver,
}
}
#[must_use]
pub fn elect_external(own: &InstanceId, read: &Read) -> Decision {
match premises(own, read) {
Some(why) => Decision::StandBy(why),
None => Decision::TakeOver,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Stay {
External,
NotHolding,
NoSplit,
Lowest,
}
impl Stay {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::External => "external",
Self::NotHolding => "not_holding",
Self::NoSplit => "no_split",
Self::Lowest => "lowest",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Heal {
StepDown(InstanceId),
Stay(Stay),
}
#[must_use]
pub fn heal(
own: &InstanceId,
election: Election,
first: &[InstanceId],
second: &[InstanceId],
) -> Heal {
if election == Election::External {
return Heal::Stay(Stay::External);
}
let first: BTreeSet<&InstanceId> = first.iter().collect();
let second: BTreeSet<&InstanceId> = second.iter().collect();
if !second.contains(own) {
return Heal::Stay(Stay::NotHolding);
}
if first.len() < 2 || second.len() < 2 {
return Heal::Stay(Stay::NoSplit);
}
match second.into_iter().next() {
Some(low) if lower(low, own) => Heal::StepDown(low.clone()),
_ => Heal::Stay(Stay::Lowest),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Poll {
pub appeared: Vec<InstanceId>,
pub withdrawn: Vec<InstanceId>,
pub next: BTreeSet<InstanceId>,
}
#[must_use]
pub fn poll(last: &BTreeSet<InstanceId>, complete: bool, holders: &BTreeSet<InstanceId>) -> Poll {
let appeared = holders.difference(last).cloned().collect();
if complete {
Poll {
appeared,
withdrawn: last.difference(holders).cloned().collect(),
next: holders.clone(),
}
} else {
Poll {
appeared,
withdrawn: Vec::new(),
next: last.union(holders).cloned().collect(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
Read(Read),
Appeared(InstanceId),
Withdrawn,
Timer,
Lock(bool),
Reminted(InstanceId),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StepDownWhy {
LowerHolder(InstanceId),
LockLost,
}
impl StepDownWhy {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::LowerHolder(_) => "lower_holder",
Self::LockLost => "lock_lost",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
Claim,
Read,
Grace,
StandBy { why: Why, retry: bool },
Retry,
TakeOver,
StepDown(StepDownWhy),
Nothing,
}
impl Step {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Claim => "claim",
Self::Read => "read",
Self::Grace => "grace",
Self::StandBy { .. } => "stand_by",
Self::Retry => "retry",
Self::TakeOver => "take_over",
Self::StepDown(_) => "step_down",
Self::Nothing => "nothing",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
Unclaimed,
Standby,
Serving,
}
impl Role {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Unclaimed => "unclaimed",
Self::Standby => "standby",
Self::Serving => "serving",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Phase {
New,
Claiming,
Campaigning,
Standby {
retry: bool,
},
TakingOver,
Serving,
HealFirst,
HealGrace(Vec<InstanceId>),
HealSecond(Vec<InstanceId>),
HealRetry(Option<Vec<InstanceId>>),
SteppingDown(StepDownWhy),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Kept {
appeared: bool,
withdrawn: bool,
}
#[derive(Debug, Clone)]
pub struct Elector {
own: InstanceId,
former: BTreeSet<InstanceId>,
election: Election,
phase: Phase,
lock: bool,
kept: Kept,
}
impl Elector {
#[must_use]
pub fn new(own: InstanceId, election: Election) -> Self {
Self {
own,
former: BTreeSet::new(),
election,
phase: Phase::New,
lock: false,
kept: Kept::default(),
}
}
#[must_use]
pub fn own(&self) -> &InstanceId {
&self.own
}
#[must_use]
pub fn is_own(&self, id: &InstanceId) -> bool {
*id == self.own || self.former.contains(id)
}
#[must_use]
pub fn election(&self) -> Election {
self.election
}
#[must_use]
pub fn role(&self) -> Role {
match self.phase {
Phase::New | Phase::Claiming => Role::Unclaimed,
Phase::Campaigning | Phase::Standby { .. } | Phase::TakingOver => Role::Standby,
Phase::Serving
| Phase::HealFirst
| Phase::HealGrace(_)
| Phase::HealSecond(_)
| Phase::HealRetry(_)
| Phase::SteppingDown(_) => Role::Serving,
}
}
#[must_use]
pub fn serving(&self) -> bool {
self.role() == Role::Serving
}
#[must_use]
pub fn lock(&self) -> bool {
self.lock
}
pub fn start(&mut self) -> Step {
if self.phase != Phase::New {
return Step::Nothing;
}
self.phase = Phase::Claiming;
Step::Claim
}
pub fn finish(&mut self) -> Step {
let step = match std::mem::replace(&mut self.phase, Phase::New) {
Phase::Claiming => {
self.kept = Kept::default();
return self.campaign();
}
Phase::TakingOver => {
self.phase = Phase::Serving;
match self.election {
Election::External if !self.lock => {
self.kept = Kept::default();
return self.step_down(StepDownWhy::LockLost);
}
_ => Step::Nothing,
}
}
Phase::SteppingDown(_) => {
self.phase = Phase::Standby { retry: false };
Step::Nothing
}
other => {
self.phase = other;
return Step::Nothing;
}
};
self.decide_kept(step)
}
pub fn observe(&mut self, event: Event) -> Step {
match event {
Event::Read(r) => {
let r = self.normalized(&r);
self.on_read(&r)
}
Event::Appeared(id) => {
if self.is_own(&id) {
return Step::Nothing;
}
self.on_appeared()
}
Event::Withdrawn => self.on_withdrawn(),
Event::Timer => self.on_timer(),
Event::Lock(held) => self.on_lock(held),
Event::Reminted(id) => {
if id != self.own {
let old = std::mem::replace(&mut self.own, id);
self.former.insert(old);
self.former.remove(&self.own);
}
Step::Nothing
}
}
}
fn normalized(&self, r: &Read) -> Read {
if self.former.is_empty() {
return r.clone();
}
let mut instances = Vec::with_capacity(r.instances.len());
let mut own: Option<Seen> = None;
for s in &r.instances {
if !self.is_own(&s.id) {
instances.push(s.clone());
continue;
}
match &mut own {
None => {
own = Some(Seen {
id: self.own.clone(),
token: s.token,
descriptor: s.descriptor,
});
}
Some(o) => {
o.token |= s.token;
if s.id == self.own {
o.descriptor = s.descriptor;
}
}
}
}
instances.extend(own);
Read {
complete: r.complete,
instances,
}
}
fn decide_kept(&mut self, step: Step) -> Step {
fn replace(step: &mut Step, next: Step) {
if next != Step::Nothing && matches!(step, Step::Nothing | Step::StandBy { .. }) {
*step = next;
}
}
let kept = std::mem::take(&mut self.kept);
let mut step = step;
if kept.appeared {
let next = self.on_appeared();
replace(&mut step, next);
}
if kept.withdrawn {
let next = self.on_withdrawn();
replace(&mut step, next);
}
step
}
fn campaign(&mut self) -> Step {
if self.election == Election::External && !self.lock {
return self.stand_by(Why::NoLock);
}
self.phase = Phase::Campaigning;
Step::Read
}
fn stand_by(&mut self, why: Why) -> Step {
let retry = why.retries();
self.phase = Phase::Standby { retry };
Step::StandBy { why, retry }
}
fn step_down(&mut self, why: StepDownWhy) -> Step {
self.phase = Phase::SteppingDown(why.clone());
Step::StepDown(why)
}
fn holding(&self, r: &Read) -> Vec<InstanceId> {
let mut h = r.holders_owned();
if !h.contains(&self.own) {
h.push(self.own.clone());
h.sort();
}
h
}
fn on_read(&mut self, r: &Read) -> Step {
let step = match self.phase.clone() {
Phase::Campaigning => {
let decision = match self.election {
Election::Claim => elect(&self.own, r),
Election::External if !self.lock => Decision::StandBy(Why::NoLock),
Election::External => elect_external(&self.own, r),
};
match decision {
Decision::TakeOver => {
self.phase = Phase::TakingOver;
Step::TakeOver
}
Decision::StandBy(why) => self.stand_by(why),
}
}
Phase::HealFirst => {
let holders = self.holding(r);
if holders.len() >= 2 {
self.phase = Phase::HealGrace(holders);
Step::Grace
} else if r.complete {
self.phase = Phase::Serving;
Step::Nothing
} else {
self.phase = Phase::HealRetry(None);
Step::Retry
}
}
Phase::HealSecond(first) => {
let second = self.holding(r);
match heal(&self.own, self.election, &first, &second) {
Heal::StepDown(low) => self.step_down(StepDownWhy::LowerHolder(low)),
Heal::Stay(Stay::NoSplit) if !r.complete => {
self.phase = Phase::HealRetry(Some(first));
Step::Retry
}
Heal::Stay(_) => {
self.phase = Phase::Serving;
Step::Nothing
}
}
}
_ => return Step::Nothing,
};
self.decide_kept(step)
}
fn on_appeared(&mut self) -> Step {
if self.election != Election::Claim {
return Step::Nothing;
}
match self.phase {
Phase::Serving => {
self.phase = Phase::HealFirst;
Step::Read
}
Phase::Campaigning | Phase::TakingOver | Phase::HealFirst | Phase::HealSecond(_) => {
self.kept.appeared = true;
Step::Nothing
}
_ => Step::Nothing,
}
}
fn on_withdrawn(&mut self) -> Step {
match self.phase {
Phase::Standby { .. } => {
if self.election == Election::External && !self.lock {
Step::Nothing
} else {
self.campaign()
}
}
Phase::Campaigning
| Phase::SteppingDown(_)
| Phase::HealFirst
| Phase::HealSecond(_) => {
self.kept.withdrawn = true;
Step::Nothing
}
_ => Step::Nothing,
}
}
fn on_timer(&mut self) -> Step {
match self.phase.clone() {
Phase::Standby { retry: true } => self.campaign(),
Phase::HealGrace(first) => {
self.phase = Phase::HealSecond(first);
Step::Read
}
Phase::HealRetry(first) => {
self.phase = match first {
None => Phase::HealFirst,
Some(first) => Phase::HealSecond(first),
};
Step::Read
}
_ => Step::Nothing,
}
}
fn on_lock(&mut self, held: bool) -> Step {
if self.election != Election::External {
return Step::Nothing;
}
self.lock = held;
match self.phase {
Phase::Standby { .. } if held => self.campaign(),
Phase::Serving if !held => self.step_down(StepDownWhy::LockLost),
_ => Step::Nothing,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reading {
pub across_face: bool,
pub governance: Governance,
pub first: Read,
pub second: Read,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
Yes,
No,
Unobservable,
NotAsked,
NotThisProfiles,
}
impl Answer {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::No => "no",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
Self::NotThisProfiles => "not_this_profiles",
}
}
}
impl fmt::Display for Answer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
AcrossFace,
NotGoverned,
NoContract,
RevisionsDisagree,
Absent,
PresenceIncomplete,
Split,
InTransition,
One,
NoDescriptor,
NoCandidate,
Vacant,
Held,
Lasting,
StandingBy,
NoneStanding,
SplitLowest,
NotACandidate,
Unlisted,
Incumbent,
MarkedHolding,
Standby,
Unmarked,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::AcrossFace => "across_face",
Self::NotGoverned => "not_governed",
Self::NoContract => "no_contract",
Self::RevisionsDisagree => "revisions_disagree",
Self::Absent => "absent",
Self::PresenceIncomplete => "presence_incomplete",
Self::Split => "split",
Self::InTransition => "in_transition",
Self::One => "one",
Self::NoDescriptor => "no_descriptor",
Self::NoCandidate => "no_candidate",
Self::Vacant => "vacant",
Self::Held => "held",
Self::Lasting => "lasting",
Self::StandingBy => "standing_by",
Self::NoneStanding => "none",
Self::SplitLowest => "split_lowest",
Self::NotACandidate => "not_a_candidate",
Self::Unlisted => "unlisted",
Self::Incumbent => "incumbent",
Self::MarkedHolding => "marked_holding",
Self::Standby => "standby",
Self::Unmarked => "unmarked",
}
}
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
pub answer: Answer,
pub reason: Reason,
}
impl Judged {
const fn new(answer: Answer, reason: Reason) -> Self {
Self { answer, reason }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Count {
pub count: usize,
pub exact: bool,
}
fn premises_of(r: &Reading, present: bool) -> Result<(), Judged> {
use Answer::{NotAsked, NotThisProfiles, Unobservable};
if r.across_face {
return Err(Judged::new(Unobservable, Reason::AcrossFace));
}
if !present {
return Err(if r.second.complete {
Judged::new(NotAsked, Reason::Absent)
} else {
Judged::new(Unobservable, Reason::PresenceIncomplete)
});
}
match r.governance {
Governance::Governed(_) => Ok(()),
Governance::NotGoverned => Err(Judged::new(NotThisProfiles, Reason::NotGoverned)),
Governance::NoContract => Err(Judged::new(Unobservable, Reason::NoContract)),
Governance::Disagree => Err(Judged::new(Unobservable, Reason::RevisionsDisagree)),
}
}
fn address_premises(r: &Reading) -> Result<(), Judged> {
premises_of(r, !r.second.instances.is_empty())
}
fn no_candidate(read: &Read) -> Option<Judged> {
if read.instances.iter().any(|s| s.descriptor.lists()) {
return None;
}
Some(
if read
.instances
.iter()
.any(|s| s.descriptor == Listing::Unread)
{
Judged::new(Answer::Unobservable, Reason::NoDescriptor)
} else {
Judged::new(Answer::NotAsked, Reason::NoCandidate)
},
)
}
#[must_use]
pub fn one_incumbent(r: &Reading) -> Judged {
use Answer::{No, Unobservable, Yes};
if let Err(j) = address_premises(r) {
return j;
}
let h1 = r.first.holders().len();
let h2 = r.second.holders().len();
if h1 >= 2 && h2 >= 2 {
return Judged::new(No, Reason::Split);
}
if h2 >= 2 {
return Judged::new(Unobservable, Reason::InTransition);
}
if h2 == 1 {
return if r.second.complete {
Judged::new(Yes, Reason::One)
} else {
Judged::new(Unobservable, Reason::PresenceIncomplete)
};
}
if !r.second.complete {
return Judged::new(Unobservable, Reason::PresenceIncomplete);
}
if let Some(j) = no_candidate(&r.second) {
return j;
}
if h1 >= 1 {
return Judged::new(Unobservable, Reason::InTransition);
}
if !r.first.complete {
return Judged::new(Unobservable, Reason::PresenceIncomplete);
}
Judged::new(No, Reason::Vacant)
}
#[must_use]
pub fn vacancy(r: &Reading) -> Judged {
use Answer::{No, Unobservable, Yes};
if let Err(j) = address_premises(r) {
return j;
}
if !r.second.holders().is_empty() {
return Judged::new(No, Reason::Held);
}
if !r.second.complete {
return Judged::new(Unobservable, Reason::PresenceIncomplete);
}
if let Some(j) = no_candidate(&r.second) {
return j;
}
if r.first.complete && r.first.holders().is_empty() {
Judged::new(Yes, Reason::Lasting)
} else {
Judged::new(Yes, Reason::Vacant)
}
}
#[must_use]
pub fn standbys(r: &Reading) -> (Judged, Count) {
use Answer::{No, Unobservable, Yes};
let unknown = Count {
count: 0,
exact: false,
};
if let Err(j) = address_premises(r) {
return (j, unknown);
}
let read = &r.second;
let n = read
.instances
.iter()
.filter(|s| !s.token && s.descriptor == Listing::Listed { standby: true })
.count();
let unread = read
.instances
.iter()
.any(|s| s.descriptor == Listing::Unread);
if n >= 1 {
return (
Judged::new(Yes, Reason::StandingBy),
Count {
count: n,
exact: read.complete && !unread,
},
);
}
if !read.complete {
return (
Judged::new(Unobservable, Reason::PresenceIncomplete),
unknown,
);
}
if unread {
return (Judged::new(Unobservable, Reason::NoDescriptor), unknown);
}
(
Judged::new(No, Reason::NoneStanding),
Count {
count: 0,
exact: true,
},
)
}
#[must_use]
pub fn twin(r: &Reading, x: &InstanceId) -> Judged {
use Answer::{No, NotAsked, Unobservable, Yes};
let x2 = r.second.get(x);
if let Err(j) = premises_of(r, x2.is_some()) {
return j;
}
let Some(x2) = x2 else {
return Judged::new(NotAsked, Reason::Absent);
};
let x1 = r.first.get(x);
let h1 = r.first.holders();
let h2 = r.second.holders();
let same = x1.is_some_and(|a| a.token == x2.token && a.descriptor == x2.descriptor);
if x2.token && x1.is_some_and(|a| a.token) && h1.len() >= 2 && h2.len() >= 2 {
return if h2.first() == Some(&x) {
Judged::new(Yes, Reason::SplitLowest)
} else {
Judged::new(Yes, Reason::Split)
};
}
match x2.descriptor {
Listing::Unread => Judged::new(Unobservable, Reason::NoDescriptor),
Listing::NotListed if !x2.token => Judged::new(NotAsked, Reason::NotACandidate),
Listing::NotListed if same => Judged::new(Yes, Reason::Unlisted),
Listing::NotListed => Judged::new(Unobservable, Reason::InTransition),
Listing::Listed { standby } if x2.token => {
if h2.len() >= 2 {
Judged::new(Unobservable, Reason::InTransition)
} else if standby {
if same {
Judged::new(Yes, Reason::MarkedHolding)
} else {
Judged::new(Unobservable, Reason::InTransition)
}
} else if r.second.complete {
Judged::new(No, Reason::Incumbent)
} else {
Judged::new(Unobservable, Reason::PresenceIncomplete)
}
}
Listing::Listed { standby: true } => {
if r.second.complete {
Judged::new(No, Reason::Standby)
} else {
Judged::new(Unobservable, Reason::PresenceIncomplete)
}
}
Listing::Listed { standby: false } => {
if !same {
Judged::new(Unobservable, Reason::InTransition)
} else if r.first.complete && r.second.complete {
Judged::new(Yes, Reason::Unmarked)
} else {
Judged::new(Unobservable, Reason::PresenceIncomplete)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn id(n: u64) -> InstanceId {
InstanceId::from_u64(n)
}
fn seen(n: u64, token: bool, descriptor: Listing) -> Seen {
Seen {
id: id(n),
token,
descriptor,
}
}
const STANDBY: Listing = Listing::Listed { standby: true };
const SERVING: Listing = Listing::Listed { standby: false };
fn read(complete: bool, instances: Vec<Seen>) -> Read {
Read {
complete,
instances,
}
}
#[test]
fn ids_compare_as_unsigned_integers() {
assert!(lower(&id(0x9), &id(0xa)));
assert!(lower(&id(0xff), &id(0x100)));
assert!(!lower(&id(5), &id(5)));
}
#[test]
fn a_live_incumbent_wins_whatever_the_read() {
let r = read(false, vec![seen(9, true, Listing::Unread)]);
assert_eq!(elect(&id(1), &r), Decision::StandBy(Why::Incumbent(id(9))));
}
#[test]
fn the_lowest_candidate_wins_a_complete_read() {
let own = id(5);
let r = read(true, vec![seen(5, false, STANDBY), seen(7, false, STANDBY)]);
assert_eq!(elect(&own, &r), Decision::TakeOver);
let r = read(
true,
vec![
seen(2, false, Listing::NotListed),
seen(3, false, STANDBY),
seen(5, false, STANDBY),
],
);
assert_eq!(
elect(&own, &r),
Decision::StandBy(Why::LowerCandidate(id(3)))
);
let r = read(true, vec![seen(3, false, STANDBY)]);
assert_eq!(elect(&own, &r), Decision::StandBy(Why::OwnClaimMissing));
}
#[test]
fn a_split_leaves_the_lowest() {
let two = [id(2), id(8)];
assert_eq!(
heal(&id(8), Election::Claim, &two, &two),
Heal::StepDown(id(2))
);
assert_eq!(
heal(&id(2), Election::Claim, &two, &two),
Heal::Stay(Stay::Lowest)
);
assert_eq!(
heal(&id(8), Election::External, &two, &two),
Heal::Stay(Stay::External)
);
assert_eq!(
heal(&id(8), Election::Claim, &[id(8)], &two),
Heal::Stay(Stay::NoSplit)
);
}
#[test]
fn a_standby_takes_over_at_a_vacancy_and_steps_down_to_a_lower_one() {
let mut e = Elector::new(id(8), Election::Claim);
assert_eq!(e.start(), Step::Claim);
assert_eq!(e.finish(), Step::Read);
let incumbent = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
assert_eq!(
e.observe(Event::Read(incumbent)),
Step::StandBy {
why: Why::Incumbent(id(4)),
retry: false
}
);
assert_eq!(e.role(), Role::Standby);
assert_eq!(e.observe(Event::Timer), Step::Nothing);
assert_eq!(e.observe(Event::Withdrawn), Step::Read);
let vacant = read(true, vec![seen(8, false, STANDBY)]);
assert_eq!(e.observe(Event::Read(vacant)), Step::TakeOver);
assert_eq!(e.finish(), Step::Nothing);
assert!(e.serving());
assert_eq!(e.observe(Event::Appeared(id(2))), Step::Read);
let split = read(false, vec![seen(2, true, SERVING), seen(8, true, SERVING)]);
assert_eq!(e.observe(Event::Read(split.clone())), Step::Grace);
assert_eq!(e.observe(Event::Timer), Step::Read);
assert_eq!(
e.observe(Event::Read(split)),
Step::StepDown(StepDownWhy::LowerHolder(id(2)))
);
assert_eq!(e.finish(), Step::Nothing);
assert_eq!(e.role(), Role::Standby);
}
#[test]
fn external_serves_only_with_its_lock() {
let mut e = Elector::new(id(1), Election::External);
assert_eq!(e.start(), Step::Claim);
assert_eq!(
e.finish(),
Step::StandBy {
why: Why::NoLock,
retry: false
}
);
assert_eq!(e.observe(Event::Withdrawn), Step::Nothing);
assert_eq!(e.observe(Event::Lock(true)), Step::Read);
let alone = read(true, vec![seen(1, false, STANDBY), seen(9, false, STANDBY)]);
assert_eq!(e.observe(Event::Read(alone)), Step::TakeOver);
assert_eq!(e.finish(), Step::Nothing);
assert_eq!(e.observe(Event::Appeared(id(0))), Step::Nothing);
assert_eq!(
e.observe(Event::Lock(false)),
Step::StepDown(StepDownWhy::LockLost)
);
}
#[test]
fn a_read_asked_is_never_asked_again_before_its_answer() {
use std::collections::{HashSet, VecDeque};
let own = id(0xb);
let reads = [
read(true, vec![seen(0xb, false, STANDBY)]),
read(
true,
vec![seen(0xa, true, SERVING), seen(0xb, false, STANDBY)],
),
read(false, vec![]),
read(
true,
vec![seen(0xa, true, SERVING), seen(0xb, true, SERVING)],
),
read(false, vec![seen(0xb, true, SERVING)]),
read(
true,
vec![seen(0x1, false, STANDBY), seen(0xb, false, STANDBY)],
),
read(true, vec![seen(0xb, true, SERVING)]),
];
let others = [
Event::Appeared(id(0xa)),
Event::Appeared(own.clone()),
Event::Withdrawn,
Event::Timer,
Event::Lock(true),
Event::Lock(false),
Event::Reminted(id(0xc)),
];
for election in [Election::Claim, Election::External] {
let mut e = Elector::new(own.clone(), election);
assert_eq!(e.start(), Step::Claim);
let mut queue = VecDeque::from([(e.clone(), false, true)]);
let mut seen_states = HashSet::new();
let mut asked_states = 0;
while let Some((e, asked, acting)) = queue.pop_front() {
if !seen_states.insert(format!("{e:?} {asked} {acting}")) {
continue;
}
let mut next = |e: Elector, step: Step, was_asked: bool| {
let act = matches!(step, Step::Claim | Step::TakeOver | Step::StepDown(_));
let asks = step == Step::Read;
assert!(
!(was_asked && asks),
"{election}: a second read asked while one runs: {e:?}"
);
queue.push_back((e, was_asked || asks, act));
};
if acting {
let mut e2 = e.clone();
let step = e2.finish();
next(e2, step, asked);
continue;
}
if asked {
asked_states += 1;
for ev in &others {
let mut e2 = e.clone();
let step = e2.observe(ev.clone());
assert_eq!(
step,
Step::Nothing,
"{election}: {ev:?} while a read runs, in {e:?}"
);
assert_eq!(e2.finish(), Step::Nothing, "no act runs while a read does");
next(e2, Step::Nothing, true);
}
for r in &reads {
let mut e2 = e.clone();
let step = e2.observe(Event::Read(r.clone()));
next(e2, step, false);
}
} else {
for ev in &others {
let mut e2 = e.clone();
let step = e2.observe(ev.clone());
next(e2, step, false);
}
}
}
assert!(
asked_states > 0,
"{election}: the exploration reached reads asked"
);
}
}
#[test]
fn a_tool_tells_a_standby_from_a_twin() {
let one = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
let r = Reading {
across_face: false,
governance: Governance::Governed(Election::Claim),
first: one.clone(),
second: one,
};
assert_eq!(one_incumbent(&r).reason, Reason::One);
assert_eq!(vacancy(&r).reason, Reason::Held);
assert_eq!(
standbys(&r).1,
Count {
count: 1,
exact: true
}
);
assert_eq!(twin(&r, &id(4)).reason, Reason::Incumbent);
assert_eq!(twin(&r, &id(8)).reason, Reason::Standby);
let split = read(false, vec![seen(4, true, SERVING), seen(8, true, SERVING)]);
let r = Reading {
first: split.clone(),
second: split,
..r
};
assert_eq!(one_incumbent(&r).reason, Reason::Split);
assert_eq!(twin(&r, &id(4)).reason, Reason::SplitLowest);
assert_eq!(twin(&r, &id(8)).reason, Reason::Split);
}
}