1use std::collections::BTreeSet;
64use std::fmt;
65
66use serde_json::Value;
67
68use crate::contract::Contract;
69use crate::descriptor::InterfaceEntry;
70use crate::grammar::{IfaceId, InstanceId, KindToken};
71use crate::wire::Run;
72
73mod fence;
74pub mod v2;
75
76pub(crate) use fence::Heard;
77pub use fence::{Asked, Described, Discard, Fence, Fenced, Holding, Member, Outcome, Sample};
78
79pub const PROFILE: &str = "redundancy.v1";
81
82pub const NAME: &str = "redundancy";
84
85pub const ELECTION: &str = "redundancy.election";
87
88pub const VOCABULARY: &[&str] = &["election"];
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
97pub enum Major {
98 V1,
101 V2,
104}
105
106impl Major {
107 pub const ALL: [Major; 2] = [Major::V1, Major::V2];
109
110 #[must_use]
112 pub const fn profile(self) -> &'static str {
113 match self {
114 Major::V1 => PROFILE,
115 Major::V2 => v2::PROFILE,
116 }
117 }
118
119 #[must_use]
121 pub const fn number(self) -> u32 {
122 match self {
123 Major::V1 => 1,
124 Major::V2 => 2,
125 }
126 }
127
128 #[must_use]
130 pub const fn from_number(n: u32) -> Option<Major> {
131 match n {
132 1 => Some(Major::V1),
133 2 => Some(Major::V2),
134 _ => None,
135 }
136 }
137
138 #[must_use]
144 pub fn of<'a>(uses: impl IntoIterator<Item = &'a IfaceId>) -> Option<Major> {
145 let mut found = None;
146 for u in uses {
147 if u.name() != NAME {
148 continue;
149 }
150 match Major::from_number(u.major()) {
151 Some(Major::V2) => return Some(Major::V2),
152 Some(Major::V1) => found = Some(Major::V1),
153 None => {}
154 }
155 }
156 found
157 }
158}
159
160impl fmt::Display for Major {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.write_str(self.profile())
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub enum Election {
171 Claim,
173 External,
175}
176
177impl Election {
178 #[must_use]
180 pub fn as_str(self) -> &'static str {
181 match self {
182 Self::Claim => "claim",
183 Self::External => "external",
184 }
185 }
186
187 #[must_use]
190 pub fn parse(v: &Value) -> Option<Self> {
191 match v.as_str() {
192 Some("claim") => Some(Self::Claim),
193 Some("external") => Some(Self::External),
194 _ => None,
195 }
196 }
197}
198
199impl fmt::Display for Election {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.write_str(self.as_str())
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
209pub enum Invalid {
210 Majors,
214 NotUsed,
217 Value,
219 Disagrees,
221 Tokenless,
224 ExplicitStream,
228}
229
230impl Invalid {
231 #[must_use]
233 pub fn as_str(self) -> &'static str {
234 match self {
235 Self::Majors => "majors",
236 Self::NotUsed => "not_used",
237 Self::Value => "value",
238 Self::Disagrees => "disagrees",
239 Self::Tokenless => "tokenless",
240 Self::ExplicitStream => "explicit_stream",
241 }
242 }
243
244 #[must_use]
246 pub fn says(self) -> &'static str {
247 match self {
248 Self::Majors => "uses lists redundancy.v2 and another major of redundancy",
249 Self::NotUsed => "redundancy.election is written, and uses does not list redundancy.v1",
250 Self::Value => "redundancy.election is the string claim or external",
251 Self::Disagrees => "every resource of a governed interface resolves to one election",
252 Self::Tokenless => {
253 "a governed interface is never tokenless: its incumbent is the holder of its token"
254 }
255 Self::ExplicitStream => {
256 "an explicit stream's samples carry no envelope, so no run a follower can fence: \
257 a redundancy.v2 interface declares none"
258 }
259 }
260 }
261}
262
263impl fmt::Display for Invalid {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 f.write_str(self.says())
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
271pub enum Declaration {
272 NotGoverned,
274 Invalid(Vec<Invalid>),
276 Governed(Election),
278}
279
280impl Declaration {
281 #[must_use]
283 pub fn as_str(&self) -> &'static str {
284 match self {
285 Self::NotGoverned => "not_governed",
286 Self::Invalid(_) => "invalid",
287 Self::Governed(_) => "governed",
288 }
289 }
290
291 #[must_use]
293 pub fn election(&self) -> Option<Election> {
294 match self {
295 Self::Governed(e) => Some(*e),
296 _ => None,
297 }
298 }
299}
300
301#[must_use]
310pub fn declaration<'a, U, A>(uses: U, annotations: A, tokenless: bool) -> Declaration
311where
312 U: IntoIterator<Item = &'a IfaceId>,
313 A: IntoIterator<Item = &'a std::collections::BTreeMap<String, Value>>,
314{
315 let mut governed = false;
316 let mut another_major = false;
317 for u in uses {
318 if u.name() == NAME {
319 if u.major() == 1 {
320 governed = true;
321 } else {
322 another_major = true;
323 }
324 }
325 }
326 if another_major && !governed {
327 return Declaration::NotGoverned;
329 }
330 let values: Vec<Option<&Value>> = annotations.into_iter().map(|a| a.get(ELECTION)).collect();
331 let carried = values.iter().any(Option::is_some);
332 if !governed && !carried {
333 return Declaration::NotGoverned;
334 }
335 let mut why = Vec::new();
336 if !governed {
337 why.push(Invalid::NotUsed);
338 }
339 let election = elections(&values, &mut why);
340 if governed && tokenless {
341 why.push(Invalid::Tokenless);
342 }
343 if why.is_empty() {
344 Declaration::Governed(election)
345 } else {
346 Declaration::Invalid(why)
347 }
348}
349
350pub(crate) fn elections(values: &[Option<&Value>], why: &mut Vec<Invalid>) -> Election {
355 let mut elections = BTreeSet::new();
356 let mut wrong = false;
357 for v in values {
358 match v {
359 None => {
360 elections.insert(Election::Claim);
361 }
362 Some(v) => match Election::parse(v) {
363 Some(e) => {
364 elections.insert(e);
365 }
366 None => wrong = true,
367 },
368 }
369 }
370 if wrong {
371 why.push(Invalid::Value);
372 }
373 if elections.len() > 1 {
374 why.push(Invalid::Disagrees);
375 }
376 elections.into_iter().next().unwrap_or(Election::Claim)
377}
378
379#[must_use]
383pub fn declaration_of(c: &Contract, tokenless: bool) -> Declaration {
384 declaration(
385 &c.uses,
386 c.resources.iter().map(|r| &r.annotations),
387 tokenless,
388 )
389}
390
391#[must_use]
396pub fn either_declaration_of(c: &Contract, tokenless: bool) -> Declaration {
397 if Major::of(&c.uses) == Some(Major::V2) {
398 v2::declaration_of(c, tokenless)
399 } else {
400 declaration_of(c, tokenless)
401 }
402}
403
404#[must_use]
408pub fn is_governed(c: &Contract) -> bool {
409 Major::of(&c.uses).is_some()
410}
411
412#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct Warning {
420 pub major: Major,
422 pub at: String,
425 pub reason: Invalid,
426}
427
428impl fmt::Display for Warning {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 write!(
432 f,
433 "warning[{} {}] {}: {}",
434 self.major.profile(),
435 self.reason.as_str(),
436 self.at,
437 self.reason.says()
438 )
439 }
440}
441
442#[must_use]
448pub fn lint_contract(c: &Contract) -> Vec<Warning> {
449 let Some(major) = Major::of(&c.uses) else {
450 return Vec::new();
451 };
452 let Declaration::Invalid(why) = either_declaration_of(c, false) else {
453 return Vec::new();
454 };
455 let warn = |at: String, reason| Warning { major, at, reason };
456 let mut out = Vec::new();
457 for reason in why {
458 match reason {
459 Invalid::Value => out.extend(
460 c.resources
461 .iter()
462 .filter(|r| {
463 r.annotations
464 .get(ELECTION)
465 .is_some_and(|v| Election::parse(v).is_none())
466 })
467 .map(|r| warn(crate::words::Lint::place(r), reason)),
468 ),
469 Invalid::Disagrees => out.push(warn(c.iface.to_string(), reason)),
470 Invalid::ExplicitStream => out.extend(
471 c.resources
472 .iter()
473 .filter(|r| r.token == KindToken::ExplicitStream)
474 .map(|r| warn(crate::words::Lint::place(r), reason)),
475 ),
476 Invalid::Majors | Invalid::NotUsed | Invalid::Tokenless => {}
477 }
478 }
479 out
480}
481
482#[must_use]
488pub fn lower(a: &InstanceId, b: &InstanceId) -> bool {
489 a.as_str() < b.as_str()
490}
491
492#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
495pub enum Listing {
496 Unread,
498 NotListed,
500 Listed { standby: bool },
502}
503
504impl Listing {
505 #[must_use]
507 pub fn lists(self) -> bool {
508 matches!(self, Self::Listed { .. })
509 }
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct Seen {
515 pub id: InstanceId,
516 pub token: bool,
518 pub descriptor: Listing,
519}
520
521#[derive(Debug, Clone, PartialEq, Eq, Default)]
524pub struct Read {
525 pub complete: bool,
526 pub instances: Vec<Seen>,
527}
528
529impl Read {
530 #[must_use]
533 pub fn holders(&self) -> Vec<&InstanceId> {
534 let set: BTreeSet<&InstanceId> = self
535 .instances
536 .iter()
537 .filter(|s| s.token)
538 .map(|s| &s.id)
539 .collect();
540 set.into_iter().collect()
541 }
542
543 #[must_use]
545 pub fn get(&self, id: &InstanceId) -> Option<&Seen> {
546 self.instances.iter().find(|s| &s.id == id)
547 }
548
549 fn holders_owned(&self) -> Vec<InstanceId> {
550 self.holders().into_iter().cloned().collect()
551 }
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
559pub enum Mark {
560 Serving,
562 Standby,
565}
566
567impl Mark {
568 #[must_use]
570 pub fn as_str(self) -> &'static str {
571 match self {
572 Self::Serving => "serving",
573 Self::Standby => "standby",
574 }
575 }
576}
577
578#[must_use]
580pub fn mark(e: &InterfaceEntry) -> Mark {
581 if e.standby {
582 Mark::Standby
583 } else {
584 Mark::Serving
585 }
586}
587
588#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
590pub enum Governance {
591 Governed(Election),
593 NotGoverned,
595 NoContract,
597 Disagree,
600}
601
602impl Governance {
603 #[must_use]
605 pub fn as_str(self) -> &'static str {
606 match self {
607 Self::Governed(e) => e.as_str(),
608 Self::NotGoverned => "not_governed",
609 Self::NoContract => "no_contract",
610 Self::Disagree => "disagree",
611 }
612 }
613
614 #[must_use]
616 pub fn parse(s: &str) -> Option<Self> {
617 match s {
618 "claim" => Some(Self::Governed(Election::Claim)),
619 "external" => Some(Self::Governed(Election::External)),
620 "not_governed" => Some(Self::NotGoverned),
621 "no_contract" => Some(Self::NoContract),
622 "disagree" => Some(Self::Disagree),
623 _ => None,
624 }
625 }
626}
627
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
630pub enum MarkFinding {
631 Malformed,
634 StandbyTokenless,
636 GovernedTokenless,
638 NotGoverned,
641}
642
643impl MarkFinding {
644 #[must_use]
646 pub fn as_str(self) -> &'static str {
647 match self {
648 Self::Malformed => "malformed",
649 Self::StandbyTokenless => "standby_tokenless",
650 Self::GovernedTokenless => "governed_tokenless",
651 Self::NotGoverned => "not_governed",
652 }
653 }
654}
655
656#[derive(Debug, Clone, PartialEq, Eq)]
658pub struct MarkRead {
659 pub mark: Option<Mark>,
660 pub findings: Vec<MarkFinding>,
661}
662
663#[must_use]
666pub fn read_mark(entry: &Value, governance: Governance) -> MarkRead {
667 let malformed = MarkRead {
668 mark: None,
669 findings: vec![MarkFinding::Malformed],
670 };
671 let Some(o) = entry.as_object() else {
672 return malformed;
673 };
674 let flag = |name: &str, absent: bool| match o.get(name) {
675 None => Some(absent),
676 Some(Value::Bool(b)) => Some(*b),
677 Some(_) => None,
678 };
679 let (Some(standby), Some(token)) = (flag("standby", false), flag("token", true)) else {
680 return malformed;
681 };
682 let mut findings = Vec::new();
683 if standby && !token {
684 findings.push(MarkFinding::StandbyTokenless);
685 }
686 if matches!(governance, Governance::Governed(_)) && !token {
687 findings.push(MarkFinding::GovernedTokenless);
688 }
689 if standby && governance == Governance::NotGoverned {
690 findings.push(MarkFinding::NotGoverned);
691 }
692 MarkRead {
693 mark: Some(if standby {
694 Mark::Standby
695 } else {
696 Mark::Serving
697 }),
698 findings,
699 }
700}
701
702#[derive(Debug, Clone, PartialEq, Eq)]
706pub struct DescriptorRead {
707 pub run: Option<Run>,
712 pub listed: bool,
715 pub mark: Option<Mark>,
717 pub findings: Vec<MarkFinding>,
719}
720
721#[must_use]
727pub fn read_descriptor(descriptor: &Value, iface: &str, governance: Governance) -> DescriptorRead {
728 let run = descriptor
729 .get("run")
730 .and_then(Value::as_str)
731 .and_then(Run::from_hex);
732 let entry = descriptor
733 .get("interfaces")
734 .and_then(Value::as_array)
735 .into_iter()
736 .flatten()
737 .find(|e| {
738 e.as_object()
739 .is_none_or(|o| o.get("iface").and_then(Value::as_str) == Some(iface))
740 });
741 match entry {
742 Some(e) => {
743 let m = read_mark(e, governance);
744 DescriptorRead {
745 run,
746 listed: true,
747 mark: m.mark,
748 findings: m.findings,
749 }
750 }
751 None => DescriptorRead {
752 run,
753 listed: false,
754 mark: None,
755 findings: Vec::new(),
756 },
757 }
758}
759
760#[must_use]
765pub fn draw_again(own: Run, read: impl IntoIterator<Item = Run>) -> bool {
766 read.into_iter().any(|r| r == own)
767}
768
769#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
773pub enum Revision {
774 Governed(Major, Election),
776 NotGoverned,
777 Invalid,
779 Unread,
781}
782
783impl Revision {
784 #[must_use]
787 pub fn of(c: &Contract) -> Revision {
788 match (either_declaration_of(c, false), Major::of(&c.uses)) {
789 (Declaration::Governed(e), Some(m)) => Revision::Governed(m, e),
790 (Declaration::Governed(_) | Declaration::NotGoverned, _) => Revision::NotGoverned,
791 (Declaration::Invalid(_), _) => Revision::Invalid,
792 }
793 }
794}
795
796#[must_use]
805pub fn governance(revisions: impl IntoIterator<Item = Revision>) -> Governance {
806 let mut any = false;
807 let mut elections = BTreeSet::new();
808 let mut not_governed = false;
809 for r in revisions {
810 any = true;
811 match r {
812 Revision::Unread | Revision::Invalid => return Governance::NoContract,
813 Revision::NotGoverned => not_governed = true,
814 Revision::Governed(_, e) => {
815 elections.insert(e);
816 }
817 }
818 }
819 if !any {
820 return Governance::NoContract;
821 }
822 match (elections.len(), not_governed) {
823 (0, _) => Governance::NotGoverned,
824 (1, false) => Governance::Governed(*elections.iter().next().expect("one")),
825 _ => Governance::Disagree,
826 }
827}
828
829#[derive(Debug, Clone, PartialEq, Eq, Hash)]
833pub enum Why {
834 Incumbent(InstanceId),
836 Incomplete,
838 OwnClaimMissing,
840 DescriptorUnread(InstanceId),
842 LowerCandidate(InstanceId),
844 NoLock,
846}
847
848impl Why {
849 #[must_use]
851 pub fn as_str(&self) -> &'static str {
852 match self {
853 Self::Incumbent(_) => "incumbent",
854 Self::Incomplete => "incomplete",
855 Self::OwnClaimMissing => "own_claim_missing",
856 Self::DescriptorUnread(_) => "descriptor_unread",
857 Self::LowerCandidate(_) => "lower_candidate",
858 Self::NoLock => "no_lock",
859 }
860 }
861
862 #[must_use]
864 pub fn instance(&self) -> Option<&InstanceId> {
865 match self {
866 Self::Incumbent(i) | Self::DescriptorUnread(i) | Self::LowerCandidate(i) => Some(i),
867 Self::Incomplete | Self::OwnClaimMissing | Self::NoLock => None,
868 }
869 }
870
871 #[must_use]
875 pub fn retries(&self) -> bool {
876 !matches!(self, Self::Incumbent(_) | Self::NoLock)
877 }
878}
879
880#[derive(Debug, Clone, PartialEq, Eq)]
882pub enum Decision {
883 TakeOver,
884 StandBy(Why),
885}
886
887impl Decision {
888 #[must_use]
890 pub fn as_str(&self) -> &'static str {
891 match self {
892 Self::TakeOver => "take_over",
893 Self::StandBy(_) => "stand_by",
894 }
895 }
896}
897
898fn premises(own: &InstanceId, read: &Read) -> Option<Why> {
901 if let Some(h) = read.holders().into_iter().find(|h| *h != own) {
902 return Some(Why::Incumbent(h.clone()));
903 }
904 if !read.complete {
905 return Some(Why::Incomplete);
906 }
907 if read.get(own).is_none() {
908 return Some(Why::OwnClaimMissing);
909 }
910 None
911}
912
913#[must_use]
919pub fn elect(own: &InstanceId, read: &Read) -> Decision {
920 if let Some(why) = premises(own, read) {
921 return Decision::StandBy(why);
922 }
923 let lowest = read
924 .instances
925 .iter()
926 .filter(|s| lower(&s.id, own) && s.descriptor != Listing::NotListed)
927 .min_by(|a, b| a.id.cmp(&b.id));
928 match lowest {
929 Some(s) if s.descriptor == Listing::Unread => {
930 Decision::StandBy(Why::DescriptorUnread(s.id.clone()))
931 }
932 Some(s) => Decision::StandBy(Why::LowerCandidate(s.id.clone())),
933 None => Decision::TakeOver,
934 }
935}
936
937#[must_use]
941pub fn elect_external(own: &InstanceId, read: &Read) -> Decision {
942 match premises(own, read) {
943 Some(why) => Decision::StandBy(why),
944 None => Decision::TakeOver,
945 }
946}
947
948#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
952pub enum Stay {
953 External,
955 NotHolding,
957 NoSplit,
959 Lowest,
961}
962
963impl Stay {
964 #[must_use]
966 pub fn as_str(self) -> &'static str {
967 match self {
968 Self::External => "external",
969 Self::NotHolding => "not_holding",
970 Self::NoSplit => "no_split",
971 Self::Lowest => "lowest",
972 }
973 }
974}
975
976#[derive(Debug, Clone, PartialEq, Eq)]
978pub enum Heal {
979 StepDown(InstanceId),
981 Stay(Stay),
982}
983
984#[must_use]
990pub fn heal(
991 own: &InstanceId,
992 election: Election,
993 first: &[InstanceId],
994 second: &[InstanceId],
995) -> Heal {
996 if election == Election::External {
997 return Heal::Stay(Stay::External);
998 }
999 let first: BTreeSet<&InstanceId> = first.iter().collect();
1000 let second: BTreeSet<&InstanceId> = second.iter().collect();
1001 if !second.contains(own) {
1002 return Heal::Stay(Stay::NotHolding);
1003 }
1004 if first.len() < 2 || second.len() < 2 {
1005 return Heal::Stay(Stay::NoSplit);
1006 }
1007 match second.into_iter().next() {
1008 Some(low) if lower(low, own) => Heal::StepDown(low.clone()),
1009 _ => Heal::Stay(Stay::Lowest),
1010 }
1011}
1012
1013#[derive(Debug, Clone, Default, PartialEq, Eq)]
1018pub struct Poll {
1019 pub appeared: Vec<InstanceId>,
1021 pub withdrawn: Vec<InstanceId>,
1024 pub next: BTreeSet<InstanceId>,
1028}
1029
1030#[must_use]
1036pub fn poll(last: &BTreeSet<InstanceId>, complete: bool, holders: &BTreeSet<InstanceId>) -> Poll {
1037 let appeared = holders.difference(last).cloned().collect();
1038 if complete {
1039 Poll {
1040 appeared,
1041 withdrawn: last.difference(holders).cloned().collect(),
1042 next: holders.clone(),
1043 }
1044 } else {
1045 Poll {
1046 appeared,
1047 withdrawn: Vec::new(),
1048 next: last.union(holders).cloned().collect(),
1049 }
1050 }
1051}
1052
1053#[derive(Debug, Clone, PartialEq, Eq)]
1057pub enum Event {
1058 Read(Read),
1060 Appeared(InstanceId),
1063 Withdrawn,
1066 Timer,
1069 Lock(bool),
1071 Reminted(InstanceId),
1076}
1077
1078#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1080pub enum StepDownWhy {
1081 LowerHolder(InstanceId),
1083 LockLost,
1085}
1086
1087impl StepDownWhy {
1088 #[must_use]
1090 pub fn as_str(&self) -> &'static str {
1091 match self {
1092 Self::LowerHolder(_) => "lower_holder",
1093 Self::LockLost => "lock_lost",
1094 }
1095 }
1096}
1097
1098#[derive(Debug, Clone, PartialEq, Eq)]
1100pub enum Step {
1101 Claim,
1105 Read,
1108 Grace,
1110 StandBy { why: Why, retry: bool },
1113 Retry,
1117 TakeOver,
1120 StepDown(StepDownWhy),
1123 Nothing,
1125}
1126
1127impl Step {
1128 #[must_use]
1130 pub fn as_str(&self) -> &'static str {
1131 match self {
1132 Self::Claim => "claim",
1133 Self::Read => "read",
1134 Self::Grace => "grace",
1135 Self::StandBy { .. } => "stand_by",
1136 Self::Retry => "retry",
1137 Self::TakeOver => "take_over",
1138 Self::StepDown(_) => "step_down",
1139 Self::Nothing => "nothing",
1140 }
1141 }
1142}
1143
1144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1146pub enum Role {
1147 Unclaimed,
1149 Standby,
1151 Serving,
1153}
1154
1155impl Role {
1156 #[must_use]
1158 pub fn as_str(self) -> &'static str {
1159 match self {
1160 Self::Unclaimed => "unclaimed",
1161 Self::Standby => "standby",
1162 Self::Serving => "serving",
1163 }
1164 }
1165}
1166
1167#[derive(Debug, Clone, PartialEq, Eq)]
1168enum Phase {
1169 New,
1170 Claiming,
1171 Campaigning,
1172 Standby {
1173 retry: bool,
1174 },
1175 TakingOver,
1176 Serving,
1177 HealFirst,
1178 HealGrace(Vec<InstanceId>),
1179 HealSecond(Vec<InstanceId>),
1180 HealRetry(Option<Vec<InstanceId>>),
1184 SteppingDown(StepDownWhy),
1185}
1186
1187#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1190struct Kept {
1191 appeared: bool,
1192 withdrawn: bool,
1193}
1194
1195#[derive(Debug, Clone)]
1210pub struct Elector {
1211 own: InstanceId,
1212 former: BTreeSet<InstanceId>,
1214 election: Election,
1215 phase: Phase,
1216 lock: bool,
1217 kept: Kept,
1218}
1219
1220impl Elector {
1221 #[must_use]
1224 pub fn new(own: InstanceId, election: Election) -> Self {
1225 Self {
1226 own,
1227 former: BTreeSet::new(),
1228 election,
1229 phase: Phase::New,
1230 lock: false,
1231 kept: Kept::default(),
1232 }
1233 }
1234
1235 #[must_use]
1237 pub fn own(&self) -> &InstanceId {
1238 &self.own
1239 }
1240
1241 #[must_use]
1244 pub fn is_own(&self, id: &InstanceId) -> bool {
1245 *id == self.own || self.former.contains(id)
1246 }
1247
1248 #[must_use]
1250 pub fn election(&self) -> Election {
1251 self.election
1252 }
1253
1254 #[must_use]
1256 pub fn role(&self) -> Role {
1257 match self.phase {
1258 Phase::New | Phase::Claiming => Role::Unclaimed,
1259 Phase::Campaigning | Phase::Standby { .. } | Phase::TakingOver => Role::Standby,
1260 Phase::Serving
1261 | Phase::HealFirst
1262 | Phase::HealGrace(_)
1263 | Phase::HealSecond(_)
1264 | Phase::HealRetry(_)
1265 | Phase::SteppingDown(_) => Role::Serving,
1266 }
1267 }
1268
1269 #[must_use]
1271 pub fn serving(&self) -> bool {
1272 self.role() == Role::Serving
1273 }
1274
1275 #[must_use]
1277 pub fn lock(&self) -> bool {
1278 self.lock
1279 }
1280
1281 pub fn start(&mut self) -> Step {
1283 if self.phase != Phase::New {
1284 return Step::Nothing;
1285 }
1286 self.phase = Phase::Claiming;
1287 Step::Claim
1288 }
1289
1290 pub fn finish(&mut self) -> Step {
1293 let step = match std::mem::replace(&mut self.phase, Phase::New) {
1294 Phase::Claiming => {
1295 self.kept = Kept::default();
1298 return self.campaign();
1299 }
1300 Phase::TakingOver => {
1301 self.phase = Phase::Serving;
1302 match self.election {
1303 Election::External if !self.lock => {
1304 self.kept = Kept::default();
1305 return self.step_down(StepDownWhy::LockLost);
1306 }
1307 _ => Step::Nothing,
1308 }
1309 }
1310 Phase::SteppingDown(_) => {
1311 self.phase = Phase::Standby { retry: false };
1312 Step::Nothing
1313 }
1314 other => {
1315 self.phase = other;
1316 return Step::Nothing;
1317 }
1318 };
1319 self.decide_kept(step)
1320 }
1321
1322 pub fn observe(&mut self, event: Event) -> Step {
1324 match event {
1325 Event::Read(r) => {
1326 let r = self.normalized(&r);
1327 self.on_read(&r)
1328 }
1329 Event::Appeared(id) => {
1330 if self.is_own(&id) {
1331 return Step::Nothing;
1332 }
1333 self.on_appeared()
1334 }
1335 Event::Withdrawn => self.on_withdrawn(),
1336 Event::Timer => self.on_timer(),
1337 Event::Lock(held) => self.on_lock(held),
1338 Event::Reminted(id) => {
1339 if id != self.own {
1342 let old = std::mem::replace(&mut self.own, id);
1343 self.former.insert(old);
1344 self.former.remove(&self.own);
1347 }
1348 Step::Nothing
1349 }
1350 }
1351 }
1352
1353 fn normalized(&self, r: &Read) -> Read {
1356 if self.former.is_empty() {
1357 return r.clone();
1358 }
1359 let mut instances = Vec::with_capacity(r.instances.len());
1360 let mut own: Option<Seen> = None;
1361 for s in &r.instances {
1362 if !self.is_own(&s.id) {
1363 instances.push(s.clone());
1364 continue;
1365 }
1366 match &mut own {
1367 None => {
1368 own = Some(Seen {
1369 id: self.own.clone(),
1370 token: s.token,
1371 descriptor: s.descriptor,
1372 });
1373 }
1374 Some(o) => {
1375 o.token |= s.token;
1376 if s.id == self.own {
1377 o.descriptor = s.descriptor;
1378 }
1379 }
1380 }
1381 }
1382 instances.extend(own);
1383 Read {
1384 complete: r.complete,
1385 instances,
1386 }
1387 }
1388
1389 fn decide_kept(&mut self, step: Step) -> Step {
1393 fn replace(step: &mut Step, next: Step) {
1394 if next != Step::Nothing && matches!(step, Step::Nothing | Step::StandBy { .. }) {
1395 *step = next;
1396 }
1397 }
1398 let kept = std::mem::take(&mut self.kept);
1399 let mut step = step;
1400 if kept.appeared {
1401 let next = self.on_appeared();
1402 replace(&mut step, next);
1403 }
1404 if kept.withdrawn {
1405 let next = self.on_withdrawn();
1406 replace(&mut step, next);
1407 }
1408 step
1409 }
1410
1411 fn campaign(&mut self) -> Step {
1413 if self.election == Election::External && !self.lock {
1414 return self.stand_by(Why::NoLock);
1415 }
1416 self.phase = Phase::Campaigning;
1417 Step::Read
1418 }
1419
1420 fn stand_by(&mut self, why: Why) -> Step {
1421 let retry = why.retries();
1422 self.phase = Phase::Standby { retry };
1423 Step::StandBy { why, retry }
1424 }
1425
1426 fn step_down(&mut self, why: StepDownWhy) -> Step {
1427 self.phase = Phase::SteppingDown(why.clone());
1428 Step::StepDown(why)
1429 }
1430
1431 fn holding(&self, r: &Read) -> Vec<InstanceId> {
1433 let mut h = r.holders_owned();
1434 if !h.contains(&self.own) {
1435 h.push(self.own.clone());
1436 h.sort();
1437 }
1438 h
1439 }
1440
1441 fn on_read(&mut self, r: &Read) -> Step {
1442 let step = match self.phase.clone() {
1443 Phase::Campaigning => {
1444 let decision = match self.election {
1445 Election::Claim => elect(&self.own, r),
1446 Election::External if !self.lock => Decision::StandBy(Why::NoLock),
1447 Election::External => elect_external(&self.own, r),
1448 };
1449 match decision {
1450 Decision::TakeOver => {
1451 self.phase = Phase::TakingOver;
1452 Step::TakeOver
1453 }
1454 Decision::StandBy(why) => self.stand_by(why),
1455 }
1456 }
1457 Phase::HealFirst => {
1458 let holders = self.holding(r);
1459 if holders.len() >= 2 {
1460 self.phase = Phase::HealGrace(holders);
1461 Step::Grace
1462 } else if r.complete {
1463 self.phase = Phase::Serving;
1464 Step::Nothing
1465 } else {
1466 self.phase = Phase::HealRetry(None);
1469 Step::Retry
1470 }
1471 }
1472 Phase::HealSecond(first) => {
1473 let second = self.holding(r);
1474 match heal(&self.own, self.election, &first, &second) {
1475 Heal::StepDown(low) => self.step_down(StepDownWhy::LowerHolder(low)),
1476 Heal::Stay(Stay::NoSplit) if !r.complete => {
1477 self.phase = Phase::HealRetry(Some(first));
1478 Step::Retry
1479 }
1480 Heal::Stay(_) => {
1481 self.phase = Phase::Serving;
1482 Step::Nothing
1483 }
1484 }
1485 }
1486 _ => return Step::Nothing,
1487 };
1488 self.decide_kept(step)
1489 }
1490
1491 fn on_appeared(&mut self) -> Step {
1494 if self.election != Election::Claim {
1495 return Step::Nothing;
1496 }
1497 match self.phase {
1498 Phase::Serving => {
1499 self.phase = Phase::HealFirst;
1500 Step::Read
1501 }
1502 Phase::Campaigning | Phase::TakingOver | Phase::HealFirst | Phase::HealSecond(_) => {
1503 self.kept.appeared = true;
1504 Step::Nothing
1505 }
1506 _ => Step::Nothing,
1507 }
1508 }
1509
1510 fn on_withdrawn(&mut self) -> Step {
1511 match self.phase {
1512 Phase::Standby { .. } => {
1513 if self.election == Election::External && !self.lock {
1514 Step::Nothing
1515 } else {
1516 self.campaign()
1517 }
1518 }
1519 Phase::Campaigning
1520 | Phase::SteppingDown(_)
1521 | Phase::HealFirst
1522 | Phase::HealSecond(_) => {
1523 self.kept.withdrawn = true;
1524 Step::Nothing
1525 }
1526 _ => Step::Nothing,
1527 }
1528 }
1529
1530 fn on_timer(&mut self) -> Step {
1531 match self.phase.clone() {
1532 Phase::Standby { retry: true } => self.campaign(),
1533 Phase::HealGrace(first) => {
1534 self.phase = Phase::HealSecond(first);
1535 Step::Read
1536 }
1537 Phase::HealRetry(first) => {
1538 self.phase = match first {
1539 None => Phase::HealFirst,
1540 Some(first) => Phase::HealSecond(first),
1541 };
1542 Step::Read
1543 }
1544 _ => Step::Nothing,
1545 }
1546 }
1547
1548 fn on_lock(&mut self, held: bool) -> Step {
1549 if self.election != Election::External {
1550 return Step::Nothing;
1551 }
1552 self.lock = held;
1553 match self.phase {
1554 Phase::Standby { .. } if held => self.campaign(),
1555 Phase::Serving if !held => self.step_down(StepDownWhy::LockLost),
1556 _ => Step::Nothing,
1557 }
1558 }
1559}
1560
1561#[derive(Debug, Clone, PartialEq, Eq)]
1566pub struct Reading {
1567 pub across_face: bool,
1569 pub governance: Governance,
1570 pub first: Read,
1571 pub second: Read,
1572}
1573
1574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1576pub enum Answer {
1577 Yes,
1578 No,
1579 Unobservable,
1581 NotAsked,
1583 NotThisProfiles,
1585}
1586
1587impl Answer {
1588 #[must_use]
1590 pub fn as_str(self) -> &'static str {
1591 match self {
1592 Self::Yes => "yes",
1593 Self::No => "no",
1594 Self::Unobservable => "unobservable",
1595 Self::NotAsked => "not_asked",
1596 Self::NotThisProfiles => "not_this_profiles",
1597 }
1598 }
1599}
1600
1601impl fmt::Display for Answer {
1602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1603 f.write_str(self.as_str())
1604 }
1605}
1606
1607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1609pub enum Reason {
1610 AcrossFace,
1611 NotGoverned,
1612 NoContract,
1613 RevisionsDisagree,
1614 Absent,
1615 PresenceIncomplete,
1616 Split,
1617 InTransition,
1618 One,
1619 NoDescriptor,
1620 NoCandidate,
1621 Vacant,
1622 Held,
1623 Lasting,
1624 StandingBy,
1625 NoneStanding,
1626 SplitLowest,
1627 NotACandidate,
1628 Unlisted,
1629 Incumbent,
1630 MarkedHolding,
1631 Standby,
1632 Unmarked,
1633}
1634
1635impl Reason {
1636 #[must_use]
1638 pub fn as_str(self) -> &'static str {
1639 match self {
1640 Self::AcrossFace => "across_face",
1641 Self::NotGoverned => "not_governed",
1642 Self::NoContract => "no_contract",
1643 Self::RevisionsDisagree => "revisions_disagree",
1644 Self::Absent => "absent",
1645 Self::PresenceIncomplete => "presence_incomplete",
1646 Self::Split => "split",
1647 Self::InTransition => "in_transition",
1648 Self::One => "one",
1649 Self::NoDescriptor => "no_descriptor",
1650 Self::NoCandidate => "no_candidate",
1651 Self::Vacant => "vacant",
1652 Self::Held => "held",
1653 Self::Lasting => "lasting",
1654 Self::StandingBy => "standing_by",
1655 Self::NoneStanding => "none",
1656 Self::SplitLowest => "split_lowest",
1657 Self::NotACandidate => "not_a_candidate",
1658 Self::Unlisted => "unlisted",
1659 Self::Incumbent => "incumbent",
1660 Self::MarkedHolding => "marked_holding",
1661 Self::Standby => "standby",
1662 Self::Unmarked => "unmarked",
1663 }
1664 }
1665}
1666
1667impl fmt::Display for Reason {
1668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669 f.write_str(self.as_str())
1670 }
1671}
1672
1673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1675pub struct Judged {
1676 pub answer: Answer,
1677 pub reason: Reason,
1678}
1679
1680impl Judged {
1681 const fn new(answer: Answer, reason: Reason) -> Self {
1682 Self { answer, reason }
1683 }
1684}
1685
1686#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1688pub struct Count {
1689 pub count: usize,
1690 pub exact: bool,
1691}
1692
1693fn premises_of(r: &Reading, present: bool) -> Result<(), Judged> {
1696 use Answer::{NotAsked, NotThisProfiles, Unobservable};
1697 if r.across_face {
1698 return Err(Judged::new(Unobservable, Reason::AcrossFace));
1699 }
1700 if !present {
1701 return Err(if r.second.complete {
1702 Judged::new(NotAsked, Reason::Absent)
1703 } else {
1704 Judged::new(Unobservable, Reason::PresenceIncomplete)
1705 });
1706 }
1707 match r.governance {
1708 Governance::Governed(_) => Ok(()),
1709 Governance::NotGoverned => Err(Judged::new(NotThisProfiles, Reason::NotGoverned)),
1710 Governance::NoContract => Err(Judged::new(Unobservable, Reason::NoContract)),
1711 Governance::Disagree => Err(Judged::new(Unobservable, Reason::RevisionsDisagree)),
1712 }
1713}
1714
1715fn address_premises(r: &Reading) -> Result<(), Judged> {
1716 premises_of(r, !r.second.instances.is_empty())
1717}
1718
1719fn no_candidate(read: &Read) -> Option<Judged> {
1722 if read.instances.iter().any(|s| s.descriptor.lists()) {
1723 return None;
1724 }
1725 Some(
1726 if read
1727 .instances
1728 .iter()
1729 .any(|s| s.descriptor == Listing::Unread)
1730 {
1731 Judged::new(Answer::Unobservable, Reason::NoDescriptor)
1732 } else {
1733 Judged::new(Answer::NotAsked, Reason::NoCandidate)
1734 },
1735 )
1736}
1737
1738#[must_use]
1741pub fn one_incumbent(r: &Reading) -> Judged {
1742 use Answer::{No, Unobservable, Yes};
1743 if let Err(j) = address_premises(r) {
1744 return j;
1745 }
1746 let h1 = r.first.holders().len();
1747 let h2 = r.second.holders().len();
1748 if h1 >= 2 && h2 >= 2 {
1749 return Judged::new(No, Reason::Split);
1750 }
1751 if h2 >= 2 {
1752 return Judged::new(Unobservable, Reason::InTransition);
1753 }
1754 if h2 == 1 {
1755 return if r.second.complete {
1756 Judged::new(Yes, Reason::One)
1757 } else {
1758 Judged::new(Unobservable, Reason::PresenceIncomplete)
1759 };
1760 }
1761 if !r.second.complete {
1762 return Judged::new(Unobservable, Reason::PresenceIncomplete);
1763 }
1764 if let Some(j) = no_candidate(&r.second) {
1765 return j;
1766 }
1767 if h1 >= 1 {
1768 return Judged::new(Unobservable, Reason::InTransition);
1769 }
1770 if !r.first.complete {
1771 return Judged::new(Unobservable, Reason::PresenceIncomplete);
1772 }
1773 Judged::new(No, Reason::Vacant)
1774}
1775
1776#[must_use]
1779pub fn vacancy(r: &Reading) -> Judged {
1780 use Answer::{No, Unobservable, Yes};
1781 if let Err(j) = address_premises(r) {
1782 return j;
1783 }
1784 if !r.second.holders().is_empty() {
1785 return Judged::new(No, Reason::Held);
1786 }
1787 if !r.second.complete {
1788 return Judged::new(Unobservable, Reason::PresenceIncomplete);
1789 }
1790 if let Some(j) = no_candidate(&r.second) {
1791 return j;
1792 }
1793 if r.first.complete && r.first.holders().is_empty() {
1794 Judged::new(Yes, Reason::Lasting)
1795 } else {
1796 Judged::new(Yes, Reason::Vacant)
1797 }
1798}
1799
1800#[must_use]
1804pub fn standbys(r: &Reading) -> (Judged, Count) {
1805 use Answer::{No, Unobservable, Yes};
1806 let unknown = Count {
1807 count: 0,
1808 exact: false,
1809 };
1810 if let Err(j) = address_premises(r) {
1811 return (j, unknown);
1812 }
1813 let read = &r.second;
1814 let n = read
1815 .instances
1816 .iter()
1817 .filter(|s| !s.token && s.descriptor == Listing::Listed { standby: true })
1818 .count();
1819 let unread = read
1820 .instances
1821 .iter()
1822 .any(|s| s.descriptor == Listing::Unread);
1823 if n >= 1 {
1824 return (
1825 Judged::new(Yes, Reason::StandingBy),
1826 Count {
1827 count: n,
1828 exact: read.complete && !unread,
1829 },
1830 );
1831 }
1832 if !read.complete {
1833 return (
1834 Judged::new(Unobservable, Reason::PresenceIncomplete),
1835 unknown,
1836 );
1837 }
1838 if unread {
1839 return (Judged::new(Unobservable, Reason::NoDescriptor), unknown);
1840 }
1841 (
1842 Judged::new(No, Reason::NoneStanding),
1843 Count {
1844 count: 0,
1845 exact: true,
1846 },
1847 )
1848}
1849
1850#[must_use]
1853pub fn twin(r: &Reading, x: &InstanceId) -> Judged {
1854 use Answer::{No, NotAsked, Unobservable, Yes};
1855 let x2 = r.second.get(x);
1856 if let Err(j) = premises_of(r, x2.is_some()) {
1857 return j;
1858 }
1859 let Some(x2) = x2 else {
1860 return Judged::new(NotAsked, Reason::Absent);
1861 };
1862 let x1 = r.first.get(x);
1863 let h1 = r.first.holders();
1864 let h2 = r.second.holders();
1865 let same = x1.is_some_and(|a| a.token == x2.token && a.descriptor == x2.descriptor);
1866 if x2.token && x1.is_some_and(|a| a.token) && h1.len() >= 2 && h2.len() >= 2 {
1867 return if h2.first() == Some(&x) {
1868 Judged::new(Yes, Reason::SplitLowest)
1869 } else {
1870 Judged::new(Yes, Reason::Split)
1871 };
1872 }
1873 match x2.descriptor {
1874 Listing::Unread => Judged::new(Unobservable, Reason::NoDescriptor),
1875 Listing::NotListed if !x2.token => Judged::new(NotAsked, Reason::NotACandidate),
1876 Listing::NotListed if same => Judged::new(Yes, Reason::Unlisted),
1877 Listing::NotListed => Judged::new(Unobservable, Reason::InTransition),
1878 Listing::Listed { standby } if x2.token => {
1879 if h2.len() >= 2 {
1880 Judged::new(Unobservable, Reason::InTransition)
1881 } else if standby {
1882 if same {
1883 Judged::new(Yes, Reason::MarkedHolding)
1884 } else {
1885 Judged::new(Unobservable, Reason::InTransition)
1886 }
1887 } else if r.second.complete {
1888 Judged::new(No, Reason::Incumbent)
1889 } else {
1890 Judged::new(Unobservable, Reason::PresenceIncomplete)
1891 }
1892 }
1893 Listing::Listed { standby: true } => {
1894 if r.second.complete {
1895 Judged::new(No, Reason::Standby)
1896 } else {
1897 Judged::new(Unobservable, Reason::PresenceIncomplete)
1898 }
1899 }
1900 Listing::Listed { standby: false } => {
1901 if !same {
1902 Judged::new(Unobservable, Reason::InTransition)
1903 } else if r.first.complete && r.second.complete {
1904 Judged::new(Yes, Reason::Unmarked)
1905 } else {
1906 Judged::new(Unobservable, Reason::PresenceIncomplete)
1907 }
1908 }
1909 }
1910}
1911
1912#[cfg(test)]
1913mod tests {
1914 use super::*;
1915
1916 fn id(n: u64) -> InstanceId {
1917 InstanceId::from_u64(n)
1918 }
1919
1920 fn seen(n: u64, token: bool, descriptor: Listing) -> Seen {
1921 Seen {
1922 id: id(n),
1923 token,
1924 descriptor,
1925 }
1926 }
1927
1928 const STANDBY: Listing = Listing::Listed { standby: true };
1929 const SERVING: Listing = Listing::Listed { standby: false };
1930
1931 fn read(complete: bool, instances: Vec<Seen>) -> Read {
1932 Read {
1933 complete,
1934 instances,
1935 }
1936 }
1937
1938 #[test]
1939 fn ids_compare_as_unsigned_integers() {
1940 assert!(lower(&id(0x9), &id(0xa)));
1941 assert!(lower(&id(0xff), &id(0x100)));
1942 assert!(!lower(&id(5), &id(5)));
1943 }
1944
1945 #[test]
1946 fn a_live_incumbent_wins_whatever_the_read() {
1947 let r = read(false, vec![seen(9, true, Listing::Unread)]);
1948 assert_eq!(elect(&id(1), &r), Decision::StandBy(Why::Incumbent(id(9))));
1949 }
1950
1951 #[test]
1952 fn the_lowest_candidate_wins_a_complete_read() {
1953 let own = id(5);
1954 let r = read(true, vec![seen(5, false, STANDBY), seen(7, false, STANDBY)]);
1955 assert_eq!(elect(&own, &r), Decision::TakeOver);
1956 let r = read(
1957 true,
1958 vec![
1959 seen(2, false, Listing::NotListed),
1960 seen(3, false, STANDBY),
1961 seen(5, false, STANDBY),
1962 ],
1963 );
1964 assert_eq!(
1965 elect(&own, &r),
1966 Decision::StandBy(Why::LowerCandidate(id(3)))
1967 );
1968 let r = read(true, vec![seen(3, false, STANDBY)]);
1969 assert_eq!(elect(&own, &r), Decision::StandBy(Why::OwnClaimMissing));
1970 }
1971
1972 #[test]
1973 fn a_split_leaves_the_lowest() {
1974 let two = [id(2), id(8)];
1975 assert_eq!(
1976 heal(&id(8), Election::Claim, &two, &two),
1977 Heal::StepDown(id(2))
1978 );
1979 assert_eq!(
1980 heal(&id(2), Election::Claim, &two, &two),
1981 Heal::Stay(Stay::Lowest)
1982 );
1983 assert_eq!(
1984 heal(&id(8), Election::External, &two, &two),
1985 Heal::Stay(Stay::External)
1986 );
1987 assert_eq!(
1988 heal(&id(8), Election::Claim, &[id(8)], &two),
1989 Heal::Stay(Stay::NoSplit)
1990 );
1991 }
1992
1993 #[test]
1994 fn a_standby_takes_over_at_a_vacancy_and_steps_down_to_a_lower_one() {
1995 let mut e = Elector::new(id(8), Election::Claim);
1996 assert_eq!(e.start(), Step::Claim);
1997 assert_eq!(e.finish(), Step::Read);
1998 let incumbent = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
1999 assert_eq!(
2000 e.observe(Event::Read(incumbent)),
2001 Step::StandBy {
2002 why: Why::Incumbent(id(4)),
2003 retry: false
2004 }
2005 );
2006 assert_eq!(e.role(), Role::Standby);
2007 assert_eq!(e.observe(Event::Timer), Step::Nothing);
2008 assert_eq!(e.observe(Event::Withdrawn), Step::Read);
2009 let vacant = read(true, vec![seen(8, false, STANDBY)]);
2010 assert_eq!(e.observe(Event::Read(vacant)), Step::TakeOver);
2011 assert_eq!(e.finish(), Step::Nothing);
2012 assert!(e.serving());
2013 assert_eq!(e.observe(Event::Appeared(id(2))), Step::Read);
2014 let split = read(false, vec![seen(2, true, SERVING), seen(8, true, SERVING)]);
2015 assert_eq!(e.observe(Event::Read(split.clone())), Step::Grace);
2016 assert_eq!(e.observe(Event::Timer), Step::Read);
2017 assert_eq!(
2018 e.observe(Event::Read(split)),
2019 Step::StepDown(StepDownWhy::LowerHolder(id(2)))
2020 );
2021 assert_eq!(e.finish(), Step::Nothing);
2022 assert_eq!(e.role(), Role::Standby);
2023 }
2024
2025 #[test]
2026 fn external_serves_only_with_its_lock() {
2027 let mut e = Elector::new(id(1), Election::External);
2028 assert_eq!(e.start(), Step::Claim);
2029 assert_eq!(
2030 e.finish(),
2031 Step::StandBy {
2032 why: Why::NoLock,
2033 retry: false
2034 }
2035 );
2036 assert_eq!(e.observe(Event::Withdrawn), Step::Nothing);
2037 assert_eq!(e.observe(Event::Lock(true)), Step::Read);
2038 let alone = read(true, vec![seen(1, false, STANDBY), seen(9, false, STANDBY)]);
2039 assert_eq!(e.observe(Event::Read(alone)), Step::TakeOver);
2040 assert_eq!(e.finish(), Step::Nothing);
2041 assert_eq!(e.observe(Event::Appeared(id(0))), Step::Nothing);
2042 assert_eq!(
2043 e.observe(Event::Lock(false)),
2044 Step::StepDown(StepDownWhy::LockLost)
2045 );
2046 }
2047
2048 #[test]
2057 fn a_read_asked_is_never_asked_again_before_its_answer() {
2058 use std::collections::{HashSet, VecDeque};
2059 let own = id(0xb);
2060 let reads = [
2061 read(true, vec![seen(0xb, false, STANDBY)]),
2062 read(
2063 true,
2064 vec![seen(0xa, true, SERVING), seen(0xb, false, STANDBY)],
2065 ),
2066 read(false, vec![]),
2067 read(
2068 true,
2069 vec![seen(0xa, true, SERVING), seen(0xb, true, SERVING)],
2070 ),
2071 read(false, vec![seen(0xb, true, SERVING)]),
2072 read(
2073 true,
2074 vec![seen(0x1, false, STANDBY), seen(0xb, false, STANDBY)],
2075 ),
2076 read(true, vec![seen(0xb, true, SERVING)]),
2077 ];
2078 let others = [
2079 Event::Appeared(id(0xa)),
2080 Event::Appeared(own.clone()),
2081 Event::Withdrawn,
2082 Event::Timer,
2083 Event::Lock(true),
2084 Event::Lock(false),
2085 Event::Reminted(id(0xc)),
2086 ];
2087 for election in [Election::Claim, Election::External] {
2088 let mut e = Elector::new(own.clone(), election);
2089 assert_eq!(e.start(), Step::Claim);
2090 let mut queue = VecDeque::from([(e.clone(), false, true)]);
2092 let mut seen_states = HashSet::new();
2093 let mut asked_states = 0;
2094 while let Some((e, asked, acting)) = queue.pop_front() {
2095 if !seen_states.insert(format!("{e:?} {asked} {acting}")) {
2096 continue;
2097 }
2098 let mut next = |e: Elector, step: Step, was_asked: bool| {
2099 let act = matches!(step, Step::Claim | Step::TakeOver | Step::StepDown(_));
2100 let asks = step == Step::Read;
2101 assert!(
2102 !(was_asked && asks),
2103 "{election}: a second read asked while one runs: {e:?}"
2104 );
2105 queue.push_back((e, was_asked || asks, act));
2106 };
2107 if acting {
2108 let mut e2 = e.clone();
2109 let step = e2.finish();
2110 next(e2, step, asked);
2111 continue;
2112 }
2113 if asked {
2114 asked_states += 1;
2115 for ev in &others {
2116 let mut e2 = e.clone();
2117 let step = e2.observe(ev.clone());
2118 assert_eq!(
2119 step,
2120 Step::Nothing,
2121 "{election}: {ev:?} while a read runs, in {e:?}"
2122 );
2123 assert_eq!(e2.finish(), Step::Nothing, "no act runs while a read does");
2124 next(e2, Step::Nothing, true);
2125 }
2126 for r in &reads {
2127 let mut e2 = e.clone();
2128 let step = e2.observe(Event::Read(r.clone()));
2129 next(e2, step, false);
2131 }
2132 } else {
2133 for ev in &others {
2134 let mut e2 = e.clone();
2135 let step = e2.observe(ev.clone());
2136 next(e2, step, false);
2137 }
2138 }
2139 }
2140 assert!(
2141 asked_states > 0,
2142 "{election}: the exploration reached reads asked"
2143 );
2144 }
2145 }
2146
2147 #[test]
2148 fn a_tool_tells_a_standby_from_a_twin() {
2149 let one = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
2150 let r = Reading {
2151 across_face: false,
2152 governance: Governance::Governed(Election::Claim),
2153 first: one.clone(),
2154 second: one,
2155 };
2156 assert_eq!(one_incumbent(&r).reason, Reason::One);
2157 assert_eq!(vacancy(&r).reason, Reason::Held);
2158 assert_eq!(
2159 standbys(&r).1,
2160 Count {
2161 count: 1,
2162 exact: true
2163 }
2164 );
2165 assert_eq!(twin(&r, &id(4)).reason, Reason::Incumbent);
2166 assert_eq!(twin(&r, &id(8)).reason, Reason::Standby);
2167 let split = read(false, vec![seen(4, true, SERVING), seen(8, true, SERVING)]);
2168 let r = Reading {
2169 first: split.clone(),
2170 second: split,
2171 ..r
2172 };
2173 assert_eq!(one_incumbent(&r).reason, Reason::Split);
2174 assert_eq!(twin(&r, &id(4)).reason, Reason::SplitLowest);
2175 assert_eq!(twin(&r, &id(8)).reason, Reason::Split);
2176 }
2177}