1use std::collections::{BTreeMap, BTreeSet};
54use std::fmt;
55use std::time::Duration;
56
57use serde_json::Value;
58
59use crate::authoring::{Kind, RequireCardinality};
60use crate::contract::{Contract, Requirement};
61use crate::grammar::{Addr, IfaceId, InstanceId, KeyError, KindToken, Name, ZkKey, parse};
62use crate::redundancy::Heard;
63use crate::template::Template;
64use crate::timing::{self, MemberState, Mono, Tracker};
65
66pub const PROFILE: &str = "arbitration.v1";
68
69pub const NAME: &str = "arbitration";
71
72pub const POLICY: &str = "arbitration.policy";
74
75pub const VOCABULARY: &[&str] = &["policy"];
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub enum Policy {
85 Priority,
87}
88
89impl Policy {
90 #[must_use]
92 pub fn as_str(self) -> &'static str {
93 match self {
94 Self::Priority => "priority",
95 }
96 }
97}
98
99impl fmt::Display for Policy {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str(self.as_str())
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub enum Invalid {
108 NotUsed,
111 ManifestRole,
113 PolicyUnsupported,
115 Value,
117 Cardinality,
119 Resource,
121 NoDeadline,
123 ParamsUnbound,
125 Framed,
128}
129
130impl Invalid {
131 #[must_use]
133 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::NotUsed => "not_used",
136 Self::ManifestRole => "manifest_role",
137 Self::PolicyUnsupported => "policy_unsupported",
138 Self::Value => "value",
139 Self::Cardinality => "cardinality",
140 Self::Resource => "resource",
141 Self::NoDeadline => "no_deadline",
142 Self::ParamsUnbound => "params_unbound",
143 Self::Framed => "framed",
144 }
145 }
146
147 #[must_use]
149 pub fn says(self) -> &'static str {
150 match self {
151 Self::NotUsed => "arbitration.policy is written, and uses does not list arbitration.v1",
152 Self::ManifestRole => {
153 "only a contract's role is arbitrated: a manifest's role reaches no descriptor with its policy"
154 }
155 Self::PolicyUnsupported => {
156 "freshest and lease are reserved; arbitration.v1 1.0 defines priority only"
157 }
158 Self::Value => "arbitration.policy is the string priority",
159 Self::Cardinality => "an arbitrated role has cardinality many",
160 Self::Resource => "an arbitrated role consumes exactly one stream resource",
161 Self::NoDeadline => {
162 "the role's stream declares a timing.v1 deadline, at or above its period"
163 }
164 Self::ParamsUnbound => {
165 "every parameter of the role's stream is bound by the role's parameter bindings"
166 }
167 Self::Framed => {
168 "a frame resource is never an arbitrated role's stream: its put carries several records"
169 }
170 }
171 }
172}
173
174impl fmt::Display for Invalid {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.write_str(self.says())
177 }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct Arbitrated {
183 pub policy: Policy,
184 pub iface: IfaceId,
186 pub token: KindToken,
189 pub template: Template,
190 pub deadline: Duration,
192 pub period: Option<Duration>,
194}
195
196impl Arbitrated {
197 #[must_use]
199 pub fn resource(&self) -> String {
200 format!("{}/{}", self.token.as_str(), self.template.as_str())
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum Declaration {
207 NotArbitrated,
210 Unread,
212 Invalid(Vec<Invalid>),
214 Arbitrated(Arbitrated),
216}
217
218impl Declaration {
219 #[must_use]
221 pub fn as_str(&self) -> &'static str {
222 match self {
223 Self::NotArbitrated => "not_arbitrated",
224 Self::Unread => "unread",
225 Self::Invalid(_) => "invalid",
226 Self::Arbitrated(_) => "arbitrated",
227 }
228 }
229
230 #[must_use]
232 pub fn arbitrated(&self) -> Option<&Arbitrated> {
233 match self {
234 Self::Arbitrated(a) => Some(a),
235 _ => None,
236 }
237 }
238
239 #[must_use]
241 pub fn carries_policy(&self) -> bool {
242 !matches!(self, Self::NotArbitrated)
243 }
244}
245
246#[derive(Debug, Clone, Copy)]
248pub struct Role<'a> {
249 pub declared_by: Option<&'a [IfaceId]>,
252 pub resources: Option<&'a [String]>,
254 pub cardinality: RequireCardinality,
255 pub annotations: &'a BTreeMap<String, Value>,
256}
257
258impl<'a> Role<'a> {
259 #[must_use]
261 pub fn of(declaring: &'a Contract, req: &'a Requirement) -> Self {
262 Self {
263 declared_by: Some(declaring.uses.as_slice()),
264 resources: req.resources.as_deref(),
265 cardinality: req.cardinality,
266 annotations: &req.annotations,
267 }
268 }
269
270 #[must_use]
272 pub fn of_manifest(req: &'a Requirement) -> Self {
273 Self {
274 declared_by: None,
275 resources: req.resources.as_deref(),
276 cardinality: req.cardinality,
277 annotations: &req.annotations,
278 }
279 }
280}
281
282#[derive(Debug, Clone, Copy)]
284pub struct Offered<'a> {
285 pub token: KindToken,
286 pub template: &'a Template,
287 pub annotations: &'a BTreeMap<String, Value>,
289 pub frame: bool,
292}
293
294#[derive(Debug, Clone)]
296pub struct Revision<'a> {
297 pub iface: &'a IfaceId,
298 pub resources: Vec<Offered<'a>>,
299}
300
301impl<'a> Revision<'a> {
302 #[must_use]
304 pub fn of(c: &'a Contract) -> Self {
305 Self {
306 iface: &c.iface,
307 resources: c
308 .resources
309 .iter()
310 .map(|r| Offered {
311 token: r.token,
312 template: &r.template,
313 annotations: &r.annotations,
314 frame: matches!(&r.body, crate::contract::Body::Data(d) if d.frame.is_some()),
315 })
316 .collect(),
317 }
318 }
319}
320
321fn kind_of(token: KindToken) -> Kind {
323 match token {
324 KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
325 KindToken::State | KindToken::ExplicitState => Kind::State,
326 KindToken::Events => Kind::Event,
327 KindToken::Op => Kind::Operation,
328 }
329}
330
331#[must_use]
338pub fn deadline_of(r: &Offered<'_>) -> Option<(Duration, Option<Duration>)> {
339 let d = match timing::declaration(kind_of(r.token), r.annotations) {
340 timing::Declaration::Declared(d) => d,
341 _ => return None,
342 };
343 Some((d.judged_deadline()?, d.period))
344}
345
346#[must_use]
352pub fn declaration(
353 role: &Role<'_>,
354 provider: Option<&Revision<'_>>,
355 params: &BTreeMap<String, String>,
356) -> Declaration {
357 let Some(policy) = role.annotations.get(POLICY) else {
358 return Declaration::NotArbitrated;
359 };
360 let mut why = Vec::new();
361 match role.declared_by {
362 Some(uses) => {
363 let v1 = uses.iter().any(|u| u.name() == NAME && u.major() == 1);
364 let any = uses.iter().any(|u| u.name() == NAME);
365 if any && !v1 {
366 return Declaration::NotArbitrated;
368 }
369 if !any {
370 why.push(Invalid::NotUsed);
371 }
372 }
373 None => why.push(Invalid::ManifestRole),
374 }
375 match policy.as_str() {
376 Some("priority") => {}
377 Some("freshest" | "lease") => why.push(Invalid::PolicyUnsupported),
378 _ => why.push(Invalid::Value),
379 }
380 if role.cardinality != RequireCardinality::Many {
381 why.push(Invalid::Cardinality);
382 }
383 let Some(rev) = provider else {
384 return if why.is_empty() {
385 Declaration::Unread
386 } else {
387 Declaration::Invalid(why)
388 };
389 };
390 let consumed: Vec<&Offered<'_>> = rev
391 .resources
392 .iter()
393 .filter(|r| match role.resources {
394 None => true,
395 Some(names) => names.iter().any(|n| n == r.template.as_str()),
396 })
397 .collect();
398 let counted: Vec<&Offered<'_>> = consumed.iter().copied().filter(|r| !r.frame).collect();
401 let one = match counted.as_slice() {
402 [r] if matches!(r.token, KindToken::Stream | KindToken::ExplicitStream) => Some(*r),
403 _ => {
404 why.push(Invalid::Resource);
405 None
406 }
407 };
408 let mut deadline = None;
409 if let Some(r) = one {
410 deadline = deadline_of(r);
411 if deadline.is_none() {
412 why.push(Invalid::NoDeadline);
413 }
414 if r.template.params().any(|(p, _)| !params.contains_key(p)) {
415 why.push(Invalid::ParamsUnbound);
416 }
417 }
418 let plain_stream = counted
420 .iter()
421 .any(|r| matches!(r.token, KindToken::Stream | KindToken::ExplicitStream));
422 if consumed.iter().any(|r| r.frame) && !plain_stream {
423 why.push(Invalid::Framed);
424 }
425 match (one, deadline) {
426 (Some(r), Some((deadline, period))) if why.is_empty() => {
427 Declaration::Arbitrated(Arbitrated {
428 policy: Policy::Priority,
429 iface: rev.iface.clone(),
430 token: r.token,
431 template: r.template.clone(),
432 deadline,
433 period,
434 })
435 }
436 _ => Declaration::Invalid(why),
437 }
438}
439
440#[must_use]
444pub fn declaration_of(
445 declaring: &Contract,
446 role: &str,
447 provider: Option<&Contract>,
448 params: &BTreeMap<String, String>,
449) -> Option<Declaration> {
450 let req = declaring.requires.get(role)?;
451 let rev = provider.map(Revision::of);
452 Some(declaration(&Role::of(declaring, req), rev.as_ref(), params))
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Hash)]
460pub struct Entry {
461 system: Option<Name>,
463 service: Option<Name>,
464}
465
466impl Entry {
467 pub fn parse(s: &str) -> Result<Self, KeyError> {
469 let (sys, svc) = s.split_once('/').ok_or(KeyError::Shape(
470 s.to_owned(),
471 "a binding entry is <system>/<service>",
472 ))?;
473 let chunk = |what: &'static str, c: &str| -> Result<Option<Name>, KeyError> {
474 if c == "*" {
475 Ok(None)
476 } else {
477 Name::new(what, c).map(Some)
478 }
479 };
480 Ok(Self {
481 system: chunk("system", sys)?,
482 service: chunk("service", svc)?,
483 })
484 }
485
486 #[must_use]
488 pub fn is_wildcard(&self) -> bool {
489 self.system.is_none() || self.service.is_none()
490 }
491
492 #[must_use]
494 pub fn exact(&self) -> Option<Addr> {
495 Some(Addr {
496 system: self.system.clone()?,
497 service: self.service.clone()?,
498 })
499 }
500
501 #[must_use]
503 pub fn matches(&self, a: &Addr) -> bool {
504 self.system.as_ref().is_none_or(|s| *s == a.system)
505 && self.service.as_ref().is_none_or(|s| *s == a.service)
506 }
507
508 #[must_use]
511 pub fn covers(&self, later: &Entry) -> bool {
512 fn chunk(a: Option<&Name>, b: Option<&Name>) -> bool {
513 match (a, b) {
514 (None, _) => true,
515 (Some(a), Some(b)) => a == b,
516 (Some(_), None) => false,
517 }
518 }
519 chunk(self.system.as_ref(), later.system.as_ref())
520 && chunk(self.service.as_ref(), later.service.as_ref())
521 }
522}
523
524impl fmt::Display for Entry {
525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 let c = |n: &Option<Name>| n.as_ref().map_or("*", Name::as_str).to_owned();
527 write!(f, "{}/{}", c(&self.system), c(&self.service))
528 }
529}
530
531#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
535pub struct Rank {
536 entry: usize,
537 system: String,
538 service: String,
539}
540
541impl Rank {
542 #[must_use]
544 pub fn entry(&self) -> usize {
545 self.entry
546 }
547}
548
549#[derive(Debug, Clone, PartialEq, Eq, Default)]
551pub struct Binding {
552 entries: Vec<Entry>,
553}
554
555impl Binding {
556 pub fn parse<S: AsRef<str>>(entries: &[S]) -> Result<Self, KeyError> {
558 Ok(Self {
559 entries: entries
560 .iter()
561 .map(|e| Entry::parse(e.as_ref()))
562 .collect::<Result<_, _>>()?,
563 })
564 }
565
566 #[must_use]
568 pub fn entries(&self) -> &[Entry] {
569 &self.entries
570 }
571
572 #[must_use]
574 pub fn is_empty(&self) -> bool {
575 self.entries.is_empty()
576 }
577
578 #[must_use]
580 pub fn rank(&self, a: &Addr) -> Option<Rank> {
581 let entry = self.entries.iter().position(|e| e.matches(a))?;
582 Some(Rank {
583 entry,
584 system: a.system.as_str().to_owned(),
585 service: a.service.as_str().to_owned(),
586 })
587 }
588
589 #[must_use]
592 pub fn ranked<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
593 let mut by: BTreeMap<Rank, Addr> = BTreeMap::new();
594 let mut add = |a: &Addr| {
595 if let Some(r) = self.rank(a) {
596 by.entry(r).or_insert_with(|| a.clone());
597 }
598 };
599 for a in self.entries.iter().filter_map(Entry::exact) {
600 add(&a);
601 }
602 for a in heard {
603 add(a);
604 }
605 by.into_values().collect()
606 }
607
608 #[must_use]
611 pub fn unbound<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
612 heard
613 .into_iter()
614 .filter(|a| self.rank(a).is_none())
615 .cloned()
616 .collect::<BTreeSet<_>>()
617 .into_iter()
618 .collect()
619 }
620
621 #[must_use]
623 pub fn wildcards(&self) -> Vec<usize> {
624 self.entries
625 .iter()
626 .enumerate()
627 .filter(|(_, e)| e.is_wildcard())
628 .map(|(i, _)| i)
629 .collect()
630 }
631
632 #[must_use]
635 pub fn shadowed(&self) -> Vec<usize> {
636 (0..self.entries.len())
637 .filter(|&j| self.entries[..j].iter().any(|e| e.covers(&self.entries[j])))
638 .collect()
639 }
640}
641
642#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
646pub enum Outcome {
647 Delivered,
649 NotActive,
651 Wild,
653 Unresolved,
655 Unbound,
657 Deleted,
659 Expired,
661 NotIncumbent,
664}
665
666impl Outcome {
667 #[must_use]
669 pub fn as_str(self) -> &'static str {
670 match self {
671 Self::Delivered => "delivered",
672 Self::NotActive => "not_active",
673 Self::Wild => "wild",
674 Self::Unresolved => "unresolved",
675 Self::Unbound => "unbound",
676 Self::Deleted => "deleted",
677 Self::Expired => "expired",
678 Self::NotIncumbent => "not_incumbent",
679 }
680 }
681
682 #[must_use]
684 pub fn delivered(self) -> bool {
685 self == Self::Delivered
686 }
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
691pub struct Sample<'a> {
692 pub key: &'a str,
694 pub delete: bool,
696 pub expired: bool,
699 pub not_incumbent: bool,
702}
703
704impl<'a> Sample<'a> {
705 #[must_use]
707 pub fn new(key: &'a str) -> Self {
708 Self {
709 key,
710 delete: false,
711 expired: false,
712 not_incumbent: false,
713 }
714 }
715}
716
717#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
719pub enum Cause {
720 Start,
722 Sample,
724 Deadline,
726 Withdrawn,
728}
729
730impl Cause {
731 #[must_use]
733 pub fn as_str(self) -> &'static str {
734 match self {
735 Self::Start => "start",
736 Self::Sample => "sample",
737 Self::Deadline => "deadline",
738 Self::Withdrawn => "withdrawn",
739 }
740 }
741}
742
743impl fmt::Display for Cause {
744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745 f.write_str(self.as_str())
746 }
747}
748
749#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct Switch {
752 pub from: Option<Addr>,
753 pub to: Option<Addr>,
754 pub cause: Cause,
755 pub last: Option<Mono>,
758}
759
760#[derive(Debug, Clone, PartialEq, Eq)]
762pub enum Event<'a> {
763 Sample(Sample<'a>),
765 Declared(&'a str),
767 Withdrawn(&'a str),
769 Read {
775 address: Addr,
776 asked: Asked,
777 complete: bool,
778 held: BTreeSet<InstanceId>,
779 },
780 Moved,
782 Stood,
784 Tick,
786}
787
788#[derive(Debug, Clone, Default, PartialEq, Eq)]
790pub struct Step {
791 pub switches: Vec<Switch>,
794 pub outcome: Option<Outcome>,
796 pub reread: Vec<Addr>,
799}
800
801#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
803pub struct Counts {
804 pub delivered: u64,
805 pub not_active: u64,
806 pub deleted: u64,
807 pub expired: u64,
808 pub not_incumbent: u64,
809}
810
811#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
813pub struct Discards {
814 pub wild: u64,
815 pub unresolved: u64,
816 pub unbound: u64,
817}
818
819const MEMBER: &str = "key";
823
824fn tracker(deadline: Duration, start: Option<Mono>) -> Tracker {
828 let mut t = Tracker::new(deadline, Some(1), [MEMBER]);
829 if let Some(at) = start {
830 t.observe(at, timing::Event::Start);
831 }
832 t
833}
834
835#[derive(Debug, Clone)]
836struct Provider {
837 addr: Addr,
838 tracker: Tracker,
841 withdrawn: bool,
842 held: BTreeSet<InstanceId>,
844 heard: Heard,
846 counts: Counts,
847 arrived: Option<Mono>,
850}
851
852impl Provider {
853 fn new(addr: Addr, deadline: Duration, start: Option<Mono>) -> Self {
854 Self {
855 addr,
856 tracker: tracker(deadline, start),
857 withdrawn: false,
858 held: BTreeSet::new(),
859 heard: Heard::default(),
860 counts: Counts::default(),
861 arrived: None,
862 }
863 }
864
865 fn withdraw(&mut self, deadline: Duration, at: Mono) {
867 self.withdrawn = true;
868 self.tracker = tracker(deadline, Some(at));
869 }
870
871 fn last(&self) -> Option<Mono> {
873 match self.tracker.state(MEMBER) {
874 Some(MemberState::Heard { last }) => Some(last),
875 _ => None,
876 }
877 }
878}
879
880#[derive(Debug, Clone)]
882enum Kept {
883 Declared(Rank, InstanceId),
884 Withdrawn(Rank, InstanceId),
885 Read(Rank, Asked, bool, BTreeSet<InstanceId>),
886}
887
888#[derive(Debug, Clone)]
894pub struct Arbiter {
895 iface: IfaceId,
896 token: KindToken,
897 template: Template,
898 params: BTreeMap<String, String>,
899 deadline: Duration,
900 binding: Binding,
901 providers: BTreeMap<Rank, Provider>,
903 active: Option<Rank>,
904 started: bool,
905 moving: bool,
907 kept: Vec<Kept>,
908 discards: Discards,
909 last: Option<Mono>,
911 heard: u64,
913}
914
915impl Arbiter {
916 #[must_use]
921 pub fn new(declared: &Arbitrated, binding: Binding, params: BTreeMap<String, String>) -> Self {
922 let providers = binding
923 .entries()
924 .iter()
925 .filter_map(Entry::exact)
926 .filter_map(|a| Some((binding.rank(&a)?, Provider::new(a, declared.deadline, None))))
927 .collect();
928 Self {
929 iface: declared.iface.clone(),
930 token: declared.token,
931 template: declared.template.clone(),
932 params,
933 deadline: declared.deadline,
934 binding,
935 providers,
936 active: None,
937 started: false,
938 moving: false,
939 kept: Vec::new(),
940 discards: Discards::default(),
941 last: None,
942 heard: 0,
943 }
944 }
945
946 #[must_use]
950 pub fn ask(&self) -> Asked {
951 Asked(self.heard)
952 }
953
954 #[must_use]
956 pub fn deadline(&self) -> Duration {
957 self.deadline
958 }
959
960 #[must_use]
962 pub fn binding(&self) -> &Binding {
963 &self.binding
964 }
965
966 #[must_use]
968 pub fn active(&self) -> Option<&Addr> {
969 self.active
970 .as_ref()
971 .and_then(|r| self.providers.get(r))
972 .map(|p| &p.addr)
973 }
974
975 #[must_use]
977 pub fn dead_man(&self) -> bool {
978 self.active.is_none()
979 }
980
981 #[must_use]
987 pub fn due(&self) -> Option<Mono> {
988 let p = self.providers.get(self.active.as_ref()?)?;
989 Some(p.last()?.saturating_add(self.deadline))
990 }
991
992 #[must_use]
994 pub fn moving(&self) -> bool {
995 self.moving
996 }
997
998 pub fn providers(&self) -> impl Iterator<Item = &Addr> {
1000 self.providers.values().map(|p| &p.addr)
1001 }
1002
1003 #[must_use]
1005 pub fn counts(&self, a: &Addr) -> Counts {
1006 self.binding
1007 .rank(a)
1008 .and_then(|r| self.providers.get(&r))
1009 .map(|p| p.counts)
1010 .unwrap_or_default()
1011 }
1012
1013 #[must_use]
1015 pub fn discards(&self) -> Discards {
1016 self.discards
1017 }
1018
1019 #[must_use]
1021 pub fn withdrawn(&self, a: &Addr) -> bool {
1022 self.binding
1023 .rank(a)
1024 .and_then(|r| self.providers.get(&r))
1025 .is_some_and(|p| p.withdrawn)
1026 }
1027
1028 pub fn identify(&self, key: &str) -> Result<Addr, Outcome> {
1031 if key.contains('*') {
1032 return Err(Outcome::Wild);
1033 }
1034 let Ok(ZkKey::Data {
1035 addr,
1036 iface,
1037 kind,
1038 resource,
1039 }) = parse(key)
1040 else {
1041 return Err(Outcome::Unresolved);
1042 };
1043 if iface != self.iface || kind != self.token {
1044 return Err(Outcome::Unresolved);
1045 }
1046 let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
1047 let Some(values) = self.template.matches(&chunks) else {
1048 return Err(Outcome::Unresolved);
1049 };
1050 for (name, vs) in &values {
1051 match (self.params.get(name), vs.as_slice()) {
1052 (Some(p), [v]) if p == v => {}
1053 _ => return Err(Outcome::Unresolved),
1054 }
1055 }
1056 if self.binding.rank(&addr).is_none() {
1057 return Err(Outcome::Unbound);
1058 }
1059 Ok(addr)
1060 }
1061
1062 pub fn start(&mut self, at: Mono) -> Step {
1065 if self.started {
1066 return Step::default();
1067 }
1068 self.started = true;
1069 self.active = None;
1070 self.last = Some(at);
1071 for p in self.providers.values_mut() {
1072 p.tracker.observe(at, timing::Event::Start);
1073 }
1074 Step {
1075 switches: vec![Switch {
1076 from: None,
1077 to: None,
1078 cause: Cause::Start,
1079 last: None,
1080 }],
1081 ..Step::default()
1082 }
1083 }
1084
1085 pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Step {
1088 let mut step = Step::default();
1089 if !self.started {
1090 return step;
1091 }
1092 debug_assert!(
1093 self.last.is_none_or(|l| at >= l),
1094 "an event at {at:?} precedes the last one, at {:?}",
1095 self.last
1096 );
1097 self.last = Some(at);
1098 if let Some(r) = self.active.clone()
1100 && !self.eligible(&r, at)
1101 {
1102 let next = self.select(at);
1103 step.switches.push(self.switch_to(next, Cause::Deadline));
1104 }
1105 let mut reread = Vec::new();
1106 let mut arrival = None;
1107 match event {
1108 Event::Sample(s) => match self.identify(s.key) {
1109 Err(o) => {
1110 match o {
1111 Outcome::Wild => self.discards.wild += 1,
1112 Outcome::Unbound => self.discards.unbound += 1,
1113 _ => self.discards.unresolved += 1,
1114 }
1115 step.outcome = Some(o);
1116 }
1117 Ok(addr) => {
1118 if let Some(r) = self.provider(addr, at)
1121 && let Some(p) = self.providers.get_mut(&r)
1122 {
1123 if s.delete {
1124 p.counts.deleted += 1;
1125 step.outcome = Some(Outcome::Deleted);
1126 } else if s.expired {
1127 p.counts.expired += 1;
1128 step.outcome = Some(Outcome::Expired);
1129 } else if s.not_incumbent {
1130 p.counts.not_incumbent += 1;
1131 step.outcome = Some(Outcome::NotIncumbent);
1132 } else {
1133 if !p.withdrawn {
1134 p.tracker.observe(
1135 at,
1136 timing::Event::Arrival {
1137 member: MEMBER,
1138 expired: false,
1139 },
1140 );
1141 p.arrived = Some(at);
1142 }
1143 arrival = Some(r);
1144 }
1145 }
1146 }
1147 },
1148 Event::Declared(key) => {
1149 if let Some((r, i)) = self.token(key, at) {
1150 self.note(&r, &i);
1151 if self.moving {
1152 self.kept.push(Kept::Declared(r, i));
1153 } else if let Some(p) = self.providers.get_mut(&r) {
1154 p.held.insert(i);
1155 p.withdrawn = false;
1156 }
1157 }
1158 }
1159 Event::Withdrawn(key) => {
1160 if let Some((r, i)) = self.token(key, at) {
1161 self.note(&r, &i);
1162 if self.moving {
1163 self.kept.push(Kept::Withdrawn(r, i));
1164 } else if let Some(p) = self.providers.get_mut(&r) {
1165 p.held.remove(&i);
1166 if p.held.is_empty() {
1167 p.withdraw(self.deadline, at);
1168 reread.push(r);
1169 }
1170 }
1171 }
1172 }
1173 Event::Read {
1174 address,
1175 asked,
1176 complete,
1177 held,
1178 } => {
1179 if let Some(r) = self.provider(address, at) {
1180 if self.moving {
1181 self.kept.push(Kept::Read(r, asked, complete, held));
1182 } else if let Some(p) = self.providers.get_mut(&r) {
1183 p.heard.read_into(&mut p.held, asked, complete, held);
1184 if !p.held.is_empty() {
1185 p.withdrawn = false;
1186 }
1187 }
1188 }
1189 }
1190 Event::Moved => self.moving = true,
1191 Event::Stood => {
1192 if self.moving {
1193 self.stand(at, &mut reread);
1194 }
1195 }
1196 Event::Tick => {}
1197 }
1198 let next = self.select(at);
1199 if next != self.active {
1200 let cause = if arrival.is_some() && next == arrival {
1201 Cause::Sample
1202 } else {
1203 debug_assert!(
1207 self.active
1208 .as_ref()
1209 .and_then(|r| self.providers.get(r))
1210 .is_some_and(|p| p.withdrawn),
1211 "a switch at {at:?} that is no arrival's, from a provider not withdrawn"
1212 );
1213 Cause::Withdrawn
1214 };
1215 step.switches.push(self.switch_to(next, cause));
1216 }
1217 if let Some(r) = arrival {
1218 let delivered = self.active.as_ref() == Some(&r);
1219 if let Some(p) = self.providers.get_mut(&r) {
1220 step.outcome = Some(if delivered {
1221 p.counts.delivered += 1;
1222 Outcome::Delivered
1223 } else {
1224 p.counts.not_active += 1;
1225 Outcome::NotActive
1226 });
1227 }
1228 }
1229 reread.sort();
1230 reread.dedup();
1231 step.reread = reread
1232 .iter()
1233 .filter_map(|r| self.providers.get(r))
1234 .map(|p| p.addr.clone())
1235 .collect();
1236 step
1237 }
1238
1239 fn eligible(&self, r: &Rank, at: Mono) -> bool {
1243 self.providers.get(r).is_some_and(|p| {
1244 !p.withdrawn
1245 && p.last()
1246 .is_some_and(|l| at <= l.saturating_add(self.deadline))
1247 })
1248 }
1249
1250 fn select(&self, at: Mono) -> Option<Rank> {
1252 self.providers
1253 .keys()
1254 .find(|r| self.eligible(r, at))
1255 .cloned()
1256 }
1257
1258 fn switch_to(&mut self, next: Option<Rank>, cause: Cause) -> Switch {
1259 let addr = |r: &Option<Rank>| {
1260 r.as_ref()
1261 .and_then(|r| self.providers.get(r))
1262 .map(|p| p.addr.clone())
1263 };
1264 let switch = Switch {
1265 from: addr(&self.active),
1266 to: addr(&next),
1267 cause,
1268 last: self
1269 .active
1270 .as_ref()
1271 .and_then(|r| self.providers.get(r))
1272 .and_then(|p| p.arrived),
1273 };
1274 self.active = next;
1275 switch
1276 }
1277
1278 fn provider(&mut self, addr: Addr, at: Mono) -> Option<Rank> {
1282 let r = self.binding.rank(&addr)?;
1283 let deadline = self.deadline;
1284 self.providers
1285 .entry(r.clone())
1286 .or_insert_with(|| Provider::new(addr, deadline, Some(at)));
1287 Some(r)
1288 }
1289
1290 fn token(&mut self, key: &str, at: Mono) -> Option<(Rank, InstanceId)> {
1293 let Ok(ZkKey::Alive {
1294 addr,
1295 iface,
1296 instance,
1297 ..
1298 }) = parse(key)
1299 else {
1300 return None;
1301 };
1302 if iface != self.iface {
1303 return None;
1304 }
1305 Some((self.provider(addr, at)?, instance))
1306 }
1307
1308 fn note(&mut self, r: &Rank, i: &InstanceId) {
1311 self.heard += 1;
1312 if let Some(p) = self.providers.get_mut(r) {
1313 p.heard.note(i.clone(), self.heard, &p.held);
1314 }
1315 }
1316
1317 fn stand(&mut self, at: Mono, reread: &mut Vec<Rank>) {
1320 self.moving = false;
1321 let mut touched: BTreeMap<Rank, (bool, bool)> = BTreeMap::new();
1323 for k in std::mem::take(&mut self.kept) {
1324 let r = match &k {
1325 Kept::Declared(r, _) | Kept::Withdrawn(r, _) | Kept::Read(r, ..) => r.clone(),
1326 };
1327 let Some(p) = self.providers.get_mut(&r) else {
1328 continue;
1329 };
1330 let t = touched.entry(r).or_insert((p.withdrawn, false));
1331 match k {
1332 Kept::Declared(_, i) => {
1333 p.held.insert(i);
1334 }
1335 Kept::Withdrawn(_, i) => {
1336 p.held.remove(&i);
1337 t.1 = true;
1338 }
1339 Kept::Read(_, asked, complete, held) => {
1340 p.heard.read_into(&mut p.held, asked, complete, held);
1341 }
1342 }
1343 }
1344 for (r, (before, withdrawal)) in touched {
1345 let Some(p) = self.providers.get_mut(&r) else {
1346 continue;
1347 };
1348 if p.held.is_empty() && withdrawal {
1349 p.withdraw(self.deadline, at);
1350 reread.push(r);
1351 } else if !p.held.is_empty() && before {
1352 p.withdrawn = false;
1353 }
1354 }
1355 }
1356}
1357
1358pub use crate::redundancy::{Asked, Holding};
1364
1365impl Holding {
1366 #[must_use]
1369 pub fn of_token(key: &str, put: bool, iface: &IfaceId, binding: &Binding) -> Option<Self> {
1370 let Ok(ZkKey::Alive {
1371 addr,
1372 iface: i,
1373 instance,
1374 ..
1375 }) = parse(key)
1376 else {
1377 return None;
1378 };
1379 if i != *iface || binding.rank(&addr).is_none() {
1380 return None;
1381 }
1382 Some(if put {
1383 Self::Declared(addr, instance)
1384 } else {
1385 Self::Withdrawn(addr, instance)
1386 })
1387 }
1388}
1389
1390pub type Incumbents = crate::redundancy::Fence;
1398
1399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1403pub enum Answer {
1404 Yes,
1405 No,
1406 Unobservable,
1408 NotAsked,
1410 NotThisProfiles,
1412}
1413
1414impl Answer {
1415 #[must_use]
1417 pub fn as_str(self) -> &'static str {
1418 match self {
1419 Self::Yes => "yes",
1420 Self::No => "no",
1421 Self::Unobservable => "unobservable",
1422 Self::NotAsked => "not_asked",
1423 Self::NotThisProfiles => "not_this_profiles",
1424 }
1425 }
1426}
1427
1428impl fmt::Display for Answer {
1429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1430 f.write_str(self.as_str())
1431 }
1432}
1433
1434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1436pub enum Reason {
1437 NoContract,
1438 NotArbitrated,
1439 RevisionsDisagree,
1440 NoProviderContract,
1441 Invalid,
1442 Valid,
1443 Unbound,
1444 NotListened,
1445 Lost,
1446 Selected,
1447 Listening,
1448 DeadMan,
1449 Wildcard,
1450 Shadowed,
1451 Exact,
1452 NoDescriptor,
1455}
1456
1457impl Reason {
1458 #[must_use]
1460 pub fn as_str(self) -> &'static str {
1461 match self {
1462 Self::NoContract => "no_contract",
1463 Self::NotArbitrated => "not_arbitrated",
1464 Self::RevisionsDisagree => "revisions_disagree",
1465 Self::NoProviderContract => "no_provider_contract",
1466 Self::Invalid => "invalid",
1467 Self::Valid => "valid",
1468 Self::Unbound => "unbound",
1469 Self::NotListened => "not_listened",
1470 Self::Lost => "lost",
1471 Self::Selected => "selected",
1472 Self::Listening => "listening",
1473 Self::DeadMan => "dead_man",
1474 Self::Wildcard => "wildcard",
1475 Self::Shadowed => "shadowed",
1476 Self::Exact => "exact",
1477 Self::NoDescriptor => "no_descriptor",
1478 }
1479 }
1480}
1481
1482impl fmt::Display for Reason {
1483 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1484 f.write_str(self.as_str())
1485 }
1486}
1487
1488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1490pub struct Judged {
1491 pub answer: Answer,
1492 pub reason: Reason,
1493}
1494
1495impl Judged {
1496 const fn new(answer: Answer, reason: Reason) -> Self {
1497 Self { answer, reason }
1498 }
1499}
1500
1501#[derive(Debug, Clone, PartialEq, Eq)]
1503pub enum Held {
1504 NoContract,
1506 RevisionsDisagree,
1508 Read(Declaration),
1512}
1513
1514#[must_use]
1518pub fn held_over(
1519 role: &Role<'_>,
1520 revisions: &[Revision<'_>],
1521 params: &BTreeMap<String, String>,
1522) -> Held {
1523 let mut seen: Option<Declaration> = None;
1524 for rev in revisions {
1525 let d = declaration(role, Some(rev), params);
1526 match &seen {
1527 None => seen = Some(d),
1528 Some(s) if *s == d => {}
1529 Some(_) => return Held::RevisionsDisagree,
1530 }
1531 }
1532 Held::Read(seen.unwrap_or_else(|| declaration(role, None, params)))
1533}
1534
1535#[derive(Debug, Clone, PartialEq, Eq)]
1537pub struct View {
1538 pub listened: Duration,
1540 pub lost: bool,
1542 pub active: Option<Addr>,
1544}
1545
1546#[derive(Debug, Clone, PartialEq, Eq)]
1548pub struct Reading {
1549 pub declaration: Held,
1550 pub binding: Option<Binding>,
1554 pub view: Option<View>,
1556}
1557
1558fn premises(r: &Reading) -> Result<(), Judged> {
1561 match &r.declaration {
1562 Held::NoContract => Err(Judged::new(Answer::Unobservable, Reason::NoContract)),
1563 Held::Read(Declaration::NotArbitrated) => {
1564 Err(Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated))
1565 }
1566 _ => Ok(()),
1567 }
1568}
1569
1570#[must_use]
1573pub fn judge_declaration(r: &Reading) -> (Judged, Vec<Invalid>) {
1574 match &r.declaration {
1575 Held::NoContract => (
1576 Judged::new(Answer::Unobservable, Reason::NoContract),
1577 Vec::new(),
1578 ),
1579 Held::Read(Declaration::NotArbitrated) => (
1580 Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated),
1581 Vec::new(),
1582 ),
1583 Held::RevisionsDisagree => (
1584 Judged::new(Answer::Unobservable, Reason::RevisionsDisagree),
1585 Vec::new(),
1586 ),
1587 Held::Read(Declaration::Unread) => (
1588 Judged::new(Answer::Unobservable, Reason::NoProviderContract),
1589 Vec::new(),
1590 ),
1591 Held::Read(Declaration::Invalid(why)) => {
1592 (Judged::new(Answer::No, Reason::Invalid), why.clone())
1593 }
1594 Held::Read(Declaration::Arbitrated(_)) => {
1595 (Judged::new(Answer::Yes, Reason::Valid), Vec::new())
1596 }
1597 }
1598}
1599
1600#[must_use]
1605pub fn judge_selection(r: &Reading) -> (Judged, Option<Addr>) {
1606 if let Err(j) = premises(r) {
1607 return (j, None);
1608 }
1609 let Some(binding) = &r.binding else {
1610 return (Judged::new(Answer::NotAsked, Reason::NoDescriptor), None);
1611 };
1612 let deadline = match &r.declaration {
1613 Held::Read(Declaration::Arbitrated(a)) => a.deadline,
1614 Held::Read(Declaration::Invalid(_)) => {
1615 return (Judged::new(Answer::Unobservable, Reason::Invalid), None);
1616 }
1617 _ => return (judge_declaration(r).0, None),
1620 };
1621 if binding.is_empty() {
1622 return (Judged::new(Answer::No, Reason::Unbound), None);
1623 }
1624 let Some(view) = &r.view else {
1625 return (Judged::new(Answer::NotAsked, Reason::NotListened), None);
1626 };
1627 if view.lost {
1628 return (Judged::new(Answer::Unobservable, Reason::Lost), None);
1629 }
1630 if let Some(a) = &view.active {
1631 return (Judged::new(Answer::Yes, Reason::Selected), Some(a.clone()));
1632 }
1633 if view.listened < deadline {
1634 return (Judged::new(Answer::Unobservable, Reason::Listening), None);
1635 }
1636 (Judged::new(Answer::No, Reason::DeadMan), None)
1637}
1638
1639#[must_use]
1644pub fn judge_binding(r: &Reading) -> (Judged, Vec<usize>, Vec<usize>) {
1645 if let Err(j) = premises(r) {
1646 return (j, Vec::new(), Vec::new());
1647 }
1648 let Some(binding) = &r.binding else {
1649 return (
1650 Judged::new(Answer::NotAsked, Reason::NoDescriptor),
1651 Vec::new(),
1652 Vec::new(),
1653 );
1654 };
1655 let wild = binding.wildcards();
1656 let shadowed = binding.shadowed();
1657 if !wild.is_empty() {
1658 return (Judged::new(Answer::Yes, Reason::Wildcard), wild, shadowed);
1659 }
1660 if !shadowed.is_empty() {
1661 return (
1662 Judged::new(Answer::Yes, Reason::Shadowed),
1663 Vec::new(),
1664 shadowed,
1665 );
1666 }
1667 (
1668 Judged::new(Answer::No, Reason::Exact),
1669 Vec::new(),
1670 Vec::new(),
1671 )
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676 use super::*;
1677
1678 fn arbitrated(deadline_ms: u64) -> Arbitrated {
1679 Arbitrated {
1680 policy: Policy::Priority,
1681 iface: "steer.v1".parse().unwrap(),
1682 token: KindToken::Stream,
1683 template: Template::parse("cmd").unwrap(),
1684 deadline: Duration::from_millis(deadline_ms),
1685 period: None,
1686 }
1687 }
1688
1689 fn arbiter() -> Arbiter {
1690 Arbiter::new(
1691 &arbitrated(300),
1692 Binding::parse(&["lab/safety", "lab/teleop"]).unwrap(),
1693 BTreeMap::new(),
1694 )
1695 }
1696
1697 const SAFETY: &str = "zk2/lab/safety/steer.v1/stream/cmd";
1698
1699 #[test]
1701 fn nothing_before_the_start_and_one_start() {
1702 let mut a = arbiter();
1703 let ms = |n| Mono::after(Duration::from_millis(n));
1704 assert_eq!(
1705 a.observe(ms(0), Event::Sample(Sample::new(SAFETY))),
1706 Step::default()
1707 );
1708 assert_eq!(a.start(ms(1)).switches.len(), 1);
1709 assert_eq!(a.start(ms(2)), Step::default());
1710 assert!(a.dead_man());
1711 let s = a.observe(ms(3), Event::Sample(Sample::new(SAFETY)));
1712 assert_eq!(s.outcome, Some(Outcome::Delivered));
1713 assert_eq!(a.due(), Some(ms(303)));
1714 assert_eq!(a.counts(&"lab/safety".parse().unwrap()).delivered, 1);
1715 }
1716
1717 #[test]
1720 fn a_switch_carries_its_froms_last_arrival() {
1721 let mut a = arbiter();
1722 let ms = |n| Mono::after(Duration::from_millis(n));
1723 assert_eq!(a.start(ms(0)).switches[0].last, None);
1724 let s = a.observe(ms(10), Event::Sample(Sample::new(SAFETY)));
1725 assert_eq!(s.switches[0].last, None, "from the dead-man");
1726 a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
1727 let s = a.observe(ms(400), Event::Tick);
1728 assert_eq!(s.switches[0].cause, Cause::Deadline);
1729 assert_eq!(s.switches[0].last, Some(ms(20)));
1730 a.observe(ms(410), Event::Sample(Sample::new(SAFETY)));
1731 let s = a.observe(
1732 ms(420),
1733 Event::Withdrawn("zk2/lab/safety/@zk/alive/steer.v1/000000000000000a/0123456789abcdef"),
1734 );
1735 assert_eq!(s.switches[0].cause, Cause::Withdrawn);
1736 assert_eq!(
1737 s.switches[0].last,
1738 Some(ms(410)),
1739 "kept across the withdrawal"
1740 );
1741 }
1742
1743 #[test]
1749 fn a_read_never_undoes_a_token_heard_since_it_was_asked() {
1750 let mut a = arbiter();
1751 let ms = |n| Mono::after(Duration::from_millis(n));
1752 let safety: Addr = "lab/safety".parse().unwrap();
1753 let alive = |i: u64| format!("zk2/lab/safety/@zk/alive/steer.v1/{i:016x}/0123456789abcdef");
1754 let (ka, kb) = (alive(0xa), alive(0xb));
1755 a.start(ms(0));
1756 a.observe(ms(10), Event::Declared(&ka));
1757 a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
1758 assert_eq!(a.active(), Some(&safety));
1759 a.observe(ms(30), Event::Moved);
1760 a.observe(ms(40), Event::Withdrawn(&ka));
1761 let asked = a.ask();
1762 a.observe(ms(50), Event::Declared(&kb));
1763 let read = |asked| Event::Read {
1764 address: safety.clone(),
1765 asked,
1766 complete: true,
1767 held: BTreeSet::new(),
1768 };
1769 a.observe(ms(60), read(asked));
1770 let s = a.observe(ms(70), Event::Stood);
1771 assert!(s.switches.is_empty(), "{:?}", s.switches);
1772 assert!(
1773 !a.withdrawn(&safety),
1774 "B holds: the read says nothing of it"
1775 );
1776 assert_eq!(a.active(), Some(&safety));
1777 let asked = a.ask();
1780 a.observe(ms(80), read(asked));
1781 let s = a.observe(ms(90), Event::Withdrawn(&ka));
1782 assert!(
1783 a.withdrawn(&safety),
1784 "none held once A's stale withdrawal is heard"
1785 );
1786 assert_eq!(s.reread, [safety]);
1787 }
1788
1789 #[test]
1792 #[cfg(debug_assertions)]
1793 #[should_panic(expected = "precedes the last one")]
1794 fn an_event_never_goes_back_in_time() {
1795 let mut a = arbiter();
1796 let ms = |n| Mono::after(Duration::from_millis(n));
1797 a.start(ms(10));
1798 a.observe(ms(5), Event::Tick);
1799 }
1800
1801 #[test]
1804 fn entries_parse_and_print() {
1805 for e in ["lab/safety", "lab/*", "*/teleop", "*/*"] {
1806 assert_eq!(Entry::parse(e).unwrap().to_string(), e);
1807 }
1808 for bad in ["lab", "lab/Safety", "lab/**", "/x"] {
1809 assert!(Entry::parse(bad).is_err(), "{bad}");
1810 }
1811 }
1812}