use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::authoring::{Kind, ParamType};
use crate::contract::Resource;
use crate::freshness;
use crate::grammar::{self, Addr, IfaceId, Key, KindToken, ZkKey};
use crate::seed::Stamp;
use crate::template::{Bindings, Template};
pub mod v2;
pub const PROFILE: &str = "desired.v1";
pub const NAME: &str = "desired";
pub const TARGET_PARAM: &str = "desired.target_param";
pub const VOCABULARY: &[&str] = &["target_param"];
pub const SCHEMA_STEM: &str = "desired.v1";
pub const REPORT: &str = "desired.v1.Report";
pub const VERSION: &str = "desired.v1.Version";
pub const REFUSAL: &str = "desired.v1.Refusal";
pub const PUBLISHED: &[&str] = &[
"sha256:8c5ffce35fadeb6196233a46e163ee3b15cbd2bd8339a05de2cf8fe22b52e9ef",
"sha256:43c952598f454ec903dba63bad36419f5dcff3312db727bd4e58a88dc1ca55ae",
];
#[must_use]
pub fn is_published(id: &str) -> bool {
PUBLISHED.contains(&id)
}
pub const SELF_SYSTEM: &str = "self.system";
pub const SELF_SERVICE: &str = "self.service";
pub const MAX_CODE: usize = 64;
pub const UNDECODABLE: &str = "undecodable";
pub const REACH: &str = "reach";
pub const SENSITIVE: &str = "sensitive";
pub const INVALID: &str = "invalid";
pub const APPLY: &str = "apply";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Binds {
Either,
System,
Service,
}
impl Binds {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Either => "either",
Self::System => SELF_SYSTEM,
Self::Service => SELF_SERVICE,
}
}
#[must_use]
pub fn admits(self, bound: &str) -> bool {
match self {
Self::Either => bound == SELF_SYSTEM || bound == SELF_SERVICE,
Self::System => bound == SELF_SYSTEM,
Self::Service => bound == SELF_SERVICE,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetParam {
pub param: String,
pub binds: Binds,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
NotState,
Value,
Repeated,
NotAParam,
RestParam,
ParamNotTarget,
NotString,
HorizonV1,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotState => "not_state",
Self::Value => "value",
Self::Repeated => "repeated",
Self::NotAParam => "not_a_param",
Self::RestParam => "rest_param",
Self::ParamNotTarget => "param_not_target",
Self::NotString => "not_string",
Self::HorizonV1 => "horizon_v1",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotState => "a desired document is state of its author",
Self::Value => "desired.target_param is a string, or an array of one or two strings",
Self::Repeated => "a target parameter is named twice",
Self::NotAParam => "a name is no parameter of the template",
Self::RestParam => "a rest parameter cannot be a target parameter",
Self::ParamNotTarget => {
"every template parameter must be a target parameter: one document per target"
}
Self::NotString => "a target parameter holds a system or a service name, a string",
Self::HorizonV1 => {
"a horizon above 0 is confirmed by a heartbeat: the contract must use freshness.v2"
}
}
}
}
impl fmt::Display for Invalid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.says())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
NotThisProfiles,
Invalid(Vec<Invalid>),
Declared(Vec<TargetParam>),
}
impl Declaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotThisProfiles => "not_this_profiles",
Self::Invalid(_) => "invalid",
Self::Declared(_) => "declared",
}
}
#[must_use]
pub fn targets(&self) -> Option<&[TargetParam]> {
match self {
Self::Declared(t) => Some(t),
_ => None,
}
}
}
#[must_use]
pub fn declaration(
kind: Kind,
template: &Template,
params: &BTreeMap<String, ParamType>,
annotations: &BTreeMap<String, Value>,
) -> Declaration {
let Some(v) = annotations.get(TARGET_PARAM) else {
return Declaration::NotThisProfiles;
};
let typed = params;
let params: Vec<(&str, bool)> = template.params().collect();
let mut why = Vec::new();
if kind != Kind::State {
why.push(Invalid::NotState);
}
let names: Option<Vec<&str>> = match v {
Value::String(s) => Some(vec![s.as_str()]),
Value::Array(a) if (1..=2).contains(&a.len()) => {
a.iter().map(Value::as_str).collect::<Option<Vec<_>>>()
}
_ => None,
};
match &names {
None => why.push(Invalid::Value),
Some(names) => {
if names.len() == 2 && names[0] == names[1] {
why.push(Invalid::Repeated);
}
if names.iter().any(|n| !params.iter().any(|(p, _)| p == n)) {
why.push(Invalid::NotAParam);
}
if names
.iter()
.any(|n| params.iter().any(|(p, rest)| *rest && p == n))
{
why.push(Invalid::RestParam);
}
if params.iter().any(|(p, _)| !names.contains(p)) {
why.push(Invalid::ParamNotTarget);
}
if names.iter().any(|n| {
params.iter().any(|(p, rest)| !*rest && p == n)
&& typed.get(*n).is_some_and(|t| *t != ParamType::String)
}) {
why.push(Invalid::NotString);
}
}
}
match names {
Some(names) if why.is_empty() => Declaration::Declared(match names.as_slice() {
[one] => vec![TargetParam {
param: (*one).to_owned(),
binds: Binds::Either,
}],
[first, second] => vec![
TargetParam {
param: (*first).to_owned(),
binds: Binds::System,
},
TargetParam {
param: (*second).to_owned(),
binds: Binds::Service,
},
],
_ => return Declaration::Invalid(vec![Invalid::Value]),
}),
_ => Declaration::Invalid(why),
}
}
#[must_use]
pub fn declaration_of(r: &Resource) -> Declaration {
declaration(r.kind, &r.template, &r.params, &r.annotations)
}
#[derive(Debug, Clone, Copy)]
pub struct Requirement<'a> {
pub bindings: &'a [String],
pub params: &'a BTreeMap<String, String>,
pub optional: bool,
pub documents: usize,
}
#[derive(Debug, Clone, Copy)]
pub struct Slice<'a> {
pub iface: &'a IfaceId,
pub token: KindToken,
pub template: &'a Template,
pub targets: &'a [TargetParam],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BindingProblem {
RequiredUnbound,
TwoDocuments,
NotOneAuthor,
TargetUnbound,
NotSelf,
WrongSelf,
}
impl BindingProblem {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::RequiredUnbound => "required_unbound",
Self::TwoDocuments => "two_documents",
Self::NotOneAuthor => "not_one_author",
Self::TargetUnbound => "target_unbound",
Self::NotSelf => "not_self",
Self::WrongSelf => "wrong_self",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Binding {
Unbound,
Invalid(Vec<BindingProblem>),
Bound { key: Key },
}
impl Binding {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Unbound => "unbound",
Self::Invalid(_) => "invalid",
Self::Bound { .. } => "bound",
}
}
}
fn one_author(bindings: &[String]) -> Option<Addr> {
let [one] = bindings else {
return None;
};
if one.split('/').any(|c| c == "*") {
return None;
}
one.parse().ok()
}
#[must_use]
pub fn binding(slice: &Slice<'_>, req: &Requirement<'_>, own: &Addr) -> Binding {
if req.bindings.is_empty() {
return if req.optional {
Binding::Unbound
} else {
Binding::Invalid(vec![BindingProblem::RequiredUnbound])
};
}
if req.documents > 1 {
return Binding::Invalid(vec![BindingProblem::TwoDocuments]);
}
let mut why = Vec::new();
let author = one_author(req.bindings);
if author.is_none() {
why.push(BindingProblem::NotOneAuthor);
}
let bound = |t: &TargetParam| req.params.get(&t.param).map(String::as_str);
if slice.targets.iter().any(|t| bound(t).is_none()) {
why.push(BindingProblem::TargetUnbound);
}
if slice
.targets
.iter()
.filter_map(bound)
.any(|b| b != SELF_SYSTEM && b != SELF_SERVICE)
{
why.push(BindingProblem::NotSelf);
}
if slice.targets.iter().any(|t| {
bound(t).is_some_and(|b| (b == SELF_SYSTEM || b == SELF_SERVICE) && !t.binds.admits(b))
}) {
why.push(BindingProblem::WrongSelf);
}
let Some(author) = author.filter(|_| why.is_empty()) else {
return Binding::Invalid(why);
};
let mut values = Bindings::new();
for t in slice.targets {
let v = if bound(t) == Some(SELF_SYSTEM) {
own.system.as_str()
} else {
own.service.as_str()
};
values.insert(t.param.clone(), vec![v.to_owned()]);
}
let built = slice.template.build(&values).ok().and_then(|chunks| {
let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
grammar::data_key(&author, slice.iface, slice.token, &refs).ok()
});
match built {
Some(key) => Binding::Bound { key },
None => Binding::Invalid(vec![BindingProblem::TargetUnbound]),
}
}
#[must_use]
pub fn parse_stamp(s: &str) -> Option<Stamp> {
let (time, id) = s.split_once('/')?;
let digits = !time.is_empty() && time.bytes().all(|b| b.is_ascii_digit());
if !digits || (time.len() > 1 && time.starts_with('0')) {
return None;
}
Stamp::parse(time.parse().ok()?, id)
}
mod stamp_text {
use serde::{Deserialize, Deserializer, Serializer};
use super::{Stamp, parse_stamp};
pub fn serialize<S: Serializer>(s: &Stamp, ser: S) -> Result<S::Ok, S::Error> {
ser.collect_str(s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Stamp, D::Error> {
let s = String::deserialize(de)?;
parse_stamp(&s).ok_or_else(|| serde::de::Error::custom(format!("{s:?} is no stamp")))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Source {
Baseline,
Desired,
Call,
}
impl Source {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Baseline => "baseline",
Self::Desired => "desired",
Self::Call => "call",
}
}
fn parse(s: &str) -> Option<Self> {
[Self::Baseline, Self::Desired, Self::Call]
.into_iter()
.find(|v| v.as_str() == s)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Converged,
Refused,
Failed,
Reverted,
}
impl Outcome {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Converged => "converged",
Self::Refused => "refused",
Self::Failed => "failed",
Self::Reverted => "reverted",
}
}
fn parse(s: &str) -> Option<Self> {
[Self::Converged, Self::Refused, Self::Failed, Self::Reverted]
.into_iter()
.find(|v| v.as_str() == s)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Version {
#[serde(with = "stamp_text")]
pub stamp: Stamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revision: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Refusal {
pub code: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pointer: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
impl Refusal {
#[must_use]
pub fn new(code: impl Into<String>) -> Self {
Self {
code: code.into(),
pointer: None,
detail: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Report {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
pub source: Source,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub in_force: Option<Version>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed: Option<Version>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<Outcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refusal: Option<Refusal>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub last_known: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unreadable {
Json(String),
Schema(String),
Stamp(String),
RevisionRange(&'static str),
}
impl Unreadable {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Json(_) => "json",
Self::Schema(_) => "schema",
Self::Stamp(_) => "stamp",
Self::RevisionRange(_) => "revision_range",
}
}
}
impl fmt::Display for Unreadable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Json(e) => write!(f, "not strict JSON: {e}"),
Self::Schema(e) => write!(f, "not a desired.v1.Report: {e}"),
Self::Stamp(s) => write!(f, "{s:?} is not a stamp as zenoh writes one"),
Self::RevisionRange(m) => write!(f, "/{m}/revision is above 2^64-1"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Finding {
Escape,
RunFields,
Keyless,
KeyForm,
ObservedOutcome,
Refusal,
Source,
InForce,
RevisionOnRevert,
LastKnown,
}
impl Finding {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Escape => "escape",
Self::RunFields => "run_fields",
Self::Keyless => "keyless",
Self::KeyForm => "key_form",
Self::ObservedOutcome => "observed_outcome",
Self::Refusal => "refusal",
Self::Source => "source",
Self::InForce => "in_force",
Self::RevisionOnRevert => "revision_on_revert",
Self::LastKnown => "last_known",
}
}
}
enum RevisionRead {
InRange(u64),
TooLarge,
}
fn exact_revision(canonical: &str) -> Option<RevisionRead> {
if canonical == "0" {
return Some(RevisionRead::InRange(0));
}
if canonical.starts_with('-') {
return None;
}
let (digits, exp) = canonical.split_once('e')?;
let exp: i128 = exp.parse().ok()?;
if exp < 0 {
return None;
}
let Ok(zeros) = usize::try_from(exp) else {
return Some(RevisionRead::TooLarge);
};
if digits.len().saturating_add(zeros) > 20 {
return Some(RevisionRead::TooLarge);
}
let text = format!("{digits}{}", "0".repeat(zeros));
Some(
text.parse::<u64>()
.map_or(RevisionRead::TooLarge, RevisionRead::InRange),
)
}
#[must_use]
pub fn revision_of_text(bytes: &[u8]) -> Option<u64> {
let text = std::str::from_utf8(bytes).ok()?;
match Exact::of_strict_text(text)? {
Exact::Object(m) => match m.get("revision")? {
Exact::Number(n) => match exact_revision(n)? {
RevisionRead::InRange(r) => Some(r),
RevisionRead::TooLarge => None,
},
_ => None,
},
_ => None,
}
}
#[must_use]
pub fn revision_of_value(v: &Value) -> Option<u64> {
match v.get("revision")? {
Value::String(s) if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) => {
s.parse().ok()
}
r => match revision(r)? {
RevisionRead::InRange(n) => Some(n),
RevisionRead::TooLarge => None,
},
}
}
fn revision(v: &Value) -> Option<RevisionRead> {
let Value::Number(n) = v else {
return None;
};
if let Some(u) = n.as_u64() {
return Some(RevisionRead::InRange(u));
}
if n.as_i64().is_some() {
return None; }
let f = n.as_f64()?;
if !(f.is_finite() && f >= 0.0 && f.fract() == 0.0) {
return None;
}
if f >= 2.0_f64.powi(64) {
return Some(RevisionRead::TooLarge);
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let n = f as u64;
Some(RevisionRead::InRange(n))
}
struct RawVersion<'a> {
stamp: &'a str,
revision: Option<RevisionRead>,
}
fn raw_version<'a>(
v: &'a Value,
member: &str,
exact: Option<&Exact>,
) -> Result<RawVersion<'a>, Unreadable> {
let schema = |why: &str| Unreadable::Schema(format!("/{member}{why}"));
let Value::Object(o) = v else {
return Err(schema(": not an object"));
};
let stamp = match o.get("stamp") {
Some(Value::String(s)) if s.chars().count() >= 3 => s.as_str(),
Some(Value::String(_)) => return Err(schema("/stamp: shorter than 3 characters")),
Some(_) => return Err(schema("/stamp: not a string")),
None => return Err(schema("/stamp: missing")),
};
let exact = match exact {
Some(Exact::Object(m)) => match m.get("revision") {
Some(Exact::Number(n)) => Some(n.as_str()),
_ => None,
},
_ => None,
};
let revision = match (o.get("revision"), exact) {
(None, _) => None,
(Some(Value::Number(_)), Some(text)) => {
Some(exact_revision(text).ok_or_else(|| schema("/revision: not an integer from 0"))?)
}
(Some(r), _) => {
Some(revision(r).ok_or_else(|| schema("/revision: not an integer from 0"))?)
}
};
Ok(RawVersion { stamp, revision })
}
fn optional_string(
o: &serde_json::Map<String, Value>,
m: &str,
at: &str,
) -> Result<Option<String>, Unreadable> {
match o.get(m) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(Unreadable::Schema(format!("{at}/{m}: not a string"))),
}
}
impl Report {
#[must_use]
pub fn baseline(key: Option<String>) -> Self {
Self {
key,
source: Source::Baseline,
in_force: None,
observed: None,
outcome: None,
refusal: None,
last_known: false,
}
}
pub fn from_json(v: &Value) -> Result<Self, Unreadable> {
Self::read(v, None)
}
fn read(v: &Value, exact: Option<&Exact>) -> Result<Self, Unreadable> {
let schema = |why: String| Unreadable::Schema(why);
let Value::Object(o) = v else {
return Err(schema("not an object".into()));
};
let exact_of = |m: &str| match exact {
Some(Exact::Object(e)) => e.get(m),
_ => None,
};
let source = match o.get("source") {
Some(Value::String(s)) => Source::parse(s),
_ => None,
}
.ok_or_else(|| schema("/source: not baseline, desired or call".into()))?;
let key = optional_string(o, "key", "")?;
let in_force = o
.get("in_force")
.map(|v| raw_version(v, "in_force", exact_of("in_force")))
.transpose()?;
let observed = o
.get("observed")
.map(|v| raw_version(v, "observed", exact_of("observed")))
.transpose()?;
let outcome = match o.get("outcome") {
None => None,
Some(Value::String(s)) => Some(Outcome::parse(s).ok_or_else(|| {
schema("/outcome: not converged, refused, failed or reverted".into())
})?),
Some(_) => return Err(schema("/outcome: not a string".into())),
};
let refusal = match o.get("refusal") {
None => None,
Some(Value::Object(r)) => {
let code = match r.get("code") {
Some(Value::String(c)) if (1..=MAX_CODE).contains(&c.chars().count()) => {
c.clone()
}
Some(Value::String(_)) => {
return Err(schema("/refusal/code: not 1 to 64 characters".into()));
}
Some(_) => return Err(schema("/refusal/code: not a string".into())),
None => return Err(schema("/refusal/code: missing".into())),
};
Some(Refusal {
code,
pointer: optional_string(r, "pointer", "/refusal")?,
detail: optional_string(r, "detail", "/refusal")?,
})
}
Some(_) => return Err(schema("/refusal: not an object".into())),
};
let last_known = match o.get("last_known") {
None => false,
Some(Value::Bool(b)) => *b,
Some(_) => return Err(schema("/last_known: not a boolean".into())),
};
let stamp = |r: &RawVersion<'_>| {
parse_stamp(r.stamp).ok_or_else(|| Unreadable::Stamp(r.stamp.to_owned()))
};
let in_force_stamp = in_force.as_ref().map(stamp).transpose()?;
let observed_stamp = observed.as_ref().map(stamp).transpose()?;
let rev = |r: &RawVersion<'_>, m: &'static str| match &r.revision {
None => Ok(None),
Some(RevisionRead::InRange(n)) => Ok(Some(*n)),
Some(RevisionRead::TooLarge) => Err(Unreadable::RevisionRange(m)),
};
let in_force = match (&in_force, in_force_stamp) {
(Some(r), Some(stamp)) => Some(Version {
stamp,
revision: rev(r, "in_force")?,
}),
_ => None,
};
let observed = match (&observed, observed_stamp) {
(Some(r), Some(stamp)) => Some(Version {
stamp,
revision: rev(r, "observed")?,
}),
_ => None,
};
Ok(Self {
key,
source,
in_force,
observed,
outcome,
refusal,
last_known,
})
}
#[must_use]
pub fn check(&self) -> Vec<Finding> {
let mut out = Vec::new();
if self.key.is_none() && (self.source != Source::Baseline || self.observed.is_some()) {
out.push(Finding::Keyless);
}
if let Some(k) = &self.key
&& !matches!(
grammar::parse(k),
Ok(ZkKey::Data {
kind: KindToken::State | KindToken::ExplicitState,
..
})
)
{
out.push(Finding::KeyForm);
}
if self.observed.is_some() != self.outcome.is_some() {
out.push(Finding::ObservedOutcome);
}
let refusing = matches!(self.outcome, Some(Outcome::Refused | Outcome::Failed));
if self.refusal.is_some() != refusing {
out.push(Finding::Refusal);
}
if (self.source == Source::Desired && self.observed.is_none())
|| (self.outcome == Some(Outcome::Converged) && self.source == Source::Baseline)
|| (self.outcome == Some(Outcome::Reverted) && self.source == Source::Desired)
{
out.push(Finding::Source);
}
let misplaced = self.in_force.is_some()
&& (self.source != Source::Desired || self.outcome == Some(Outcome::Failed));
let not_observed = self.outcome == Some(Outcome::Converged)
&& self.source == Source::Desired
&& self.in_force != self.observed;
if misplaced || not_observed {
out.push(Finding::InForce);
}
if self.outcome == Some(Outcome::Reverted)
&& self.observed.is_some_and(|o| o.revision.is_some())
{
out.push(Finding::RevisionOnRevert);
}
if self.last_known && self.observed.is_none() {
out.push(Finding::LastKnown);
}
out
}
#[must_use]
pub fn to_json(&self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
}
pub const MAX_DEPTH: usize = crate::telemetry::decode::MAX_DEPTH;
#[must_use]
pub fn strict_json(bytes: &[u8]) -> Option<Value> {
fn value(d: &crate::telemetry::Datum) -> Option<Value> {
use crate::telemetry::Datum as D;
let float = |f: f64| serde_json::Number::from_f64(f).map(Value::Number);
Some(match d {
D::Null => Value::Null,
D::Bool(b) => Value::Bool(*b),
D::Int(i) => match (u64::try_from(*i), i64::try_from(*i)) {
(Ok(u), _) => Value::from(u),
(_, Ok(i)) => Value::from(i),
#[allow(clippy::cast_precision_loss)]
_ => float(*i as f64)?,
},
D::BigInt(f) | D::Float(f) => float(*f)?,
D::Text(t) => Value::String(t.clone()),
D::Array(a) => Value::Array(a.iter().map(value).collect::<Option<_>>()?),
D::Map(m) => Value::Object(
m.iter()
.map(|(k, v)| Some((k.clone(), value(v)?)))
.collect::<Option<_>>()?,
),
D::Bytes(_) => return None,
})
}
value(&crate::telemetry::decode::json(bytes)?)
}
pub fn decode(bytes: &[u8]) -> Result<Report, Unreadable> {
let v = strict_json(bytes).ok_or_else(|| {
Unreadable::Json(format!(
"not strict JSON: UTF-8, RFC 8259, no duplicate member, every number finite, at most {MAX_DEPTH} deep"
))
})?;
let exact = std::str::from_utf8(bytes)
.ok()
.and_then(Exact::of_strict_text);
Report::read(&v, exact.as_ref())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Via {
Owner,
Archive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mutation {
Put,
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Content([u8; 32]);
impl Content {
fn digest(bytes: &[u8]) -> Self {
use sha2::{Digest, Sha256};
let mut d = [0u8; 32];
d.copy_from_slice(&Sha256::digest(bytes));
Self(d)
}
#[must_use]
pub fn of_json(v: &Value) -> Self {
let mut out = Vec::new();
Exact::of_value(v).write(&mut out);
Self::digest(&out)
}
#[must_use]
pub fn of_bytes(bytes: &[u8]) -> Self {
Self::digest(bytes)
}
#[must_use]
pub fn of_payload(bytes: &[u8], json: bool) -> Self {
let read = json
.then(|| std::str::from_utf8(bytes).ok())
.flatten()
.and_then(Exact::of_strict_text);
match read {
Some(e) => {
let mut out = Vec::new();
e.write(&mut out);
Self::digest(&out)
}
None => Self::of_bytes(bytes),
}
}
}
#[must_use]
pub fn exact_number(text: &str) -> Option<String> {
let (neg, rest) = match text.strip_prefix('-') {
Some(r) => (true, r),
None => (false, text),
};
let (mantissa, exp) = match rest.find(['e', 'E']) {
Some(i) => (&rest[..i], Some(&rest[i + 1..])),
None => (rest, None),
};
let (int, frac) = match mantissa.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (mantissa, None),
};
let digits = |d: &str| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit());
if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
return None;
}
if frac.is_some_and(|f| !digits(f)) {
return None;
}
let exp: i128 = match exp {
None => 0,
Some(e) => {
let body = e.strip_prefix(['+', '-']).unwrap_or(e);
if !digits(body) {
return None;
}
e.parse().ok()?
}
};
let frac = frac.unwrap_or("");
let all: String = [int, frac].concat();
let significant = all.trim_start_matches('0');
if significant.is_empty() {
return Some("0".to_owned());
}
let kept = significant.trim_end_matches('0');
let trailing = i128::try_from(significant.len() - kept.len()).ok()?;
let exp = exp
.checked_sub(i128::try_from(frac.len()).ok()?)?
.checked_add(trailing)?;
Some(format!("{}{kept}e{exp}", if neg { "-" } else { "" }))
}
enum Exact {
Null,
Bool(bool),
Number(String),
Text(String),
Array(Vec<Exact>),
Object(BTreeMap<String, Exact>),
}
impl Exact {
fn of_value(v: &Value) -> Self {
match v {
Value::Null => Self::Null,
Value::Bool(b) => Self::Bool(*b),
Value::Number(n) => {
let text = match (n.as_u64(), n.as_i64(), n.as_f64()) {
(Some(u), _, _) => u.to_string(),
(None, Some(i), _) => i.to_string(),
(None, None, Some(f)) => format!("{f:e}"),
(None, None, None) => n.to_string(),
};
Self::Number(exact_number(&text).unwrap_or(text))
}
Value::String(s) => Self::Text(s.clone()),
Value::Array(a) => Self::Array(a.iter().map(Self::of_value).collect()),
Value::Object(m) => Self::Object(
m.iter()
.map(|(k, v)| (k.clone(), Self::of_value(v)))
.collect(),
),
}
}
fn of_strict_text(text: &str) -> Option<Self> {
crate::telemetry::decode::json(text.as_bytes())?;
let mut r = ExactReader {
text,
s: text.as_bytes(),
at: 0,
};
let v = r.value()?;
r.ws();
(r.at == r.s.len()).then_some(v)
}
fn write(&self, out: &mut Vec<u8>) {
match self {
Self::Null => out.extend_from_slice(b"null"),
Self::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
Self::Number(n) => out.extend_from_slice(n.as_bytes()),
Self::Text(s) => write_string(s, out),
Self::Array(a) => {
out.push(b'[');
for (i, v) in a.iter().enumerate() {
if i > 0 {
out.push(b',');
}
v.write(out);
}
out.push(b']');
}
Self::Object(m) => {
let mut members: Vec<(&String, &Exact)> = m.iter().collect();
members.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
out.push(b'{');
for (i, (k, v)) in members.into_iter().enumerate() {
if i > 0 {
out.push(b',');
}
write_string(k, out);
out.push(b':');
v.write(out);
}
out.push(b'}');
}
}
}
}
fn write_string(s: &str, out: &mut Vec<u8>) {
let quoted = serde_json::to_string(s).unwrap_or_default();
out.extend_from_slice(quoted.as_bytes());
}
struct ExactReader<'a> {
text: &'a str,
s: &'a [u8],
at: usize,
}
impl ExactReader<'_> {
fn ws(&mut self) {
while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.s.get(self.at) {
self.at += 1;
}
}
fn eat(&mut self, b: u8) -> bool {
let hit = self.s.get(self.at) == Some(&b);
if hit {
self.at += 1;
}
hit
}
fn string(&mut self) -> Option<String> {
let start = self.at;
if !self.eat(b'"') {
return None;
}
loop {
match self.s.get(self.at)? {
b'"' => break,
b'\\' => self.at += 2,
_ => self.at += 1,
}
}
self.at += 1;
serde_json::from_str(self.text.get(start..self.at)?).ok()
}
fn value(&mut self) -> Option<Exact> {
self.ws();
match *self.s.get(self.at)? {
b'{' => {
self.at += 1;
let mut m = BTreeMap::new();
self.ws();
if self.eat(b'}') {
return Some(Exact::Object(m));
}
loop {
self.ws();
let k = self.string()?;
self.ws();
if !self.eat(b':') {
return None;
}
let v = self.value()?;
m.insert(k, v);
self.ws();
if self.eat(b'}') {
return Some(Exact::Object(m));
}
if !self.eat(b',') {
return None;
}
}
}
b'[' => {
self.at += 1;
let mut a = Vec::new();
self.ws();
if self.eat(b']') {
return Some(Exact::Array(a));
}
loop {
a.push(self.value()?);
self.ws();
if self.eat(b']') {
return Some(Exact::Array(a));
}
if !self.eat(b',') {
return None;
}
}
}
b'"' => self.string().map(Exact::Text),
b't' | b'f' | b'n' => {
for (word, v) in [
("true", Exact::Bool(true)),
("false", Exact::Bool(false)),
("null", Exact::Null),
] {
if self.s[self.at..].starts_with(word.as_bytes()) {
self.at += word.len();
return Some(v);
}
}
None
}
_ => {
let start = self.at;
while let Some(b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') = self.s.get(self.at)
{
self.at += 1;
}
exact_number(self.text.get(start..self.at)?).map(Exact::Number)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sample {
pub via: Via,
pub mutation: Mutation,
pub stamp: Option<Stamp>,
pub revision: Option<u64>,
pub content: Option<Content>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActKind {
Apply,
Revert,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Act {
pub kind: ActKind,
pub stamp: Stamp,
pub revision: Option<u64>,
pub via: Via,
pub content: Option<Content>,
}
impl Act {
fn of(s: &Sample, stamp: Stamp) -> Self {
Self {
kind: match s.mutation {
Mutation::Put => ActKind::Apply,
Mutation::Delete => ActKind::Revert,
},
stamp,
revision: match s.mutation {
Mutation::Put => s.revision,
Mutation::Delete => None,
},
via: s.via,
content: match s.mutation {
Mutation::Put => s.content,
Mutation::Delete => None,
},
}
}
#[must_use]
pub fn same_document(&self, next: &Act) -> bool {
machine::same_document((self.kind, self.content), (next.kind, next.content))
}
#[must_use]
pub fn version(&self) -> Version {
Version {
stamp: self.stamp,
revision: self.revision,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ended<R = Refusal> {
Done,
Refused(R),
Failed(R),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Act(Act),
Adopted,
Held,
Unstamped,
SameVersion,
Older,
Confirmed,
Done,
}
impl Step {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Act(Act {
kind: ActKind::Apply,
..
}) => "act",
Self::Act(Act {
kind: ActKind::Revert,
..
}) => "revert",
Self::Adopted => "adopted",
Self::Held => "held",
Self::Unstamped => "unstamped",
Self::SameVersion => "same_version",
Self::Older => "older",
Self::Confirmed => "confirmed",
Self::Done => "done",
}
}
}
pub const REMEMBERED_IDS: usize = 16;
pub(crate) mod machine {
use std::cmp::Ordering;
use std::fmt;
use super::{ActKind, Content, Ended, Outcome, REMEMBERED_IDS, Source, Via};
pub(crate) trait Mark: Copy + Eq + fmt::Debug {
type Epoch: Copy + Eq + fmt::Debug;
type Tick: Copy + Ord + fmt::Debug;
fn epoch(&self) -> Self::Epoch;
fn tick(&self) -> Self::Tick;
fn floor(&self) -> bool {
false
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Doing<M> {
pub kind: ActKind,
pub mark: M,
pub revision: Option<u64>,
pub via: Via,
pub content: Option<Content>,
}
pub(crate) fn same_document(
a: (ActKind, Option<Content>),
b: (ActKind, Option<Content>),
) -> bool {
match (a.0, b.0) {
(ActKind::Revert, ActKind::Revert) => true,
(ActKind::Apply, ActKind::Apply) => a.1.is_some() && a.1 == b.1,
_ => false,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Judged<M> {
Act(Doing<M>),
Adopted,
Held,
SameVersion,
Older,
Confirmed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Floored<M> {
NoVerdict,
Older,
Held,
Act(Doing<M>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Finished<M> {
Done,
Adopted,
Act(Doing<M>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Ledger<M, R> {
pub source: Source,
pub in_force: Option<(M, Option<u64>)>,
pub observed: Option<(M, Option<u64>)>,
pub outcome: Option<Outcome>,
pub refusal: Option<R>,
pub last_known: bool,
}
enum Not {
Same,
Older,
}
fn admits<M: Mark>(held: &M, incoming: &M) -> Result<(), Not> {
if held.epoch() != incoming.epoch() {
return Ok(());
}
match incoming.tick().cmp(&held.tick()) {
Ordering::Greater => Ok(()),
Ordering::Equal if !held.floor() => Err(Not::Same),
Ordering::Equal | Ordering::Less => Err(Not::Older),
}
}
fn confirm<M>(slot: &mut Doing<M>, via: Via) -> bool {
let confirmed = via == Via::Owner && slot.via == Via::Archive;
if confirmed {
slot.via = Via::Owner;
}
confirmed
}
#[derive(Debug, Clone)]
pub(crate) struct Core<M: Mark, R> {
acted: Option<Doing<M>>,
running: bool,
waiting: Option<Doing<M>>,
remembered: Vec<(M::Epoch, M::Tick, bool)>,
ledger: Ledger<M, R>,
}
impl<M: Mark, R> Core<M, R> {
pub fn new() -> Self {
Self {
acted: None,
running: false,
waiting: None,
remembered: Vec::new(),
ledger: Ledger {
source: Source::Baseline,
in_force: None,
observed: None,
outcome: None,
refusal: None,
last_known: false,
},
}
}
pub fn ledger(&self) -> &Ledger<M, R> {
&self.ledger
}
pub fn running(&self) -> Option<&Doing<M>> {
self.acted.as_ref().filter(|_| self.running)
}
pub fn latest(&self) -> Option<&Doing<M>> {
self.waiting.as_ref().or(self.acted.as_ref())
}
pub fn remembered(&self, epoch: M::Epoch) -> Option<M::Tick> {
self.remembered_as(epoch).map(|(t, _)| t)
}
fn remembered_as(&self, epoch: M::Epoch) -> Option<(M::Tick, bool)> {
self.remembered
.iter()
.find(|(e, _, _)| *e == epoch)
.map(|(_, t, f)| (*t, *f))
}
fn remember(&mut self, mark: M) {
let (tick, floor) = match self
.remembered
.iter()
.position(|(e, _, _)| *e == mark.epoch())
{
Some(at) => {
let (_, tick, floor) = self.remembered.remove(at);
match mark.tick().cmp(&tick) {
Ordering::Greater => (mark.tick(), mark.floor()),
Ordering::Equal => (tick, floor || mark.floor()),
Ordering::Less => (tick, floor),
}
}
None => (mark.tick(), mark.floor()),
};
self.remembered.insert(0, (mark.epoch(), tick, floor));
self.remembered.truncate(REMEMBERED_IDS);
}
pub fn observe(&mut self, doing: Doing<M>) -> Judged<M> {
let mark = doing.mark;
let remembered = self.remembered_as(mark.epoch());
if let Some(r) = self.acted.as_mut() {
if r.mark.epoch() == mark.epoch() {
match admits(&r.mark, &mark) {
Ok(()) => {}
Err(Not::Same) if confirm(r, doing.via) => {
if !self.running {
self.ledger.last_known = false;
}
return Judged::Confirmed;
}
Err(Not::Same) => return Judged::SameVersion,
Err(Not::Older) => return Judged::Older,
}
} else if let Some((tick, floor)) = remembered {
match mark.tick().cmp(&tick) {
Ordering::Greater => {}
Ordering::Equal if !floor => return Judged::SameVersion,
Ordering::Equal | Ordering::Less => return Judged::Older,
}
}
}
if let Some(w) = self.waiting.as_mut() {
match admits(&w.mark, &mark) {
Ok(()) => {}
Err(Not::Same) if confirm(w, doing.via) => return Judged::Confirmed,
Err(Not::Same) => return Judged::SameVersion,
Err(Not::Older) => return Judged::Older,
}
}
if self.running {
self.waiting = Some(doing);
return Judged::Held;
}
match self.start(doing) {
Finished::Act(a) => Judged::Act(a),
Finished::Adopted | Finished::Done => Judged::Adopted,
}
}
pub fn observe_floor(&mut self, floor: M) -> Floored<M> {
let reverts = |held: &Doing<M>| {
if held.kind != ActKind::Apply || held.mark.epoch() != floor.epoch() {
Err(Floored::NoVerdict)
} else if held.mark.tick() > floor.tick() {
Err(Floored::Older)
} else {
Ok(())
}
};
let Some(acted) = self.acted.as_ref() else {
return Floored::NoVerdict;
};
if let Err(why) = reverts(acted) {
return why;
}
if let Some(Err(why)) = self.waiting.as_ref().map(reverts) {
return why;
}
let doing = Doing {
kind: ActKind::Revert,
mark: floor,
revision: None,
via: Via::Owner,
content: None,
};
if self.running {
self.waiting = Some(doing);
return Floored::Held;
}
match self.start(doing) {
Finished::Act(a) => Floored::Act(a),
Finished::Adopted | Finished::Done => Floored::NoVerdict,
}
}
pub fn unchanged(&mut self, mark: M) -> bool {
if let Some(w) = self.waiting.as_mut().filter(|w| w.mark == mark) {
return confirm(w, Via::Owner);
}
let Some(a) = self.acted.as_mut().filter(|a| a.mark == mark) else {
return false;
};
let confirmed = confirm(a, Via::Owner);
if confirmed && !self.running {
self.ledger.last_known = false;
}
confirmed
}
fn start(&mut self, doing: Doing<M>) -> Finished<M> {
self.remember(doing.mark);
let version = (!doing.mark.floor()).then_some((doing.mark, doing.revision));
if let Some(prev) = self.acted
&& same_document((prev.kind, prev.content), (doing.kind, doing.content))
{
let l = &mut self.ledger;
if !prev.mark.floor() && l.in_force.is_some_and(|(m, _)| m == prev.mark) {
l.in_force = version;
}
l.observed = version;
l.last_known = doing.via == Via::Archive;
self.acted = Some(doing);
return Finished::Adopted;
}
self.acted = Some(doing);
self.running = true;
Finished::Act(doing)
}
pub fn finish(&mut self, ended: Ended<R>) -> Finished<M> {
let Some(act) = self.acted.filter(|_| self.running) else {
return Finished::Done;
};
self.running = false;
let l = &mut self.ledger;
let version = (act.mark, act.revision);
if !act.mark.floor() {
l.observed = Some(version);
l.last_known = act.via == Via::Archive;
} else if matches!(ended, Ended::Done) {
l.observed = None;
l.last_known = false;
}
l.refusal = None;
match (act.kind, ended) {
(ActKind::Apply, Ended::Done) => {
l.source = Source::Desired;
l.in_force = Some(version);
l.outcome = Some(Outcome::Converged);
}
(ActKind::Revert, Ended::Done) => {
l.source = Source::Baseline;
l.in_force = None;
l.outcome = Some(Outcome::Reverted);
}
(ActKind::Apply, Ended::Refused(why)) => {
l.outcome = Some(Outcome::Refused);
l.refusal = Some(why);
}
(kind, Ended::Refused(why) | Ended::Failed(why)) => {
l.source = match kind {
ActKind::Apply => Source::Desired,
ActKind::Revert => Source::Baseline,
};
l.in_force = None;
l.outcome = Some(Outcome::Failed);
l.refusal = Some(why);
}
}
match self.waiting.take() {
Some(next) => self.start(next),
None => Finished::Done,
}
}
pub fn call(&mut self) {
self.ledger.source = Source::Call;
self.ledger.in_force = None;
}
}
}
impl machine::Mark for Stamp {
type Epoch = u128;
type Tick = u64;
fn epoch(&self) -> u128 {
self.id
}
fn tick(&self) -> u64 {
self.time
}
}
impl From<machine::Doing<Stamp>> for Act {
fn from(d: machine::Doing<Stamp>) -> Self {
Self {
kind: d.kind,
stamp: d.mark,
revision: d.revision,
via: d.via,
content: d.content,
}
}
}
#[derive(Debug, Clone)]
pub struct Target {
core: machine::Core<Stamp, Refusal>,
key: Option<String>,
running: Option<Act>,
report: Report,
}
impl Target {
#[must_use]
pub fn new(key: Option<String>) -> Self {
Self {
core: machine::Core::new(),
running: None,
report: Report::baseline(key.clone()),
key,
}
}
#[must_use]
pub fn report(&self) -> &Report {
&self.report
}
#[must_use]
pub fn running(&self) -> Option<&Act> {
self.running.as_ref()
}
#[must_use]
pub fn remembered(&self, id: u128) -> Option<u64> {
self.core.remembered(id)
}
fn sync(&mut self) {
let version = |(stamp, revision): (Stamp, Option<u64>)| Version { stamp, revision };
let l = self.core.ledger();
self.report = Report {
key: self.key.clone(),
source: l.source,
in_force: l.in_force.map(version),
observed: l.observed.map(version),
outcome: l.outcome,
refusal: l.refusal.clone(),
last_known: l.last_known,
};
self.running = self.core.running().map(|d| Act::from(*d));
}
pub fn observe(&mut self, s: Sample) -> Step {
let Some(stamp) = s.stamp else {
return Step::Unstamped;
};
let act = Act::of(&s, stamp);
let step = match self.core.observe(machine::Doing {
kind: act.kind,
mark: stamp,
revision: act.revision,
via: act.via,
content: act.content,
}) {
machine::Judged::Act(d) => Step::Act(d.into()),
machine::Judged::Adopted => Step::Adopted,
machine::Judged::Held => Step::Held,
machine::Judged::SameVersion => Step::SameVersion,
machine::Judged::Older => Step::Older,
machine::Judged::Confirmed => Step::Confirmed,
};
self.sync();
step
}
pub fn finish(&mut self, ended: Ended) -> Step {
let step = match self.core.finish(ended) {
machine::Finished::Done => Step::Done,
machine::Finished::Adopted => Step::Adopted,
machine::Finished::Act(d) => Step::Act(d.into()),
};
self.sync();
step
}
pub fn call(&mut self) {
self.core.call();
self.sync();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Seen {
Present,
Absent,
Incomplete,
AcrossFace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Listing {
NotListed,
Listed { bound: bool },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Facts {
pub source: Source,
pub outcome: Option<Outcome>,
pub last_known: bool,
pub in_force: bool,
}
pub trait Reported {
fn facts(&self) -> Option<Facts>;
}
impl Reported for Report {
fn facts(&self) -> Option<Facts> {
self.check().is_empty().then(|| Facts {
source: self.source,
outcome: self.outcome,
last_known: self.last_known,
in_force: self.in_force.is_some(),
})
}
}
#[derive(Debug)]
pub enum ReportRead<'a, R = Report> {
NotRead,
Unreadable,
Read(&'a R),
}
impl<R> Clone for ReportRead<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R> Copy for ReportRead<'_, R> {}
#[derive(Debug)]
pub struct TargetReading<'a, R = Report> {
pub presence: Seen,
pub descriptor: Option<Listing>,
pub deployment: Option<Listing>,
pub report: ReportRead<'a, R>,
pub freshness: freshness::Verdict,
}
impl<R> Clone for TargetReading<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R> Copy for TargetReading<'_, R> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Current {
NotRead,
Incomplete,
Silent,
Put(Stamp),
Delete(Stamp),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthorReading {
pub presence: Seen,
pub current: Current,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
Yes,
No,
NotYet,
Unobservable,
NotAsked,
}
impl Answer {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::No => "no",
Self::NotYet => "not_yet",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
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 {
TargetAbsent,
PresenceIncomplete,
NoDescriptor,
NotATarget,
Unbound,
NoReport,
NothingCrossed,
ReportInvalid,
ReportStale,
ReportUnobservable,
NotActed,
Converged,
Refused,
Failed,
Reverted,
LastKnown,
Current,
Desired,
Partial,
Baseline,
Call,
AuthorAbsent,
AuthorPresenceIncomplete,
AuthorNotRead,
AuthorReadIncomplete,
AuthorSilent,
Behind,
Ahead,
OtherEpoch,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::TargetAbsent => "target_absent",
Self::PresenceIncomplete => "presence_incomplete",
Self::NoDescriptor => "no_descriptor",
Self::NotATarget => "not_a_target",
Self::Unbound => "unbound",
Self::NoReport => "no_report",
Self::NothingCrossed => "nothing_crossed",
Self::ReportInvalid => "report_invalid",
Self::ReportStale => "report_stale",
Self::ReportUnobservable => "report_unobservable",
Self::NotActed => "not_acted",
Self::Converged => "converged",
Self::Refused => "refused",
Self::Failed => "failed",
Self::Reverted => "reverted",
Self::LastKnown => "last_known",
Self::Current => "current",
Self::Desired => "desired",
Self::Partial => "partial",
Self::Baseline => "baseline",
Self::Call => "call",
Self::AuthorAbsent => "author_absent",
Self::AuthorPresenceIncomplete => "author_presence_incomplete",
Self::AuthorNotRead => "author_not_read",
Self::AuthorReadIncomplete => "author_read_incomplete",
Self::AuthorSilent => "author_silent",
Self::Behind => "behind",
Self::Ahead => "ahead",
Self::OtherEpoch => "other_epoch",
}
}
}
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 }
}
}
fn premises<'a, R: Reported>(
t: &TargetReading<'a, R>,
unbound: Judged,
) -> Result<(&'a R, Facts), Judged> {
use Answer::{NotAsked, Unobservable};
let listing = match t.presence {
Seen::Absent => return Err(Judged::new(NotAsked, Reason::TargetAbsent)),
Seen::Incomplete => return Err(Judged::new(Unobservable, Reason::PresenceIncomplete)),
Seen::AcrossFace => t.deployment,
Seen::Present => t.descriptor,
};
match listing {
None => return Err(Judged::new(Unobservable, Reason::NoDescriptor)),
Some(Listing::NotListed) => return Err(Judged::new(NotAsked, Reason::NotATarget)),
Some(Listing::Listed { bound: false }) => return Err(unbound),
Some(Listing::Listed { bound: true }) => {}
}
let report = match t.report {
ReportRead::NotRead => {
return Err(Judged::new(
Unobservable,
if t.presence == Seen::AcrossFace {
Reason::NothingCrossed
} else {
Reason::NoReport
},
));
}
ReportRead::Unreadable => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
ReportRead::Read(r) => match r.facts() {
Some(f) => (r, f),
None => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
},
};
match t.freshness {
freshness::Verdict::Stale => Err(Judged::new(Unobservable, Reason::ReportStale)),
freshness::Verdict::Unobservable => {
Err(Judged::new(Unobservable, Reason::ReportUnobservable))
}
freshness::Verdict::Fresh | freshness::Verdict::NotAsked => Ok(report),
}
}
const UNBOUND: Judged = Judged::new(Answer::NotAsked, Reason::Unbound);
fn converging<'a, R: Reported>(
t: &TargetReading<'a, R>,
author: Seen,
) -> Result<(&'a R, Facts), Judged> {
let r = premises(t, UNBOUND)?;
match author {
Seen::Absent => Err(Judged::new(Answer::NotAsked, Reason::AuthorAbsent)),
Seen::Incomplete => Err(Judged::new(
Answer::Unobservable,
Reason::AuthorPresenceIncomplete,
)),
Seen::Present | Seen::AcrossFace => Ok(r),
}
}
fn compared<M: machine::Mark>(observed: &M, current: &M, outcome: Outcome) -> Judged {
if observed == current {
return match outcome {
Outcome::Converged | Outcome::Reverted => {
Judged::new(Answer::Yes, outcome_reason(outcome))
}
Outcome::Refused | Outcome::Failed => Judged::new(Answer::No, outcome_reason(outcome)),
};
}
if observed.epoch() != current.epoch() {
return Judged::new(Answer::NotYet, Reason::OtherEpoch);
}
if observed.tick() < current.tick() {
Judged::new(Answer::NotYet, Reason::Behind)
} else {
Judged::new(Answer::Unobservable, Reason::Ahead)
}
}
fn outcome_reason(o: Outcome) -> Reason {
match o {
Outcome::Converged => Reason::Converged,
Outcome::Refused => Reason::Refused,
Outcome::Failed => Reason::Failed,
Outcome::Reverted => Reason::Reverted,
}
}
#[must_use]
pub fn refused<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
let r = match premises(t, UNBOUND) {
Ok((_, f)) => f,
Err(j) => return j,
};
match r.outcome {
None => Judged::new(Answer::NotAsked, Reason::NotActed),
Some(o @ (Outcome::Refused | Outcome::Failed)) => {
Judged::new(Answer::Yes, outcome_reason(o))
}
Some(o) => Judged::new(Answer::No, outcome_reason(o)),
}
}
#[must_use]
pub fn last_known<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
let r = match premises(t, UNBOUND) {
Ok((_, f)) => f,
Err(j) => return j,
};
match (r.outcome, r.last_known) {
(None, _) => Judged::new(Answer::NotAsked, Reason::NotActed),
(Some(_), true) => Judged::new(Answer::Yes, Reason::LastKnown),
(Some(_), false) => Judged::new(Answer::No, Reason::Current),
}
}
#[must_use]
pub fn in_force<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
let r = match premises(t, Judged::new(Answer::No, Reason::Unbound)) {
Ok((_, f)) => f,
Err(j) => return j,
};
match r.source {
Source::Desired if r.in_force => Judged::new(Answer::Yes, Reason::Desired),
Source::Desired => Judged::new(Answer::Yes, Reason::Partial),
Source::Baseline => Judged::new(Answer::No, Reason::Baseline),
Source::Call => Judged::new(Answer::No, Reason::Call),
}
}
#[must_use]
pub fn converged(t: &TargetReading<'_>, a: &AuthorReading) -> Judged {
use Answer::{NotYet, Unobservable};
let r = match converging(t, a.presence) {
Ok((r, _)) => r,
Err(j) => return j,
};
let current = match a.current {
Current::NotRead => return Judged::new(Unobservable, Reason::AuthorNotRead),
Current::Incomplete => return Judged::new(Unobservable, Reason::AuthorReadIncomplete),
Current::Silent => return Judged::new(Unobservable, Reason::AuthorSilent),
Current::Put(s) | Current::Delete(s) => s,
};
let (Some(observed), Some(outcome)) = (&r.observed, r.outcome) else {
return Judged::new(NotYet, Reason::NotActed);
};
compared(&observed.stamp, ¤t, outcome)
}
#[cfg(test)]
mod tests {
use super::*;
fn st(time: u64, id: &str) -> Stamp {
Stamp::parse(time, id).expect("a stamp")
}
fn put(time: u64, id: &str) -> Sample {
Sample {
via: Via::Owner,
mutation: Mutation::Put,
stamp: Some(st(time, id)),
revision: Some(time),
content: Some(Content::of_json(&serde_json::json!({"revision": time}))),
}
}
#[test]
fn stamps_read_as_zenoh_writes_them() {
assert_eq!(
parse_stamp("7386690599959157260/33"),
Some(st(7_386_690_599_959_157_260, "33"))
);
assert_eq!(st(7, "1bc0").to_string(), "7/1bc0");
assert_eq!(parse_stamp("0/1"), Some(st(0, "1")));
assert_eq!(
parse_stamp(&format!("{}/1", u64::MAX)),
Some(st(u64::MAX, "1"))
);
for bad in [
"",
"1",
"/1",
"1/",
"01/1",
"1/01",
"1/A",
"+1/1",
"1/0",
"18446744073709551616/1",
"1/1/1",
" 1/1",
] {
assert_eq!(parse_stamp(bad), None, "{bad:?}");
}
}
#[test]
fn a_report_serializes_as_the_schema_names_it() {
let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
assert_eq!(
t.report().to_json(),
serde_json::json!({"key": "zk2/a/b/i.v1/state/x", "source": "baseline"})
);
assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
t.finish(Ended::Done);
let v = t.report().to_json();
assert_eq!(
v,
serde_json::json!({
"key": "zk2/a/b/i.v1/state/x",
"source": "desired",
"in_force": {"stamp": "100/a1", "revision": 100},
"observed": {"stamp": "100/a1", "revision": 100},
"outcome": "converged",
})
);
let back: Report = serde_json::from_value(v.clone()).expect("serde reads it back");
assert_eq!(&back, t.report());
assert_eq!(Report::from_json(&v).as_ref(), Ok(t.report()));
assert!(t.report().check().is_empty());
}
#[test]
fn every_report_the_machine_makes_is_consistent() {
let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
let mut seen = Vec::new();
let steps = vec![
put(100, "a1"),
put(200, "a1"),
Sample {
mutation: Mutation::Delete,
revision: None,
..put(300, "a1")
},
Sample {
via: Via::Archive,
..put(400, "b2")
},
];
for (i, s) in steps.into_iter().enumerate() {
assert!(
matches!(t.observe(s), Step::Act(_)),
"a new document is acted on"
);
let again = Sample {
stamp: s.stamp.map(|x| Stamp {
time: x.time + 1,
..x
}),
..s
};
assert_eq!(t.observe(again), Step::Held);
let ended = match i % 3 {
0 => Ended::Done,
1 => Ended::Refused(Refusal::new(REACH)),
_ => Ended::Failed(Refusal::new(APPLY)),
};
assert_eq!(
t.finish(ended),
Step::Adopted,
"the held re-put is the same document"
);
seen.push(t.report().clone());
t.call();
seen.push(t.report().clone());
}
for r in &seen {
assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
}
}
#[test]
fn numbers_compare_by_their_exact_value() {
for (text, exact) in [
("0", "0"),
("-0", "0"),
("0.000", "0"),
("0e99", "0"),
("10", "1e1"),
("10.0", "1e1"),
("1e1", "1e1"),
("100E-1", "1e1"),
("1.5", "15e-1"),
("-0.25", "-25e-2"),
("9007199254740992", "9007199254740992e0"),
("9007199254740993", "9007199254740993e0"),
("18446744073709551617", "18446744073709551617e0"),
("1e+2", "1e2"),
] {
assert_eq!(exact_number(text).as_deref(), Some(exact), "{text}");
}
for bad in ["", "-", "01", "1.", ".5", "+1", "1e", "1e+", "--1", "0x1"] {
assert_eq!(exact_number(bad), None, "{bad:?}");
}
}
#[test]
fn a_payload_and_its_decoded_value_compare_alike() {
let same = |a: &str, b: &str| {
Content::of_payload(a.as_bytes(), true) == Content::of_payload(b.as_bytes(), true)
};
assert!(same(
r#"{"a":10,"b":[1,2]}"#,
r#" { "b" : [1, 2.0], "a" : 1e1 } "#
));
assert!(same(r#"{"s":"\u0041"}"#, r#"{"s":"A"}"#));
assert!(!same(
r#"{"revision":9007199254740992}"#,
r#"{"revision":9007199254740993}"#
));
assert!(!same(
r#"{"revision":18446744073709551616}"#,
r#"{"revision":18446744073709551617}"#
));
assert!(!same(r#"{"x":0.1}"#, r#"{"x":0.10000000000000000555}"#));
assert!(same(r#"{"a":1e400}"#, r#"{"a":1e400}"#));
assert!(!same(r#"{"a":1e400}"#, r#"{"a": 1e400}"#));
assert!(!same(r#"{"a":1,"a":1}"#, r#"{"a":1}"#));
for text in [
r#"{"mode":"run","rate_hz":10.0,"revision":1}"#,
r#"{"revision":9007199254740993,"x":[-0.5,true,null,"é"]}"#,
] {
let v = crate::strict::parse_json(text).expect("strict JSON");
assert_eq!(
Content::of_payload(text.as_bytes(), true),
Content::of_json(&v),
"{text}"
);
}
assert_ne!(
Content::of_payload(b"{}", false),
Content::of_payload(b"{ }", false),
"a payload that is not JSON compares byte for byte"
);
}
#[test]
fn a_decoded_value_and_its_text_agree_where_the_text_says() {
let of_json = |v: Value| Content::of_json(&serde_json::json!({ "x": v }));
let of_text = |t: &str| Content::of_payload(format!(r#"{{"x":{t}}}"#).as_bytes(), true);
assert_eq!(
of_json(serde_json::json!(1e20)),
of_text("100000000000000000000")
);
assert_eq!(of_json(serde_json::json!(1e20)), of_text("1e20"));
assert_eq!(of_json(serde_json::json!(1e300)), of_text("1e300"));
assert_eq!(
of_json(serde_json::json!(1e300)),
of_text(&format!("1{}", "0".repeat(300)))
);
assert_eq!(of_json(serde_json::json!(-0.0)), of_text("0"));
assert_eq!(of_json(serde_json::json!(0)), of_text("-0.0"));
assert_eq!(of_json(serde_json::json!(0.1)), of_text("0.1"));
assert_eq!(
of_json(serde_json::json!(9_007_199_254_740_993_u64)),
of_text("9007199254740993")
);
assert_ne!(
of_json(serde_json::json!(0.1)),
of_text("0.10000000000000000555")
);
assert_ne!(
of_json(serde_json::json!(9_007_199_254_740_992_u64)),
of_text("9007199254740993")
);
assert_ne!(
of_json(serde_json::json!(1e20)),
of_text("100000000000000000001")
);
}
#[test]
fn a_held_version_is_remembered_only_once_it_starts() {
let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
assert_eq!(t.observe(put(50, "b2")), Step::Held);
assert_eq!(t.remembered(0xb2), None, "held waiting, not acted on");
assert_eq!(t.remembered(0xa1), Some(100), "the running act counts");
assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
assert_eq!(t.remembered(0xb2), Some(50));
t.finish(Ended::Done);
let again = Sample {
content: put(50, "b2").content,
revision: Some(50),
..put(70, "b2")
};
assert_eq!(t.observe(again), Step::Adopted);
assert_eq!(t.remembered(0xb2), Some(70));
assert_eq!(t.observe(put(60, "b2")), Step::Older);
}
#[test]
fn finite_is_by_rounding() {
let with = |n: &str| format!(r#"{{"source":"baseline","x":{n}}}"#);
assert!(decode(with("1.7976931348623158e308").as_bytes()).is_ok());
for n in ["1.7976931348623159e308", "1e400", "-1e400"] {
assert!(
matches!(decode(with(n).as_bytes()), Err(Unreadable::Json(_))),
"{n}"
);
}
let nested = |n: usize| {
format!(
r#"{{"source":"baseline","x":{}{}}}"#,
"[".repeat(n),
"]".repeat(n)
)
};
assert!(decode(nested(MAX_DEPTH - 1).as_bytes()).is_ok());
assert!(matches!(
decode(nested(MAX_DEPTH).as_bytes()),
Err(Unreadable::Json(_))
));
assert!(matches!(
decode(nested(100_000).as_bytes()),
Err(Unreadable::Json(_))
));
let deep = |n: usize, ws: &str| format!("{}{ws}{}", "[".repeat(n), "]".repeat(n));
assert_eq!(
Content::of_payload(deep(MAX_DEPTH, " ").as_bytes(), true),
Content::of_payload(deep(MAX_DEPTH, "").as_bytes(), true)
);
assert_ne!(
Content::of_payload(deep(MAX_DEPTH + 1, " ").as_bytes(), true),
Content::of_payload(deep(MAX_DEPTH + 1, "").as_bytes(), true)
);
let big = format!("1{}", "0".repeat(400));
assert!(matches!(
decode(with(&big).as_bytes()),
Err(Unreadable::Json(_))
));
}
#[test]
fn a_revision_reads_by_its_exact_value() {
let rep = |r: &str| {
format!(
r#"{{"key":"zk2/a/b/i.v1/state/x","source":"desired","in_force":{{"stamp":"1/a","revision":{r}}},"observed":{{"stamp":"1/a","revision":{r}}},"outcome":"converged"}}"#
)
};
let observed = |r: &str| decode(rep(r).as_bytes()).map(|x| x.observed.unwrap().revision);
assert_eq!(observed("18446744073709551615.0"), Ok(Some(u64::MAX)));
assert_eq!(observed("30e-1"), Ok(Some(3)));
assert_eq!(observed("-0.0"), Ok(Some(0)));
assert_eq!(observed("1e19"), Ok(Some(10_000_000_000_000_000_000)));
assert!(matches!(
observed("18446744073709551616.0"),
Err(Unreadable::RevisionRange(_))
));
assert!(matches!(observed("1e400"), Err(Unreadable::Json(_))));
assert!(
matches!(observed("1e99999999999999999999"), Err(Unreadable::Json(_))),
"never finite: not strict JSON, before the schema"
);
assert!(matches!(
exact_revision("1e99999999999999999999"),
Some(RevisionRead::TooLarge)
));
assert!(exact_revision("1e-99999999999999999999").is_none());
assert!(matches!(observed("1.5"), Err(Unreadable::Schema(_))));
assert!(matches!(observed("-1"), Err(Unreadable::Schema(_))));
let v: Value = serde_json::from_str(&rep("18446744073709551615.0")).unwrap();
assert!(matches!(
Report::from_json(&v),
Err(Unreadable::RevisionRange(_))
));
assert_eq!(
revision_of_text(br#"{"revision": 3.0, "mode": "run"}"#),
Some(3)
);
assert_eq!(
revision_of_text(br#"{"revision": 18446744073709551615.0}"#),
Some(u64::MAX)
);
for none in [
&br#"{"revision": 1.5}"#[..],
br#"{"revision": "1"}"#,
br#"{"revision": 18446744073709551616}"#,
br#"[1]"#,
br#"{"rev": 1}"#,
b"not json",
] {
assert_eq!(
revision_of_text(none),
None,
"{}",
String::from_utf8_lossy(none)
);
}
assert_eq!(
revision_of_value(&serde_json::json!({"revision": "18446744073709551615"})),
Some(u64::MAX),
"protobuf's JSON mapping writes a 64-bit field as a string"
);
assert_eq!(
revision_of_value(&serde_json::json!({"revision": 7})),
Some(7)
);
assert_eq!(
revision_of_value(&serde_json::json!({"revision": "x"})),
None
);
}
#[test]
fn an_id_forgotten_beyond_sixteen_is_read_as_new() {
let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
let ids: Vec<String> = (1..=17).map(|i| format!("{i:x}")).collect();
for (n, id) in ids.iter().enumerate() {
let s = Sample {
revision: Some(n as u64),
content: Some(Content::of_json(&serde_json::json!({"revision": n}))),
..put(500, id)
};
assert!(matches!(t.observe(s), Step::Act(_)), "{id}");
t.finish(Ended::Done);
}
assert_eq!(t.remembered(2), Some(500));
assert_eq!(t.observe(put(400, "2")), Step::Older);
assert_eq!(t.observe(put(500, "2")), Step::SameVersion);
assert_eq!(t.remembered(1), None);
assert!(matches!(t.observe(put(400, "1")), Step::Act(_)));
}
}