use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::time::Duration;
use serde_json::Value;
use crate::authoring::{Kind, RequireCardinality};
use crate::contract::{Contract, Requirement};
use crate::grammar::{Addr, IfaceId, InstanceId, KeyError, KindToken, Name, ZkKey, parse};
use crate::template::Template;
use crate::timing::{self, MemberState, Mono, Tracker};
pub const PROFILE: &str = "arbitration.v1";
pub const NAME: &str = "arbitration";
pub const POLICY: &str = "arbitration.policy";
pub const VOCABULARY: &[&str] = &["policy"];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Policy {
Priority,
}
impl Policy {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Priority => "priority",
}
}
}
impl fmt::Display for Policy {
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,
ManifestRole,
PolicyUnsupported,
Value,
Cardinality,
Resource,
NoDeadline,
ParamsUnbound,
Framed,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotUsed => "not_used",
Self::ManifestRole => "manifest_role",
Self::PolicyUnsupported => "policy_unsupported",
Self::Value => "value",
Self::Cardinality => "cardinality",
Self::Resource => "resource",
Self::NoDeadline => "no_deadline",
Self::ParamsUnbound => "params_unbound",
Self::Framed => "framed",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotUsed => "arbitration.policy is written, and uses does not list arbitration.v1",
Self::ManifestRole => {
"only a contract's role is arbitrated: a manifest's role reaches no descriptor with its policy"
}
Self::PolicyUnsupported => {
"freshest and lease are reserved; arbitration.v1 1.0 defines priority only"
}
Self::Value => "arbitration.policy is the string priority",
Self::Cardinality => "an arbitrated role has cardinality many",
Self::Resource => "an arbitrated role consumes exactly one stream resource",
Self::NoDeadline => {
"the role's stream declares a timing.v1 deadline, at or above its period"
}
Self::ParamsUnbound => {
"every parameter of the role's stream is bound by the role's parameter bindings"
}
Self::Framed => {
"a frame resource is never an arbitrated role's stream: its put carries several records"
}
}
}
}
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 struct Arbitrated {
pub policy: Policy,
pub iface: IfaceId,
pub token: KindToken,
pub template: Template,
pub deadline: Duration,
pub period: Option<Duration>,
}
impl Arbitrated {
#[must_use]
pub fn resource(&self) -> String {
format!("{}/{}", self.token.as_str(), self.template.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
NotArbitrated,
Unread,
Invalid(Vec<Invalid>),
Arbitrated(Arbitrated),
}
impl Declaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotArbitrated => "not_arbitrated",
Self::Unread => "unread",
Self::Invalid(_) => "invalid",
Self::Arbitrated(_) => "arbitrated",
}
}
#[must_use]
pub fn arbitrated(&self) -> Option<&Arbitrated> {
match self {
Self::Arbitrated(a) => Some(a),
_ => None,
}
}
#[must_use]
pub fn carries_policy(&self) -> bool {
!matches!(self, Self::NotArbitrated)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Role<'a> {
pub declared_by: Option<&'a [IfaceId]>,
pub resources: Option<&'a [String]>,
pub cardinality: RequireCardinality,
pub annotations: &'a BTreeMap<String, Value>,
}
impl<'a> Role<'a> {
#[must_use]
pub fn of(declaring: &'a Contract, req: &'a Requirement) -> Self {
Self {
declared_by: Some(declaring.uses.as_slice()),
resources: req.resources.as_deref(),
cardinality: req.cardinality,
annotations: &req.annotations,
}
}
#[must_use]
pub fn of_manifest(req: &'a Requirement) -> Self {
Self {
declared_by: None,
resources: req.resources.as_deref(),
cardinality: req.cardinality,
annotations: &req.annotations,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Offered<'a> {
pub token: KindToken,
pub template: &'a Template,
pub annotations: &'a BTreeMap<String, Value>,
pub frame: bool,
}
#[derive(Debug, Clone)]
pub struct Revision<'a> {
pub iface: &'a IfaceId,
pub resources: Vec<Offered<'a>>,
}
impl<'a> Revision<'a> {
#[must_use]
pub fn of(c: &'a Contract) -> Self {
Self {
iface: &c.iface,
resources: c
.resources
.iter()
.map(|r| Offered {
token: r.token,
template: &r.template,
annotations: &r.annotations,
frame: matches!(&r.body, crate::contract::Body::Data(d) if d.frame.is_some()),
})
.collect(),
}
}
}
fn kind_of(token: KindToken) -> Kind {
match token {
KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
KindToken::State | KindToken::ExplicitState => Kind::State,
KindToken::Events => Kind::Event,
KindToken::Op => Kind::Operation,
}
}
#[must_use]
pub fn deadline_of(r: &Offered<'_>) -> Option<(Duration, Option<Duration>)> {
let d = match timing::declaration(kind_of(r.token), r.annotations) {
timing::Declaration::Declared(d) => d,
_ => return None,
};
Some((d.judged_deadline()?, d.period))
}
#[must_use]
pub fn declaration(
role: &Role<'_>,
provider: Option<&Revision<'_>>,
params: &BTreeMap<String, String>,
) -> Declaration {
let Some(policy) = role.annotations.get(POLICY) else {
return Declaration::NotArbitrated;
};
let mut why = Vec::new();
match role.declared_by {
Some(uses) => {
let v1 = uses.iter().any(|u| u.name() == NAME && u.major() == 1);
let any = uses.iter().any(|u| u.name() == NAME);
if any && !v1 {
return Declaration::NotArbitrated;
}
if !any {
why.push(Invalid::NotUsed);
}
}
None => why.push(Invalid::ManifestRole),
}
match policy.as_str() {
Some("priority") => {}
Some("freshest" | "lease") => why.push(Invalid::PolicyUnsupported),
_ => why.push(Invalid::Value),
}
if role.cardinality != RequireCardinality::Many {
why.push(Invalid::Cardinality);
}
let Some(rev) = provider else {
return if why.is_empty() {
Declaration::Unread
} else {
Declaration::Invalid(why)
};
};
let consumed: Vec<&Offered<'_>> = rev
.resources
.iter()
.filter(|r| match role.resources {
None => true,
Some(names) => names.iter().any(|n| n == r.template.as_str()),
})
.collect();
let counted: Vec<&Offered<'_>> = consumed.iter().copied().filter(|r| !r.frame).collect();
let one = match counted.as_slice() {
[r] if matches!(r.token, KindToken::Stream | KindToken::ExplicitStream) => Some(*r),
_ => {
why.push(Invalid::Resource);
None
}
};
let mut deadline = None;
if let Some(r) = one {
deadline = deadline_of(r);
if deadline.is_none() {
why.push(Invalid::NoDeadline);
}
if r.template.params().any(|(p, _)| !params.contains_key(p)) {
why.push(Invalid::ParamsUnbound);
}
}
let plain_stream = counted
.iter()
.any(|r| matches!(r.token, KindToken::Stream | KindToken::ExplicitStream));
if consumed.iter().any(|r| r.frame) && !plain_stream {
why.push(Invalid::Framed);
}
match (one, deadline) {
(Some(r), Some((deadline, period))) if why.is_empty() => {
Declaration::Arbitrated(Arbitrated {
policy: Policy::Priority,
iface: rev.iface.clone(),
token: r.token,
template: r.template.clone(),
deadline,
period,
})
}
_ => Declaration::Invalid(why),
}
}
#[must_use]
pub fn declaration_of(
declaring: &Contract,
role: &str,
provider: Option<&Contract>,
params: &BTreeMap<String, String>,
) -> Option<Declaration> {
let req = declaring.requires.get(role)?;
let rev = provider.map(Revision::of);
Some(declaration(&Role::of(declaring, req), rev.as_ref(), params))
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Entry {
system: Option<Name>,
service: Option<Name>,
}
impl Entry {
pub fn parse(s: &str) -> Result<Self, KeyError> {
let (sys, svc) = s.split_once('/').ok_or(KeyError::Shape(
s.to_owned(),
"a binding entry is <system>/<service>",
))?;
let chunk = |what: &'static str, c: &str| -> Result<Option<Name>, KeyError> {
if c == "*" {
Ok(None)
} else {
Name::new(what, c).map(Some)
}
};
Ok(Self {
system: chunk("system", sys)?,
service: chunk("service", svc)?,
})
}
#[must_use]
pub fn is_wildcard(&self) -> bool {
self.system.is_none() || self.service.is_none()
}
#[must_use]
pub fn exact(&self) -> Option<Addr> {
Some(Addr {
system: self.system.clone()?,
service: self.service.clone()?,
})
}
#[must_use]
pub fn matches(&self, a: &Addr) -> bool {
self.system.as_ref().is_none_or(|s| *s == a.system)
&& self.service.as_ref().is_none_or(|s| *s == a.service)
}
#[must_use]
pub fn covers(&self, later: &Entry) -> bool {
fn chunk(a: Option<&Name>, b: Option<&Name>) -> bool {
match (a, b) {
(None, _) => true,
(Some(a), Some(b)) => a == b,
(Some(_), None) => false,
}
}
chunk(self.system.as_ref(), later.system.as_ref())
&& chunk(self.service.as_ref(), later.service.as_ref())
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let c = |n: &Option<Name>| n.as_ref().map_or("*", Name::as_str).to_owned();
write!(f, "{}/{}", c(&self.system), c(&self.service))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rank {
entry: usize,
system: String,
service: String,
}
impl Rank {
#[must_use]
pub fn entry(&self) -> usize {
self.entry
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Binding {
entries: Vec<Entry>,
}
impl Binding {
pub fn parse<S: AsRef<str>>(entries: &[S]) -> Result<Self, KeyError> {
Ok(Self {
entries: entries
.iter()
.map(|e| Entry::parse(e.as_ref()))
.collect::<Result<_, _>>()?,
})
}
#[must_use]
pub fn entries(&self) -> &[Entry] {
&self.entries
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn rank(&self, a: &Addr) -> Option<Rank> {
let entry = self.entries.iter().position(|e| e.matches(a))?;
Some(Rank {
entry,
system: a.system.as_str().to_owned(),
service: a.service.as_str().to_owned(),
})
}
#[must_use]
pub fn ranked<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
let mut by: BTreeMap<Rank, Addr> = BTreeMap::new();
let mut add = |a: &Addr| {
if let Some(r) = self.rank(a) {
by.entry(r).or_insert_with(|| a.clone());
}
};
for a in self.entries.iter().filter_map(Entry::exact) {
add(&a);
}
for a in heard {
add(a);
}
by.into_values().collect()
}
#[must_use]
pub fn unbound<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
heard
.into_iter()
.filter(|a| self.rank(a).is_none())
.cloned()
.collect::<BTreeSet<_>>()
.into_iter()
.collect()
}
#[must_use]
pub fn wildcards(&self) -> Vec<usize> {
self.entries
.iter()
.enumerate()
.filter(|(_, e)| e.is_wildcard())
.map(|(i, _)| i)
.collect()
}
#[must_use]
pub fn shadowed(&self) -> Vec<usize> {
(0..self.entries.len())
.filter(|&j| self.entries[..j].iter().any(|e| e.covers(&self.entries[j])))
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Outcome {
Delivered,
NotActive,
Wild,
Unresolved,
Unbound,
Deleted,
Expired,
NotIncumbent,
}
impl Outcome {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Delivered => "delivered",
Self::NotActive => "not_active",
Self::Wild => "wild",
Self::Unresolved => "unresolved",
Self::Unbound => "unbound",
Self::Deleted => "deleted",
Self::Expired => "expired",
Self::NotIncumbent => "not_incumbent",
}
}
#[must_use]
pub fn delivered(self) -> bool {
self == Self::Delivered
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sample<'a> {
pub key: &'a str,
pub delete: bool,
pub expired: bool,
pub not_incumbent: bool,
}
impl<'a> Sample<'a> {
#[must_use]
pub fn new(key: &'a str) -> Self {
Self {
key,
delete: false,
expired: false,
not_incumbent: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cause {
Start,
Sample,
Deadline,
Withdrawn,
}
impl Cause {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Start => "start",
Self::Sample => "sample",
Self::Deadline => "deadline",
Self::Withdrawn => "withdrawn",
}
}
}
impl fmt::Display for Cause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Switch {
pub from: Option<Addr>,
pub to: Option<Addr>,
pub cause: Cause,
pub last: Option<Mono>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event<'a> {
Sample(Sample<'a>),
Declared(&'a str),
Withdrawn(&'a str),
Read {
address: Addr,
complete: bool,
held: BTreeSet<InstanceId>,
},
Moved,
Stood,
Tick,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Step {
pub switches: Vec<Switch>,
pub outcome: Option<Outcome>,
pub reread: Vec<Addr>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
pub delivered: u64,
pub not_active: u64,
pub deleted: u64,
pub expired: u64,
pub not_incumbent: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Discards {
pub wild: u64,
pub unresolved: u64,
pub unbound: u64,
}
const MEMBER: &str = "key";
fn tracker(deadline: Duration, start: Option<Mono>) -> Tracker {
let mut t = Tracker::new(deadline, Some(1), [MEMBER]);
if let Some(at) = start {
t.observe(at, timing::Event::Start);
}
t
}
#[derive(Debug, Clone)]
struct Provider {
addr: Addr,
tracker: Tracker,
withdrawn: bool,
held: BTreeSet<InstanceId>,
counts: Counts,
arrived: Option<Mono>,
}
impl Provider {
fn new(addr: Addr, deadline: Duration, start: Option<Mono>) -> Self {
Self {
addr,
tracker: tracker(deadline, start),
withdrawn: false,
held: BTreeSet::new(),
counts: Counts::default(),
arrived: None,
}
}
fn withdraw(&mut self, deadline: Duration, at: Mono) {
self.withdrawn = true;
self.tracker = tracker(deadline, Some(at));
}
fn last(&self) -> Option<Mono> {
match self.tracker.state(MEMBER) {
Some(MemberState::Heard { last }) => Some(last),
_ => None,
}
}
}
#[derive(Debug, Clone)]
enum Kept {
Declared(Rank, InstanceId),
Withdrawn(Rank, InstanceId),
Read(Rank, bool, BTreeSet<InstanceId>),
}
#[derive(Debug, Clone)]
pub struct Arbiter {
iface: IfaceId,
token: KindToken,
template: Template,
params: BTreeMap<String, String>,
deadline: Duration,
binding: Binding,
providers: BTreeMap<Rank, Provider>,
active: Option<Rank>,
started: bool,
moving: bool,
kept: Vec<Kept>,
discards: Discards,
last: Option<Mono>,
}
impl Arbiter {
#[must_use]
pub fn new(declared: &Arbitrated, binding: Binding, params: BTreeMap<String, String>) -> Self {
let providers = binding
.entries()
.iter()
.filter_map(Entry::exact)
.filter_map(|a| Some((binding.rank(&a)?, Provider::new(a, declared.deadline, None))))
.collect();
Self {
iface: declared.iface.clone(),
token: declared.token,
template: declared.template.clone(),
params,
deadline: declared.deadline,
binding,
providers,
active: None,
started: false,
moving: false,
kept: Vec::new(),
discards: Discards::default(),
last: None,
}
}
#[must_use]
pub fn deadline(&self) -> Duration {
self.deadline
}
#[must_use]
pub fn binding(&self) -> &Binding {
&self.binding
}
#[must_use]
pub fn active(&self) -> Option<&Addr> {
self.active
.as_ref()
.and_then(|r| self.providers.get(r))
.map(|p| &p.addr)
}
#[must_use]
pub fn dead_man(&self) -> bool {
self.active.is_none()
}
#[must_use]
pub fn due(&self) -> Option<Mono> {
let p = self.providers.get(self.active.as_ref()?)?;
Some(p.last()?.saturating_add(self.deadline))
}
#[must_use]
pub fn moving(&self) -> bool {
self.moving
}
pub fn providers(&self) -> impl Iterator<Item = &Addr> {
self.providers.values().map(|p| &p.addr)
}
#[must_use]
pub fn counts(&self, a: &Addr) -> Counts {
self.binding
.rank(a)
.and_then(|r| self.providers.get(&r))
.map(|p| p.counts)
.unwrap_or_default()
}
#[must_use]
pub fn discards(&self) -> Discards {
self.discards
}
#[must_use]
pub fn withdrawn(&self, a: &Addr) -> bool {
self.binding
.rank(a)
.and_then(|r| self.providers.get(&r))
.is_some_and(|p| p.withdrawn)
}
pub fn identify(&self, key: &str) -> Result<Addr, Outcome> {
if key.contains('*') {
return Err(Outcome::Wild);
}
let Ok(ZkKey::Data {
addr,
iface,
kind,
resource,
}) = parse(key)
else {
return Err(Outcome::Unresolved);
};
if iface != self.iface || kind != self.token {
return Err(Outcome::Unresolved);
}
let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
let Some(values) = self.template.matches(&chunks) else {
return Err(Outcome::Unresolved);
};
for (name, vs) in &values {
match (self.params.get(name), vs.as_slice()) {
(Some(p), [v]) if p == v => {}
_ => return Err(Outcome::Unresolved),
}
}
if self.binding.rank(&addr).is_none() {
return Err(Outcome::Unbound);
}
Ok(addr)
}
pub fn start(&mut self, at: Mono) -> Step {
if self.started {
return Step::default();
}
self.started = true;
self.active = None;
self.last = Some(at);
for p in self.providers.values_mut() {
p.tracker.observe(at, timing::Event::Start);
}
Step {
switches: vec![Switch {
from: None,
to: None,
cause: Cause::Start,
last: None,
}],
..Step::default()
}
}
pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Step {
let mut step = Step::default();
if !self.started {
return step;
}
debug_assert!(
self.last.is_none_or(|l| at >= l),
"an event at {at:?} precedes the last one, at {:?}",
self.last
);
self.last = Some(at);
if let Some(r) = self.active.clone()
&& !self.eligible(&r, at)
{
let next = self.select(at);
step.switches.push(self.switch_to(next, Cause::Deadline));
}
let mut reread = Vec::new();
let mut arrival = None;
match event {
Event::Sample(s) => match self.identify(s.key) {
Err(o) => {
match o {
Outcome::Wild => self.discards.wild += 1,
Outcome::Unbound => self.discards.unbound += 1,
_ => self.discards.unresolved += 1,
}
step.outcome = Some(o);
}
Ok(addr) => {
if let Some(r) = self.provider(addr, at)
&& let Some(p) = self.providers.get_mut(&r)
{
if s.delete {
p.counts.deleted += 1;
step.outcome = Some(Outcome::Deleted);
} else if s.expired {
p.counts.expired += 1;
step.outcome = Some(Outcome::Expired);
} else if s.not_incumbent {
p.counts.not_incumbent += 1;
step.outcome = Some(Outcome::NotIncumbent);
} else {
if !p.withdrawn {
p.tracker.observe(
at,
timing::Event::Arrival {
member: MEMBER,
expired: false,
},
);
p.arrived = Some(at);
}
arrival = Some(r);
}
}
}
},
Event::Declared(key) => {
if let Some((r, i)) = self.token(key, at) {
if self.moving {
self.kept.push(Kept::Declared(r, i));
} else if let Some(p) = self.providers.get_mut(&r) {
p.held.insert(i);
p.withdrawn = false;
}
}
}
Event::Withdrawn(key) => {
if let Some((r, i)) = self.token(key, at) {
if self.moving {
self.kept.push(Kept::Withdrawn(r, i));
} else if let Some(p) = self.providers.get_mut(&r) {
p.held.remove(&i);
if p.held.is_empty() {
p.withdraw(self.deadline, at);
reread.push(r);
}
}
}
}
Event::Read {
address,
complete,
held,
} => {
if let Some(r) = self.provider(address, at) {
if self.moving {
self.kept.push(Kept::Read(r, complete, held));
} else if let Some(p) = self.providers.get_mut(&r) {
read_into(&mut p.held, complete, held);
if !p.held.is_empty() {
p.withdrawn = false;
}
}
}
}
Event::Moved => self.moving = true,
Event::Stood => {
if self.moving {
self.stand(at, &mut reread);
}
}
Event::Tick => {}
}
let next = self.select(at);
if next != self.active {
let cause = if arrival.is_some() && next == arrival {
Cause::Sample
} else {
debug_assert!(
self.active
.as_ref()
.and_then(|r| self.providers.get(r))
.is_some_and(|p| p.withdrawn),
"a switch at {at:?} that is no arrival's, from a provider not withdrawn"
);
Cause::Withdrawn
};
step.switches.push(self.switch_to(next, cause));
}
if let Some(r) = arrival {
let delivered = self.active.as_ref() == Some(&r);
if let Some(p) = self.providers.get_mut(&r) {
step.outcome = Some(if delivered {
p.counts.delivered += 1;
Outcome::Delivered
} else {
p.counts.not_active += 1;
Outcome::NotActive
});
}
}
reread.sort();
reread.dedup();
step.reread = reread
.iter()
.filter_map(|r| self.providers.get(r))
.map(|p| p.addr.clone())
.collect();
step
}
fn eligible(&self, r: &Rank, at: Mono) -> bool {
self.providers.get(r).is_some_and(|p| {
!p.withdrawn
&& p.last()
.is_some_and(|l| at <= l.saturating_add(self.deadline))
})
}
fn select(&self, at: Mono) -> Option<Rank> {
self.providers
.keys()
.find(|r| self.eligible(r, at))
.cloned()
}
fn switch_to(&mut self, next: Option<Rank>, cause: Cause) -> Switch {
let addr = |r: &Option<Rank>| {
r.as_ref()
.and_then(|r| self.providers.get(r))
.map(|p| p.addr.clone())
};
let switch = Switch {
from: addr(&self.active),
to: addr(&next),
cause,
last: self
.active
.as_ref()
.and_then(|r| self.providers.get(r))
.and_then(|p| p.arrived),
};
self.active = next;
switch
}
fn provider(&mut self, addr: Addr, at: Mono) -> Option<Rank> {
let r = self.binding.rank(&addr)?;
let deadline = self.deadline;
self.providers
.entry(r.clone())
.or_insert_with(|| Provider::new(addr, deadline, Some(at)));
Some(r)
}
fn token(&mut self, key: &str, at: Mono) -> Option<(Rank, InstanceId)> {
let Ok(ZkKey::Alive {
addr,
iface,
instance,
..
}) = parse(key)
else {
return None;
};
if iface != self.iface {
return None;
}
Some((self.provider(addr, at)?, instance))
}
fn stand(&mut self, at: Mono, reread: &mut Vec<Rank>) {
self.moving = false;
let mut touched: BTreeMap<Rank, (bool, bool)> = BTreeMap::new();
for k in std::mem::take(&mut self.kept) {
let r = match &k {
Kept::Declared(r, _) | Kept::Withdrawn(r, _) | Kept::Read(r, _, _) => r.clone(),
};
let Some(p) = self.providers.get_mut(&r) else {
continue;
};
let t = touched.entry(r).or_insert((p.withdrawn, false));
match k {
Kept::Declared(_, i) => {
p.held.insert(i);
}
Kept::Withdrawn(_, i) => {
p.held.remove(&i);
t.1 = true;
}
Kept::Read(_, complete, held) => read_into(&mut p.held, complete, held),
}
}
for (r, (before, withdrawal)) in touched {
let Some(p) = self.providers.get_mut(&r) else {
continue;
};
if p.held.is_empty() && withdrawal {
p.withdraw(self.deadline, at);
reread.push(r);
} else if !p.held.is_empty() && before {
p.withdrawn = false;
}
}
}
}
fn read_into(known: &mut BTreeSet<InstanceId>, complete: bool, held: BTreeSet<InstanceId>) {
if complete {
*known = held;
} else {
known.extend(held);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Holding {
Declared(Addr, InstanceId),
Withdrawn(Addr, InstanceId),
Read(Addr, bool, BTreeSet<InstanceId>),
}
impl Holding {
#[must_use]
pub fn of_token(key: &str, put: bool, iface: &IfaceId, binding: &Binding) -> Option<Self> {
let Ok(ZkKey::Alive {
addr,
iface: i,
instance,
..
}) = parse(key)
else {
return None;
};
if i != *iface || binding.rank(&addr).is_none() {
return None;
}
Some(if put {
Self::Declared(addr, instance)
} else {
Self::Withdrawn(addr, instance)
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Incumbents {
holders: BTreeMap<Addr, BTreeSet<InstanceId>>,
zids: BTreeMap<(Addr, InstanceId), u128>,
kept: Vec<Holding>,
}
impl Incumbents {
pub fn hear(&mut self, h: Holding, moving: bool) {
if moving {
self.kept.push(h);
} else {
self.apply(h);
}
}
pub fn stood(&mut self) {
for h in std::mem::take(&mut self.kept) {
self.apply(h);
}
}
fn apply(&mut self, h: Holding) {
match h {
Holding::Declared(a, i) => {
self.holders.entry(a).or_default().insert(i);
}
Holding::Withdrawn(a, i) => {
self.holders.entry(a).or_default().remove(&i);
}
Holding::Read(a, complete, held) => {
read_into(self.holders.entry(a).or_default(), complete, held)
}
}
}
pub fn described(&mut self, addr: Addr, instance: InstanceId, zid: u128) {
self.zids.insert((addr, instance), zid);
}
#[must_use]
pub fn accepts(&self, addr: &Addr, id: Option<u128>) -> bool {
let Some(lowest) = self.holders.get(addr).and_then(|h| h.iter().next()) else {
return false;
};
let Some(zid) = self.zids.get(&(addr.clone(), lowest.clone())) else {
return false;
};
id == Some(*zid)
}
#[must_use]
pub fn undescribed(&self) -> Vec<(Addr, InstanceId)> {
self.holders
.iter()
.flat_map(|(a, is)| is.iter().map(move |i| (a.clone(), i.clone())))
.filter(|k| !self.zids.contains_key(k))
.collect()
}
}
#[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 {
NoContract,
NotArbitrated,
RevisionsDisagree,
NoProviderContract,
Invalid,
Valid,
Unbound,
NotListened,
Lost,
Selected,
Listening,
DeadMan,
Wildcard,
Shadowed,
Exact,
NoDescriptor,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NoContract => "no_contract",
Self::NotArbitrated => "not_arbitrated",
Self::RevisionsDisagree => "revisions_disagree",
Self::NoProviderContract => "no_provider_contract",
Self::Invalid => "invalid",
Self::Valid => "valid",
Self::Unbound => "unbound",
Self::NotListened => "not_listened",
Self::Lost => "lost",
Self::Selected => "selected",
Self::Listening => "listening",
Self::DeadMan => "dead_man",
Self::Wildcard => "wildcard",
Self::Shadowed => "shadowed",
Self::Exact => "exact",
Self::NoDescriptor => "no_descriptor",
}
}
}
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, PartialEq, Eq)]
pub enum Held {
NoContract,
RevisionsDisagree,
Read(Declaration),
}
#[must_use]
pub fn held_over(
role: &Role<'_>,
revisions: &[Revision<'_>],
params: &BTreeMap<String, String>,
) -> Held {
let mut seen: Option<Declaration> = None;
for rev in revisions {
let d = declaration(role, Some(rev), params);
match &seen {
None => seen = Some(d),
Some(s) if *s == d => {}
Some(_) => return Held::RevisionsDisagree,
}
}
Held::Read(seen.unwrap_or_else(|| declaration(role, None, params)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct View {
pub listened: Duration,
pub lost: bool,
pub active: Option<Addr>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reading {
pub declaration: Held,
pub binding: Option<Binding>,
pub view: Option<View>,
}
fn premises(r: &Reading) -> Result<(), Judged> {
match &r.declaration {
Held::NoContract => Err(Judged::new(Answer::Unobservable, Reason::NoContract)),
Held::Read(Declaration::NotArbitrated) => {
Err(Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated))
}
_ => Ok(()),
}
}
#[must_use]
pub fn judge_declaration(r: &Reading) -> (Judged, Vec<Invalid>) {
match &r.declaration {
Held::NoContract => (
Judged::new(Answer::Unobservable, Reason::NoContract),
Vec::new(),
),
Held::Read(Declaration::NotArbitrated) => (
Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated),
Vec::new(),
),
Held::RevisionsDisagree => (
Judged::new(Answer::Unobservable, Reason::RevisionsDisagree),
Vec::new(),
),
Held::Read(Declaration::Unread) => (
Judged::new(Answer::Unobservable, Reason::NoProviderContract),
Vec::new(),
),
Held::Read(Declaration::Invalid(why)) => {
(Judged::new(Answer::No, Reason::Invalid), why.clone())
}
Held::Read(Declaration::Arbitrated(_)) => {
(Judged::new(Answer::Yes, Reason::Valid), Vec::new())
}
}
}
#[must_use]
pub fn judge_selection(r: &Reading) -> (Judged, Option<Addr>) {
if let Err(j) = premises(r) {
return (j, None);
}
let Some(binding) = &r.binding else {
return (Judged::new(Answer::NotAsked, Reason::NoDescriptor), None);
};
let deadline = match &r.declaration {
Held::Read(Declaration::Arbitrated(a)) => a.deadline,
Held::Read(Declaration::Invalid(_)) => {
return (Judged::new(Answer::Unobservable, Reason::Invalid), None);
}
_ => return (judge_declaration(r).0, None),
};
if binding.is_empty() {
return (Judged::new(Answer::No, Reason::Unbound), None);
}
let Some(view) = &r.view else {
return (Judged::new(Answer::NotAsked, Reason::NotListened), None);
};
if view.lost {
return (Judged::new(Answer::Unobservable, Reason::Lost), None);
}
if let Some(a) = &view.active {
return (Judged::new(Answer::Yes, Reason::Selected), Some(a.clone()));
}
if view.listened < deadline {
return (Judged::new(Answer::Unobservable, Reason::Listening), None);
}
(Judged::new(Answer::No, Reason::DeadMan), None)
}
#[must_use]
pub fn judge_binding(r: &Reading) -> (Judged, Vec<usize>, Vec<usize>) {
if let Err(j) = premises(r) {
return (j, Vec::new(), Vec::new());
}
let Some(binding) = &r.binding else {
return (
Judged::new(Answer::NotAsked, Reason::NoDescriptor),
Vec::new(),
Vec::new(),
);
};
let wild = binding.wildcards();
let shadowed = binding.shadowed();
if !wild.is_empty() {
return (Judged::new(Answer::Yes, Reason::Wildcard), wild, shadowed);
}
if !shadowed.is_empty() {
return (
Judged::new(Answer::Yes, Reason::Shadowed),
Vec::new(),
shadowed,
);
}
(
Judged::new(Answer::No, Reason::Exact),
Vec::new(),
Vec::new(),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn arbitrated(deadline_ms: u64) -> Arbitrated {
Arbitrated {
policy: Policy::Priority,
iface: "steer.v1".parse().unwrap(),
token: KindToken::Stream,
template: Template::parse("cmd").unwrap(),
deadline: Duration::from_millis(deadline_ms),
period: None,
}
}
fn arbiter() -> Arbiter {
Arbiter::new(
&arbitrated(300),
Binding::parse(&["lab/safety", "lab/teleop"]).unwrap(),
BTreeMap::new(),
)
}
const SAFETY: &str = "zk2/lab/safety/steer.v1/stream/cmd";
#[test]
fn nothing_before_the_start_and_one_start() {
let mut a = arbiter();
let ms = |n| Mono::after(Duration::from_millis(n));
assert_eq!(
a.observe(ms(0), Event::Sample(Sample::new(SAFETY))),
Step::default()
);
assert_eq!(a.start(ms(1)).switches.len(), 1);
assert_eq!(a.start(ms(2)), Step::default());
assert!(a.dead_man());
let s = a.observe(ms(3), Event::Sample(Sample::new(SAFETY)));
assert_eq!(s.outcome, Some(Outcome::Delivered));
assert_eq!(a.due(), Some(ms(303)));
assert_eq!(a.counts(&"lab/safety".parse().unwrap()).delivered, 1);
}
#[test]
fn a_switch_carries_its_froms_last_arrival() {
let mut a = arbiter();
let ms = |n| Mono::after(Duration::from_millis(n));
assert_eq!(a.start(ms(0)).switches[0].last, None);
let s = a.observe(ms(10), Event::Sample(Sample::new(SAFETY)));
assert_eq!(s.switches[0].last, None, "from the dead-man");
a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
let s = a.observe(ms(400), Event::Tick);
assert_eq!(s.switches[0].cause, Cause::Deadline);
assert_eq!(s.switches[0].last, Some(ms(20)));
a.observe(ms(410), Event::Sample(Sample::new(SAFETY)));
let s = a.observe(
ms(420),
Event::Withdrawn("zk2/lab/safety/@zk/alive/steer.v1/000000000000000a/0123456789abcdef"),
);
assert_eq!(s.switches[0].cause, Cause::Withdrawn);
assert_eq!(
s.switches[0].last,
Some(ms(410)),
"kept across the withdrawal"
);
}
#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "precedes the last one")]
fn an_event_never_goes_back_in_time() {
let mut a = arbiter();
let ms = |n| Mono::after(Duration::from_millis(n));
a.start(ms(10));
a.observe(ms(5), Event::Tick);
}
#[test]
fn entries_parse_and_print() {
for e in ["lab/safety", "lab/*", "*/teleop", "*/*"] {
assert_eq!(Entry::parse(e).unwrap().to_string(), e);
}
for bad in ["lab", "lab/Safety", "lab/**", "/x"] {
assert!(Entry::parse(bad).is_err(), "{bad}");
}
}
}