1use std::collections::BTreeMap;
43use std::fmt;
44
45use serde::{Deserialize, Serialize};
46use serde_json::Value;
47
48use crate::authoring::{Kind, ParamType};
49use crate::contract::Resource;
50use crate::freshness;
51use crate::grammar::{self, Addr, IfaceId, Key, KindToken, ZkKey};
52use crate::seed::Stamp;
53use crate::template::{Bindings, Template};
54
55pub mod v2;
56
57pub const PROFILE: &str = "desired.v1";
59
60pub const NAME: &str = "desired";
62
63pub const TARGET_PARAM: &str = "desired.target_param";
65
66pub const VOCABULARY: &[&str] = &["target_param"];
70
71pub const SCHEMA_STEM: &str = "desired.v1";
73pub const REPORT: &str = "desired.v1.Report";
75pub const VERSION: &str = "desired.v1.Version";
77pub const REFUSAL: &str = "desired.v1.Refusal";
79
80pub const PUBLISHED: &[&str] = &[
84 "sha256:8c5ffce35fadeb6196233a46e163ee3b15cbd2bd8339a05de2cf8fe22b52e9ef",
85 "sha256:43c952598f454ec903dba63bad36419f5dcff3312db727bd4e58a88dc1ca55ae",
86];
87
88#[must_use]
90pub fn is_published(id: &str) -> bool {
91 PUBLISHED.contains(&id)
92}
93
94pub const SELF_SYSTEM: &str = "self.system";
96pub const SELF_SERVICE: &str = "self.service";
98
99pub const MAX_CODE: usize = 64;
101
102pub const UNDECODABLE: &str = "undecodable";
105pub const REACH: &str = "reach";
107pub const SENSITIVE: &str = "sensitive";
110pub const INVALID: &str = "invalid";
112pub const APPLY: &str = "apply";
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub enum Binds {
120 Either,
123 System,
125 Service,
127}
128
129impl Binds {
130 #[must_use]
132 pub fn as_str(self) -> &'static str {
133 match self {
134 Self::Either => "either",
135 Self::System => SELF_SYSTEM,
136 Self::Service => SELF_SERVICE,
137 }
138 }
139
140 #[must_use]
142 pub fn admits(self, bound: &str) -> bool {
143 match self {
144 Self::Either => bound == SELF_SYSTEM || bound == SELF_SERVICE,
145 Self::System => bound == SELF_SYSTEM,
146 Self::Service => bound == SELF_SERVICE,
147 }
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct TargetParam {
154 pub param: String,
155 pub binds: Binds,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub enum Invalid {
161 NotState,
163 Value,
165 Repeated,
167 NotAParam,
169 RestParam,
171 ParamNotTarget,
173 NotString,
176 HorizonV1,
180}
181
182impl Invalid {
183 #[must_use]
185 pub fn as_str(self) -> &'static str {
186 match self {
187 Self::NotState => "not_state",
188 Self::Value => "value",
189 Self::Repeated => "repeated",
190 Self::NotAParam => "not_a_param",
191 Self::RestParam => "rest_param",
192 Self::ParamNotTarget => "param_not_target",
193 Self::NotString => "not_string",
194 Self::HorizonV1 => "horizon_v1",
195 }
196 }
197
198 #[must_use]
200 pub fn says(self) -> &'static str {
201 match self {
202 Self::NotState => "a desired document is state of its author",
203 Self::Value => "desired.target_param is a string, or an array of one or two strings",
204 Self::Repeated => "a target parameter is named twice",
205 Self::NotAParam => "a name is no parameter of the template",
206 Self::RestParam => "a rest parameter cannot be a target parameter",
207 Self::ParamNotTarget => {
208 "every template parameter must be a target parameter: one document per target"
209 }
210 Self::NotString => "a target parameter holds a system or a service name, a string",
211 Self::HorizonV1 => {
212 "a horizon above 0 is confirmed by a heartbeat: the contract must use freshness.v2"
213 }
214 }
215 }
216}
217
218impl fmt::Display for Invalid {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 f.write_str(self.says())
221 }
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
226pub enum Declaration {
227 NotThisProfiles,
229 Invalid(Vec<Invalid>),
231 Declared(Vec<TargetParam>),
233}
234
235impl Declaration {
236 #[must_use]
238 pub fn as_str(&self) -> &'static str {
239 match self {
240 Self::NotThisProfiles => "not_this_profiles",
241 Self::Invalid(_) => "invalid",
242 Self::Declared(_) => "declared",
243 }
244 }
245
246 #[must_use]
248 pub fn targets(&self) -> Option<&[TargetParam]> {
249 match self {
250 Self::Declared(t) => Some(t),
251 _ => None,
252 }
253 }
254}
255
256#[must_use]
265pub fn declaration(
266 kind: Kind,
267 template: &Template,
268 params: &BTreeMap<String, ParamType>,
269 annotations: &BTreeMap<String, Value>,
270) -> Declaration {
271 let Some(v) = annotations.get(TARGET_PARAM) else {
272 return Declaration::NotThisProfiles;
273 };
274 let typed = params;
275 let params: Vec<(&str, bool)> = template.params().collect();
276 let mut why = Vec::new();
277 if kind != Kind::State {
278 why.push(Invalid::NotState);
279 }
280 let names: Option<Vec<&str>> = match v {
281 Value::String(s) => Some(vec![s.as_str()]),
282 Value::Array(a) if (1..=2).contains(&a.len()) => {
283 a.iter().map(Value::as_str).collect::<Option<Vec<_>>>()
284 }
285 _ => None,
286 };
287 match &names {
288 None => why.push(Invalid::Value),
289 Some(names) => {
290 if names.len() == 2 && names[0] == names[1] {
291 why.push(Invalid::Repeated);
292 }
293 if names.iter().any(|n| !params.iter().any(|(p, _)| p == n)) {
294 why.push(Invalid::NotAParam);
295 }
296 if names
297 .iter()
298 .any(|n| params.iter().any(|(p, rest)| *rest && p == n))
299 {
300 why.push(Invalid::RestParam);
301 }
302 if params.iter().any(|(p, _)| !names.contains(p)) {
303 why.push(Invalid::ParamNotTarget);
304 }
305 if names.iter().any(|n| {
308 params.iter().any(|(p, rest)| !*rest && p == n)
309 && typed.get(*n).is_some_and(|t| *t != ParamType::String)
310 }) {
311 why.push(Invalid::NotString);
312 }
313 }
314 }
315 match names {
316 Some(names) if why.is_empty() => Declaration::Declared(match names.as_slice() {
317 [one] => vec![TargetParam {
318 param: (*one).to_owned(),
319 binds: Binds::Either,
320 }],
321 [first, second] => vec![
322 TargetParam {
323 param: (*first).to_owned(),
324 binds: Binds::System,
325 },
326 TargetParam {
327 param: (*second).to_owned(),
328 binds: Binds::Service,
329 },
330 ],
331 _ => return Declaration::Invalid(vec![Invalid::Value]),
333 }),
334 _ => Declaration::Invalid(why),
335 }
336}
337
338#[must_use]
340pub fn declaration_of(r: &Resource) -> Declaration {
341 declaration(r.kind, &r.template, &r.params, &r.annotations)
342}
343
344#[derive(Debug, Clone, Copy)]
349pub struct Requirement<'a> {
350 pub bindings: &'a [String],
352 pub params: &'a BTreeMap<String, String>,
354 pub optional: bool,
356 pub documents: usize,
361}
362
363#[derive(Debug, Clone, Copy)]
366pub struct Slice<'a> {
367 pub iface: &'a IfaceId,
368 pub token: KindToken,
369 pub template: &'a Template,
370 pub targets: &'a [TargetParam],
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
375pub enum BindingProblem {
376 RequiredUnbound,
378 TwoDocuments,
382 NotOneAuthor,
384 TargetUnbound,
386 NotSelf,
389 WrongSelf,
391}
392
393impl BindingProblem {
394 #[must_use]
396 pub fn as_str(self) -> &'static str {
397 match self {
398 Self::RequiredUnbound => "required_unbound",
399 Self::TwoDocuments => "two_documents",
400 Self::NotOneAuthor => "not_one_author",
401 Self::TargetUnbound => "target_unbound",
402 Self::NotSelf => "not_self",
403 Self::WrongSelf => "wrong_self",
404 }
405 }
406}
407
408#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum Binding {
411 Unbound,
413 Invalid(Vec<BindingProblem>),
415 Bound { key: Key },
417}
418
419impl Binding {
420 #[must_use]
422 pub fn as_str(&self) -> &'static str {
423 match self {
424 Self::Unbound => "unbound",
425 Self::Invalid(_) => "invalid",
426 Self::Bound { .. } => "bound",
427 }
428 }
429}
430
431fn one_author(bindings: &[String]) -> Option<Addr> {
433 let [one] = bindings else {
434 return None;
435 };
436 if one.split('/').any(|c| c == "*") {
437 return None;
438 }
439 one.parse().ok()
440}
441
442#[must_use]
450pub fn binding(slice: &Slice<'_>, req: &Requirement<'_>, own: &Addr) -> Binding {
451 if req.bindings.is_empty() {
452 return if req.optional {
453 Binding::Unbound
454 } else {
455 Binding::Invalid(vec![BindingProblem::RequiredUnbound])
456 };
457 }
458 if req.documents > 1 {
462 return Binding::Invalid(vec![BindingProblem::TwoDocuments]);
463 }
464 let mut why = Vec::new();
465 let author = one_author(req.bindings);
466 if author.is_none() {
467 why.push(BindingProblem::NotOneAuthor);
468 }
469 let bound = |t: &TargetParam| req.params.get(&t.param).map(String::as_str);
470 if slice.targets.iter().any(|t| bound(t).is_none()) {
471 why.push(BindingProblem::TargetUnbound);
472 }
473 if slice
474 .targets
475 .iter()
476 .filter_map(bound)
477 .any(|b| b != SELF_SYSTEM && b != SELF_SERVICE)
478 {
479 why.push(BindingProblem::NotSelf);
480 }
481 if slice.targets.iter().any(|t| {
482 bound(t).is_some_and(|b| (b == SELF_SYSTEM || b == SELF_SERVICE) && !t.binds.admits(b))
483 }) {
484 why.push(BindingProblem::WrongSelf);
485 }
486 let Some(author) = author.filter(|_| why.is_empty()) else {
487 return Binding::Invalid(why);
488 };
489 let mut values = Bindings::new();
490 for t in slice.targets {
491 let v = if bound(t) == Some(SELF_SYSTEM) {
492 own.system.as_str()
493 } else {
494 own.service.as_str()
495 };
496 values.insert(t.param.clone(), vec![v.to_owned()]);
497 }
498 let built = slice.template.build(&values).ok().and_then(|chunks| {
499 let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
500 grammar::data_key(&author, slice.iface, slice.token, &refs).ok()
501 });
502 match built {
503 Some(key) => Binding::Bound { key },
504 None => Binding::Invalid(vec![BindingProblem::TargetUnbound]),
507 }
508}
509
510#[must_use]
517pub fn parse_stamp(s: &str) -> Option<Stamp> {
518 let (time, id) = s.split_once('/')?;
519 let digits = !time.is_empty() && time.bytes().all(|b| b.is_ascii_digit());
520 if !digits || (time.len() > 1 && time.starts_with('0')) {
521 return None;
522 }
523 Stamp::parse(time.parse().ok()?, id)
524}
525
526mod stamp_text {
528 use serde::{Deserialize, Deserializer, Serializer};
529
530 use super::{Stamp, parse_stamp};
531
532 pub fn serialize<S: Serializer>(s: &Stamp, ser: S) -> Result<S::Ok, S::Error> {
533 ser.collect_str(s)
534 }
535
536 pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Stamp, D::Error> {
537 let s = String::deserialize(de)?;
538 parse_stamp(&s).ok_or_else(|| serde::de::Error::custom(format!("{s:?} is no stamp")))
539 }
540}
541
542#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
546#[serde(rename_all = "snake_case")]
547pub enum Source {
548 Baseline,
550 Desired,
552 Call,
554}
555
556impl Source {
557 #[must_use]
559 pub fn as_str(self) -> &'static str {
560 match self {
561 Self::Baseline => "baseline",
562 Self::Desired => "desired",
563 Self::Call => "call",
564 }
565 }
566
567 fn parse(s: &str) -> Option<Self> {
568 [Self::Baseline, Self::Desired, Self::Call]
569 .into_iter()
570 .find(|v| v.as_str() == s)
571 }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
576#[serde(rename_all = "snake_case")]
577pub enum Outcome {
578 Converged,
580 Refused,
582 Failed,
584 Reverted,
586}
587
588impl Outcome {
589 #[must_use]
591 pub fn as_str(self) -> &'static str {
592 match self {
593 Self::Converged => "converged",
594 Self::Refused => "refused",
595 Self::Failed => "failed",
596 Self::Reverted => "reverted",
597 }
598 }
599
600 fn parse(s: &str) -> Option<Self> {
601 [Self::Converged, Self::Refused, Self::Failed, Self::Reverted]
602 .into_iter()
603 .find(|v| v.as_str() == s)
604 }
605}
606
607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
609pub struct Version {
610 #[serde(with = "stamp_text")]
611 pub stamp: Stamp,
612 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub revision: Option<u64>,
614}
615
616#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
619pub struct Refusal {
620 pub code: String,
623 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub pointer: Option<String>,
626 #[serde(default, skip_serializing_if = "Option::is_none")]
628 pub detail: Option<String>,
629}
630
631impl Refusal {
632 #[must_use]
634 pub fn new(code: impl Into<String>) -> Self {
635 Self {
636 code: code.into(),
637 pointer: None,
638 detail: None,
639 }
640 }
641}
642
643#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646pub struct Report {
647 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub key: Option<String>,
650 pub source: Source,
651 #[serde(default, skip_serializing_if = "Option::is_none")]
652 pub in_force: Option<Version>,
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub observed: Option<Version>,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub outcome: Option<Outcome>,
657 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub refusal: Option<Refusal>,
659 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
661 pub last_known: bool,
662}
663
664#[derive(Debug, Clone, PartialEq, Eq)]
666pub enum Unreadable {
667 Json(String),
669 Schema(String),
671 Stamp(String),
673 RevisionRange(&'static str),
675}
676
677impl Unreadable {
678 #[must_use]
680 pub fn as_str(&self) -> &'static str {
681 match self {
682 Self::Json(_) => "json",
683 Self::Schema(_) => "schema",
684 Self::Stamp(_) => "stamp",
685 Self::RevisionRange(_) => "revision_range",
686 }
687 }
688}
689
690impl fmt::Display for Unreadable {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 match self {
693 Self::Json(e) => write!(f, "not strict JSON: {e}"),
694 Self::Schema(e) => write!(f, "not a desired.v1.Report: {e}"),
695 Self::Stamp(s) => write!(f, "{s:?} is not a stamp as zenoh writes one"),
696 Self::RevisionRange(m) => write!(f, "/{m}/revision is above 2^64-1"),
697 }
698 }
699}
700
701#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
705pub enum Finding {
706 Escape,
708 RunFields,
710 Keyless,
712 KeyForm,
714 ObservedOutcome,
715 Refusal,
716 Source,
717 InForce,
718 RevisionOnRevert,
719 LastKnown,
720}
721
722impl Finding {
723 #[must_use]
725 pub fn as_str(self) -> &'static str {
726 match self {
727 Self::Escape => "escape",
728 Self::RunFields => "run_fields",
729 Self::Keyless => "keyless",
730 Self::KeyForm => "key_form",
731 Self::ObservedOutcome => "observed_outcome",
732 Self::Refusal => "refusal",
733 Self::Source => "source",
734 Self::InForce => "in_force",
735 Self::RevisionOnRevert => "revision_on_revert",
736 Self::LastKnown => "last_known",
737 }
738 }
739}
740
741enum RevisionRead {
744 InRange(u64),
745 TooLarge,
746}
747
748fn exact_revision(canonical: &str) -> Option<RevisionRead> {
753 if canonical == "0" {
754 return Some(RevisionRead::InRange(0));
755 }
756 if canonical.starts_with('-') {
757 return None;
758 }
759 let (digits, exp) = canonical.split_once('e')?;
760 let exp: i128 = exp.parse().ok()?;
761 if exp < 0 {
764 return None;
765 }
766 let Ok(zeros) = usize::try_from(exp) else {
770 return Some(RevisionRead::TooLarge);
771 };
772 if digits.len().saturating_add(zeros) > 20 {
774 return Some(RevisionRead::TooLarge);
775 }
776 let text = format!("{digits}{}", "0".repeat(zeros));
777 Some(
778 text.parse::<u64>()
779 .map_or(RevisionRead::TooLarge, RevisionRead::InRange),
780 )
781}
782
783#[must_use]
789pub fn revision_of_text(bytes: &[u8]) -> Option<u64> {
790 let text = std::str::from_utf8(bytes).ok()?;
791 match Exact::of_strict_text(text)? {
792 Exact::Object(m) => match m.get("revision")? {
793 Exact::Number(n) => match exact_revision(n)? {
794 RevisionRead::InRange(r) => Some(r),
795 RevisionRead::TooLarge => None,
796 },
797 _ => None,
798 },
799 _ => None,
800 }
801}
802
803#[must_use]
809pub fn revision_of_value(v: &Value) -> Option<u64> {
810 match v.get("revision")? {
811 Value::String(s) if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) => {
812 s.parse().ok()
813 }
814 r => match revision(r)? {
815 RevisionRead::InRange(n) => Some(n),
816 RevisionRead::TooLarge => None,
817 },
818 }
819}
820
821fn revision(v: &Value) -> Option<RevisionRead> {
822 let Value::Number(n) = v else {
823 return None;
824 };
825 if let Some(u) = n.as_u64() {
826 return Some(RevisionRead::InRange(u));
827 }
828 if n.as_i64().is_some() {
829 return None; }
831 let f = n.as_f64()?;
832 if !(f.is_finite() && f >= 0.0 && f.fract() == 0.0) {
833 return None;
834 }
835 if f >= 2.0_f64.powi(64) {
837 return Some(RevisionRead::TooLarge);
838 }
839 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
840 let n = f as u64;
841 Some(RevisionRead::InRange(n))
842}
843
844struct RawVersion<'a> {
846 stamp: &'a str,
847 revision: Option<RevisionRead>,
848}
849
850fn raw_version<'a>(
854 v: &'a Value,
855 member: &str,
856 exact: Option<&Exact>,
857) -> Result<RawVersion<'a>, Unreadable> {
858 let schema = |why: &str| Unreadable::Schema(format!("/{member}{why}"));
859 let Value::Object(o) = v else {
860 return Err(schema(": not an object"));
861 };
862 let stamp = match o.get("stamp") {
863 Some(Value::String(s)) if s.chars().count() >= 3 => s.as_str(),
864 Some(Value::String(_)) => return Err(schema("/stamp: shorter than 3 characters")),
865 Some(_) => return Err(schema("/stamp: not a string")),
866 None => return Err(schema("/stamp: missing")),
867 };
868 let exact = match exact {
869 Some(Exact::Object(m)) => match m.get("revision") {
870 Some(Exact::Number(n)) => Some(n.as_str()),
871 _ => None,
872 },
873 _ => None,
874 };
875 let revision = match (o.get("revision"), exact) {
876 (None, _) => None,
877 (Some(Value::Number(_)), Some(text)) => {
878 Some(exact_revision(text).ok_or_else(|| schema("/revision: not an integer from 0"))?)
879 }
880 (Some(r), _) => {
881 Some(revision(r).ok_or_else(|| schema("/revision: not an integer from 0"))?)
882 }
883 };
884 Ok(RawVersion { stamp, revision })
885}
886
887fn optional_string(
888 o: &serde_json::Map<String, Value>,
889 m: &str,
890 at: &str,
891) -> Result<Option<String>, Unreadable> {
892 match o.get(m) {
893 None => Ok(None),
894 Some(Value::String(s)) => Ok(Some(s.clone())),
895 Some(_) => Err(Unreadable::Schema(format!("{at}/{m}: not a string"))),
896 }
897}
898
899impl Report {
900 #[must_use]
903 pub fn baseline(key: Option<String>) -> Self {
904 Self {
905 key,
906 source: Source::Baseline,
907 in_force: None,
908 observed: None,
909 outcome: None,
910 refusal: None,
911 last_known: false,
912 }
913 }
914
915 pub fn from_json(v: &Value) -> Result<Self, Unreadable> {
927 Self::read(v, None)
928 }
929
930 fn read(v: &Value, exact: Option<&Exact>) -> Result<Self, Unreadable> {
934 let schema = |why: String| Unreadable::Schema(why);
935 let Value::Object(o) = v else {
936 return Err(schema("not an object".into()));
937 };
938 let exact_of = |m: &str| match exact {
939 Some(Exact::Object(e)) => e.get(m),
940 _ => None,
941 };
942 let source = match o.get("source") {
943 Some(Value::String(s)) => Source::parse(s),
944 _ => None,
945 }
946 .ok_or_else(|| schema("/source: not baseline, desired or call".into()))?;
947 let key = optional_string(o, "key", "")?;
948 let in_force = o
949 .get("in_force")
950 .map(|v| raw_version(v, "in_force", exact_of("in_force")))
951 .transpose()?;
952 let observed = o
953 .get("observed")
954 .map(|v| raw_version(v, "observed", exact_of("observed")))
955 .transpose()?;
956 let outcome = match o.get("outcome") {
957 None => None,
958 Some(Value::String(s)) => Some(Outcome::parse(s).ok_or_else(|| {
959 schema("/outcome: not converged, refused, failed or reverted".into())
960 })?),
961 Some(_) => return Err(schema("/outcome: not a string".into())),
962 };
963 let refusal = match o.get("refusal") {
964 None => None,
965 Some(Value::Object(r)) => {
966 let code = match r.get("code") {
967 Some(Value::String(c)) if (1..=MAX_CODE).contains(&c.chars().count()) => {
968 c.clone()
969 }
970 Some(Value::String(_)) => {
971 return Err(schema("/refusal/code: not 1 to 64 characters".into()));
972 }
973 Some(_) => return Err(schema("/refusal/code: not a string".into())),
974 None => return Err(schema("/refusal/code: missing".into())),
975 };
976 Some(Refusal {
977 code,
978 pointer: optional_string(r, "pointer", "/refusal")?,
979 detail: optional_string(r, "detail", "/refusal")?,
980 })
981 }
982 Some(_) => return Err(schema("/refusal: not an object".into())),
983 };
984 let last_known = match o.get("last_known") {
985 None => false,
986 Some(Value::Bool(b)) => *b,
987 Some(_) => return Err(schema("/last_known: not a boolean".into())),
988 };
989 let stamp = |r: &RawVersion<'_>| {
990 parse_stamp(r.stamp).ok_or_else(|| Unreadable::Stamp(r.stamp.to_owned()))
991 };
992 let in_force_stamp = in_force.as_ref().map(stamp).transpose()?;
993 let observed_stamp = observed.as_ref().map(stamp).transpose()?;
994 let rev = |r: &RawVersion<'_>, m: &'static str| match &r.revision {
995 None => Ok(None),
996 Some(RevisionRead::InRange(n)) => Ok(Some(*n)),
997 Some(RevisionRead::TooLarge) => Err(Unreadable::RevisionRange(m)),
998 };
999 let in_force = match (&in_force, in_force_stamp) {
1000 (Some(r), Some(stamp)) => Some(Version {
1001 stamp,
1002 revision: rev(r, "in_force")?,
1003 }),
1004 _ => None,
1005 };
1006 let observed = match (&observed, observed_stamp) {
1007 (Some(r), Some(stamp)) => Some(Version {
1008 stamp,
1009 revision: rev(r, "observed")?,
1010 }),
1011 _ => None,
1012 };
1013 Ok(Self {
1014 key,
1015 source,
1016 in_force,
1017 observed,
1018 outcome,
1019 refusal,
1020 last_known,
1021 })
1022 }
1023
1024 #[must_use]
1028 pub fn check(&self) -> Vec<Finding> {
1029 let mut out = Vec::new();
1030 if self.key.is_none() && (self.source != Source::Baseline || self.observed.is_some()) {
1031 out.push(Finding::Keyless);
1032 }
1033 if let Some(k) = &self.key
1034 && !matches!(
1035 grammar::parse(k),
1036 Ok(ZkKey::Data {
1037 kind: KindToken::State | KindToken::ExplicitState,
1038 ..
1039 })
1040 )
1041 {
1042 out.push(Finding::KeyForm);
1043 }
1044 if self.observed.is_some() != self.outcome.is_some() {
1045 out.push(Finding::ObservedOutcome);
1046 }
1047 let refusing = matches!(self.outcome, Some(Outcome::Refused | Outcome::Failed));
1048 if self.refusal.is_some() != refusing {
1049 out.push(Finding::Refusal);
1050 }
1051 if (self.source == Source::Desired && self.observed.is_none())
1052 || (self.outcome == Some(Outcome::Converged) && self.source == Source::Baseline)
1053 || (self.outcome == Some(Outcome::Reverted) && self.source == Source::Desired)
1054 {
1055 out.push(Finding::Source);
1056 }
1057 let misplaced = self.in_force.is_some()
1058 && (self.source != Source::Desired || self.outcome == Some(Outcome::Failed));
1059 let not_observed = self.outcome == Some(Outcome::Converged)
1060 && self.source == Source::Desired
1061 && self.in_force != self.observed;
1062 if misplaced || not_observed {
1063 out.push(Finding::InForce);
1064 }
1065 if self.outcome == Some(Outcome::Reverted)
1066 && self.observed.is_some_and(|o| o.revision.is_some())
1067 {
1068 out.push(Finding::RevisionOnRevert);
1069 }
1070 if self.last_known && self.observed.is_none() {
1071 out.push(Finding::LastKnown);
1072 }
1073 out
1074 }
1075
1076 #[must_use]
1078 pub fn to_json(&self) -> Value {
1079 serde_json::to_value(self).unwrap_or(Value::Null)
1080 }
1081}
1082
1083pub const MAX_DEPTH: usize = crate::telemetry::decode::MAX_DEPTH;
1087
1088#[must_use]
1096pub fn strict_json(bytes: &[u8]) -> Option<Value> {
1097 fn value(d: &crate::telemetry::Datum) -> Option<Value> {
1098 use crate::telemetry::Datum as D;
1099 let float = |f: f64| serde_json::Number::from_f64(f).map(Value::Number);
1100 Some(match d {
1101 D::Null => Value::Null,
1102 D::Bool(b) => Value::Bool(*b),
1103 D::Int(i) => match (u64::try_from(*i), i64::try_from(*i)) {
1104 (Ok(u), _) => Value::from(u),
1105 (_, Ok(i)) => Value::from(i),
1106 #[allow(clippy::cast_precision_loss)]
1108 _ => float(*i as f64)?,
1109 },
1110 D::BigInt(f) | D::Float(f) => float(*f)?,
1111 D::Text(t) => Value::String(t.clone()),
1112 D::Array(a) => Value::Array(a.iter().map(value).collect::<Option<_>>()?),
1113 D::Map(m) => Value::Object(
1114 m.iter()
1115 .map(|(k, v)| Some((k.clone(), value(v)?)))
1116 .collect::<Option<_>>()?,
1117 ),
1118 D::Bytes(_) => return None,
1120 })
1121 }
1122 value(&crate::telemetry::decode::json(bytes)?)
1123}
1124
1125pub fn decode(bytes: &[u8]) -> Result<Report, Unreadable> {
1146 let v = strict_json(bytes).ok_or_else(|| {
1147 Unreadable::Json(format!(
1148 "not strict JSON: UTF-8, RFC 8259, no duplicate member, every number finite, at most {MAX_DEPTH} deep"
1149 ))
1150 })?;
1151 let exact = std::str::from_utf8(bytes)
1154 .ok()
1155 .and_then(Exact::of_strict_text);
1156 Report::read(&v, exact.as_ref())
1157}
1158
1159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1163pub enum Via {
1164 Owner,
1166 Archive,
1168}
1169
1170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1172pub enum Mutation {
1173 Put,
1174 Delete,
1175}
1176
1177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1189pub struct Content([u8; 32]);
1190
1191impl Content {
1192 fn digest(bytes: &[u8]) -> Self {
1193 use sha2::{Digest, Sha256};
1194 let mut d = [0u8; 32];
1195 d.copy_from_slice(&Sha256::digest(bytes));
1196 Self(d)
1197 }
1198
1199 #[must_use]
1205 pub fn of_json(v: &Value) -> Self {
1206 let mut out = Vec::new();
1207 Exact::of_value(v).write(&mut out);
1208 Self::digest(&out)
1209 }
1210
1211 #[must_use]
1213 pub fn of_bytes(bytes: &[u8]) -> Self {
1214 Self::digest(bytes)
1215 }
1216
1217 #[must_use]
1223 pub fn of_payload(bytes: &[u8], json: bool) -> Self {
1224 let read = json
1225 .then(|| std::str::from_utf8(bytes).ok())
1226 .flatten()
1227 .and_then(Exact::of_strict_text);
1228 match read {
1229 Some(e) => {
1230 let mut out = Vec::new();
1231 e.write(&mut out);
1232 Self::digest(&out)
1233 }
1234 None => Self::of_bytes(bytes),
1235 }
1236 }
1237}
1238
1239#[must_use]
1247pub fn exact_number(text: &str) -> Option<String> {
1248 let (neg, rest) = match text.strip_prefix('-') {
1249 Some(r) => (true, r),
1250 None => (false, text),
1251 };
1252 let (mantissa, exp) = match rest.find(['e', 'E']) {
1253 Some(i) => (&rest[..i], Some(&rest[i + 1..])),
1254 None => (rest, None),
1255 };
1256 let (int, frac) = match mantissa.split_once('.') {
1257 Some((i, f)) => (i, Some(f)),
1258 None => (mantissa, None),
1259 };
1260 let digits = |d: &str| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit());
1261 if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
1262 return None;
1263 }
1264 if frac.is_some_and(|f| !digits(f)) {
1265 return None;
1266 }
1267 let exp: i128 = match exp {
1268 None => 0,
1269 Some(e) => {
1270 let body = e.strip_prefix(['+', '-']).unwrap_or(e);
1271 if !digits(body) {
1272 return None;
1273 }
1274 e.parse().ok()?
1275 }
1276 };
1277 let frac = frac.unwrap_or("");
1278 let all: String = [int, frac].concat();
1279 let significant = all.trim_start_matches('0');
1280 if significant.is_empty() {
1281 return Some("0".to_owned());
1282 }
1283 let kept = significant.trim_end_matches('0');
1284 let trailing = i128::try_from(significant.len() - kept.len()).ok()?;
1285 let exp = exp
1286 .checked_sub(i128::try_from(frac.len()).ok()?)?
1287 .checked_add(trailing)?;
1288 Some(format!("{}{kept}e{exp}", if neg { "-" } else { "" }))
1289}
1290
1291enum Exact {
1294 Null,
1295 Bool(bool),
1296 Number(String),
1297 Text(String),
1298 Array(Vec<Exact>),
1299 Object(BTreeMap<String, Exact>),
1300}
1301
1302impl Exact {
1303 fn of_value(v: &Value) -> Self {
1304 match v {
1305 Value::Null => Self::Null,
1306 Value::Bool(b) => Self::Bool(*b),
1307 Value::Number(n) => {
1308 let text = match (n.as_u64(), n.as_i64(), n.as_f64()) {
1309 (Some(u), _, _) => u.to_string(),
1310 (None, Some(i), _) => i.to_string(),
1311 (None, None, Some(f)) => format!("{f:e}"),
1312 (None, None, None) => n.to_string(),
1313 };
1314 Self::Number(exact_number(&text).unwrap_or(text))
1316 }
1317 Value::String(s) => Self::Text(s.clone()),
1318 Value::Array(a) => Self::Array(a.iter().map(Self::of_value).collect()),
1319 Value::Object(m) => Self::Object(
1320 m.iter()
1321 .map(|(k, v)| (k.clone(), Self::of_value(v)))
1322 .collect(),
1323 ),
1324 }
1325 }
1326
1327 fn of_strict_text(text: &str) -> Option<Self> {
1334 crate::telemetry::decode::json(text.as_bytes())?;
1335 let mut r = ExactReader {
1336 text,
1337 s: text.as_bytes(),
1338 at: 0,
1339 };
1340 let v = r.value()?;
1341 r.ws();
1342 (r.at == r.s.len()).then_some(v)
1343 }
1344
1345 fn write(&self, out: &mut Vec<u8>) {
1346 match self {
1347 Self::Null => out.extend_from_slice(b"null"),
1348 Self::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
1349 Self::Number(n) => out.extend_from_slice(n.as_bytes()),
1350 Self::Text(s) => write_string(s, out),
1351 Self::Array(a) => {
1352 out.push(b'[');
1353 for (i, v) in a.iter().enumerate() {
1354 if i > 0 {
1355 out.push(b',');
1356 }
1357 v.write(out);
1358 }
1359 out.push(b']');
1360 }
1361 Self::Object(m) => {
1362 let mut members: Vec<(&String, &Exact)> = m.iter().collect();
1364 members.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
1365 out.push(b'{');
1366 for (i, (k, v)) in members.into_iter().enumerate() {
1367 if i > 0 {
1368 out.push(b',');
1369 }
1370 write_string(k, out);
1371 out.push(b':');
1372 v.write(out);
1373 }
1374 out.push(b'}');
1375 }
1376 }
1377 }
1378}
1379
1380fn write_string(s: &str, out: &mut Vec<u8>) {
1381 let quoted = serde_json::to_string(s).unwrap_or_default();
1382 out.extend_from_slice(quoted.as_bytes());
1383}
1384
1385struct ExactReader<'a> {
1396 text: &'a str,
1397 s: &'a [u8],
1398 at: usize,
1399}
1400
1401impl ExactReader<'_> {
1402 fn ws(&mut self) {
1403 while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.s.get(self.at) {
1404 self.at += 1;
1405 }
1406 }
1407
1408 fn eat(&mut self, b: u8) -> bool {
1409 let hit = self.s.get(self.at) == Some(&b);
1410 if hit {
1411 self.at += 1;
1412 }
1413 hit
1414 }
1415
1416 fn string(&mut self) -> Option<String> {
1417 let start = self.at;
1418 if !self.eat(b'"') {
1419 return None;
1420 }
1421 loop {
1422 match self.s.get(self.at)? {
1423 b'"' => break,
1424 b'\\' => self.at += 2,
1425 _ => self.at += 1,
1426 }
1427 }
1428 self.at += 1;
1429 serde_json::from_str(self.text.get(start..self.at)?).ok()
1430 }
1431
1432 fn value(&mut self) -> Option<Exact> {
1433 self.ws();
1434 match *self.s.get(self.at)? {
1435 b'{' => {
1436 self.at += 1;
1437 let mut m = BTreeMap::new();
1438 self.ws();
1439 if self.eat(b'}') {
1440 return Some(Exact::Object(m));
1441 }
1442 loop {
1443 self.ws();
1444 let k = self.string()?;
1445 self.ws();
1446 if !self.eat(b':') {
1447 return None;
1448 }
1449 let v = self.value()?;
1450 m.insert(k, v);
1451 self.ws();
1452 if self.eat(b'}') {
1453 return Some(Exact::Object(m));
1454 }
1455 if !self.eat(b',') {
1456 return None;
1457 }
1458 }
1459 }
1460 b'[' => {
1461 self.at += 1;
1462 let mut a = Vec::new();
1463 self.ws();
1464 if self.eat(b']') {
1465 return Some(Exact::Array(a));
1466 }
1467 loop {
1468 a.push(self.value()?);
1469 self.ws();
1470 if self.eat(b']') {
1471 return Some(Exact::Array(a));
1472 }
1473 if !self.eat(b',') {
1474 return None;
1475 }
1476 }
1477 }
1478 b'"' => self.string().map(Exact::Text),
1479 b't' | b'f' | b'n' => {
1480 for (word, v) in [
1481 ("true", Exact::Bool(true)),
1482 ("false", Exact::Bool(false)),
1483 ("null", Exact::Null),
1484 ] {
1485 if self.s[self.at..].starts_with(word.as_bytes()) {
1486 self.at += word.len();
1487 return Some(v);
1488 }
1489 }
1490 None
1491 }
1492 _ => {
1493 let start = self.at;
1494 while let Some(b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') = self.s.get(self.at)
1495 {
1496 self.at += 1;
1497 }
1498 exact_number(self.text.get(start..self.at)?).map(Exact::Number)
1499 }
1500 }
1501 }
1502}
1503
1504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1507pub struct Sample {
1508 pub via: Via,
1509 pub mutation: Mutation,
1510 pub stamp: Option<Stamp>,
1512 pub revision: Option<u64>,
1515 pub content: Option<Content>,
1519}
1520
1521#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1523pub enum ActKind {
1524 Apply,
1526 Revert,
1528}
1529
1530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1533pub struct Act {
1534 pub kind: ActKind,
1535 pub stamp: Stamp,
1536 pub revision: Option<u64>,
1537 pub via: Via,
1538 pub content: Option<Content>,
1539}
1540
1541impl Act {
1542 fn of(s: &Sample, stamp: Stamp) -> Self {
1543 Self {
1544 kind: match s.mutation {
1545 Mutation::Put => ActKind::Apply,
1546 Mutation::Delete => ActKind::Revert,
1547 },
1548 stamp,
1549 revision: match s.mutation {
1550 Mutation::Put => s.revision,
1551 Mutation::Delete => None,
1552 },
1553 via: s.via,
1554 content: match s.mutation {
1555 Mutation::Put => s.content,
1556 Mutation::Delete => None,
1557 },
1558 }
1559 }
1560
1561 #[must_use]
1564 pub fn same_document(&self, next: &Act) -> bool {
1565 machine::same_document((self.kind, self.content), (next.kind, next.content))
1566 }
1567
1568 #[must_use]
1570 pub fn version(&self) -> Version {
1571 Version {
1572 stamp: self.stamp,
1573 revision: self.revision,
1574 }
1575 }
1576}
1577
1578#[derive(Debug, Clone, PartialEq, Eq)]
1581pub enum Ended<R = Refusal> {
1582 Done,
1584 Refused(R),
1587 Failed(R),
1589}
1590
1591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1593pub enum Step {
1594 Act(Act),
1596 Adopted,
1599 Held,
1601 Unstamped,
1603 SameVersion,
1605 Older,
1607 Confirmed,
1610 Done,
1612}
1613
1614impl Step {
1615 #[must_use]
1617 pub fn as_str(&self) -> &'static str {
1618 match self {
1619 Self::Act(Act {
1620 kind: ActKind::Apply,
1621 ..
1622 }) => "act",
1623 Self::Act(Act {
1624 kind: ActKind::Revert,
1625 ..
1626 }) => "revert",
1627 Self::Adopted => "adopted",
1628 Self::Held => "held",
1629 Self::Unstamped => "unstamped",
1630 Self::SameVersion => "same_version",
1631 Self::Older => "older",
1632 Self::Confirmed => "confirmed",
1633 Self::Done => "done",
1634 }
1635 }
1636}
1637
1638pub const REMEMBERED_IDS: usize = 16;
1643
1644pub(crate) mod machine {
1650 use std::cmp::Ordering;
1651 use std::fmt;
1652
1653 use super::{ActKind, Content, Ended, Outcome, REMEMBERED_IDS, Source, Via};
1654
1655 pub(crate) trait Mark: Copy + Eq + fmt::Debug {
1659 type Epoch: Copy + Eq + fmt::Debug;
1660 type Tick: Copy + Ord + fmt::Debug;
1661 fn epoch(&self) -> Self::Epoch;
1662 fn tick(&self) -> Self::Tick;
1663 fn floor(&self) -> bool {
1668 false
1669 }
1670 }
1671
1672 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1675 pub(crate) struct Doing<M> {
1676 pub kind: ActKind,
1677 pub mark: M,
1678 pub revision: Option<u64>,
1679 pub via: Via,
1680 pub content: Option<Content>,
1681 }
1682
1683 pub(crate) fn same_document(
1686 a: (ActKind, Option<Content>),
1687 b: (ActKind, Option<Content>),
1688 ) -> bool {
1689 match (a.0, b.0) {
1690 (ActKind::Revert, ActKind::Revert) => true,
1691 (ActKind::Apply, ActKind::Apply) => a.1.is_some() && a.1 == b.1,
1692 _ => false,
1693 }
1694 }
1695
1696 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1698 pub(crate) enum Judged<M> {
1699 Act(Doing<M>),
1700 Adopted,
1701 Held,
1702 SameVersion,
1703 Older,
1704 Confirmed,
1705 }
1706
1707 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1709 pub(crate) enum Floored<M> {
1710 NoVerdict,
1711 Older,
1712 Held,
1713 Act(Doing<M>),
1714 }
1715
1716 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1718 pub(crate) enum Finished<M> {
1719 Done,
1720 Adopted,
1721 Act(Doing<M>),
1722 }
1723
1724 #[derive(Debug, Clone, PartialEq, Eq)]
1727 pub(crate) struct Ledger<M, R> {
1728 pub source: Source,
1729 pub in_force: Option<(M, Option<u64>)>,
1730 pub observed: Option<(M, Option<u64>)>,
1731 pub outcome: Option<Outcome>,
1733 pub refusal: Option<R>,
1734 pub last_known: bool,
1735 }
1736
1737 enum Not {
1739 Same,
1740 Older,
1741 }
1742
1743 fn admits<M: Mark>(held: &M, incoming: &M) -> Result<(), Not> {
1747 if held.epoch() != incoming.epoch() {
1748 return Ok(());
1749 }
1750 match incoming.tick().cmp(&held.tick()) {
1751 Ordering::Greater => Ok(()),
1752 Ordering::Equal if !held.floor() => Err(Not::Same),
1753 Ordering::Equal | Ordering::Less => Err(Not::Older),
1754 }
1755 }
1756
1757 fn confirm<M>(slot: &mut Doing<M>, via: Via) -> bool {
1760 let confirmed = via == Via::Owner && slot.via == Via::Archive;
1761 if confirmed {
1762 slot.via = Via::Owner;
1763 }
1764 confirmed
1765 }
1766
1767 #[derive(Debug, Clone)]
1771 pub(crate) struct Core<M: Mark, R> {
1772 acted: Option<Doing<M>>,
1773 running: bool,
1774 waiting: Option<Doing<M>>,
1775 remembered: Vec<(M::Epoch, M::Tick, bool)>,
1778 ledger: Ledger<M, R>,
1779 }
1780
1781 impl<M: Mark, R> Core<M, R> {
1782 pub fn new() -> Self {
1784 Self {
1785 acted: None,
1786 running: false,
1787 waiting: None,
1788 remembered: Vec::new(),
1789 ledger: Ledger {
1790 source: Source::Baseline,
1791 in_force: None,
1792 observed: None,
1793 outcome: None,
1794 refusal: None,
1795 last_known: false,
1796 },
1797 }
1798 }
1799
1800 pub fn ledger(&self) -> &Ledger<M, R> {
1801 &self.ledger
1802 }
1803
1804 pub fn running(&self) -> Option<&Doing<M>> {
1806 self.acted.as_ref().filter(|_| self.running)
1807 }
1808
1809 pub fn latest(&self) -> Option<&Doing<M>> {
1813 self.waiting.as_ref().or(self.acted.as_ref())
1814 }
1815
1816 pub fn remembered(&self, epoch: M::Epoch) -> Option<M::Tick> {
1819 self.remembered_as(epoch).map(|(t, _)| t)
1820 }
1821
1822 fn remembered_as(&self, epoch: M::Epoch) -> Option<(M::Tick, bool)> {
1823 self.remembered
1824 .iter()
1825 .find(|(e, _, _)| *e == epoch)
1826 .map(|(_, t, f)| (*t, *f))
1827 }
1828
1829 fn remember(&mut self, mark: M) {
1835 let (tick, floor) = match self
1836 .remembered
1837 .iter()
1838 .position(|(e, _, _)| *e == mark.epoch())
1839 {
1840 Some(at) => {
1841 let (_, tick, floor) = self.remembered.remove(at);
1842 match mark.tick().cmp(&tick) {
1843 Ordering::Greater => (mark.tick(), mark.floor()),
1844 Ordering::Equal => (tick, floor || mark.floor()),
1845 Ordering::Less => (tick, floor),
1846 }
1847 }
1848 None => (mark.tick(), mark.floor()),
1849 };
1850 self.remembered.insert(0, (mark.epoch(), tick, floor));
1851 self.remembered.truncate(REMEMBERED_IDS);
1852 }
1853
1854 pub fn observe(&mut self, doing: Doing<M>) -> Judged<M> {
1860 let mark = doing.mark;
1861 let remembered = self.remembered_as(mark.epoch());
1862 if let Some(r) = self.acted.as_mut() {
1863 if r.mark.epoch() == mark.epoch() {
1864 match admits(&r.mark, &mark) {
1865 Ok(()) => {}
1866 Err(Not::Same) if confirm(r, doing.via) => {
1867 if !self.running {
1868 self.ledger.last_known = false;
1869 }
1870 return Judged::Confirmed;
1871 }
1872 Err(Not::Same) => return Judged::SameVersion,
1873 Err(Not::Older) => return Judged::Older,
1874 }
1875 } else if let Some((tick, floor)) = remembered {
1876 match mark.tick().cmp(&tick) {
1882 Ordering::Greater => {}
1883 Ordering::Equal if !floor => return Judged::SameVersion,
1884 Ordering::Equal | Ordering::Less => return Judged::Older,
1885 }
1886 }
1887 }
1888 if let Some(w) = self.waiting.as_mut() {
1889 match admits(&w.mark, &mark) {
1890 Ok(()) => {}
1891 Err(Not::Same) if confirm(w, doing.via) => return Judged::Confirmed,
1892 Err(Not::Same) => return Judged::SameVersion,
1893 Err(Not::Older) => return Judged::Older,
1894 }
1895 }
1896 if self.running {
1897 self.waiting = Some(doing);
1898 return Judged::Held;
1899 }
1900 match self.start(doing) {
1901 Finished::Act(a) => Judged::Act(a),
1902 Finished::Adopted | Finished::Done => Judged::Adopted,
1903 }
1904 }
1905
1906 pub fn observe_floor(&mut self, floor: M) -> Floored<M> {
1910 let reverts = |held: &Doing<M>| {
1911 if held.kind != ActKind::Apply || held.mark.epoch() != floor.epoch() {
1912 Err(Floored::NoVerdict)
1913 } else if held.mark.tick() > floor.tick() {
1914 Err(Floored::Older)
1915 } else {
1916 Ok(())
1917 }
1918 };
1919 let Some(acted) = self.acted.as_ref() else {
1920 return Floored::NoVerdict;
1921 };
1922 if let Err(why) = reverts(acted) {
1923 return why;
1924 }
1925 if let Some(Err(why)) = self.waiting.as_ref().map(reverts) {
1926 return why;
1927 }
1928 let doing = Doing {
1929 kind: ActKind::Revert,
1930 mark: floor,
1931 revision: None,
1932 via: Via::Owner,
1933 content: None,
1934 };
1935 if self.running {
1936 self.waiting = Some(doing);
1937 return Floored::Held;
1938 }
1939 match self.start(doing) {
1940 Finished::Act(a) => Floored::Act(a),
1941 Finished::Adopted | Finished::Done => Floored::NoVerdict,
1943 }
1944 }
1945
1946 pub fn unchanged(&mut self, mark: M) -> bool {
1952 if let Some(w) = self.waiting.as_mut().filter(|w| w.mark == mark) {
1953 return confirm(w, Via::Owner);
1954 }
1955 let Some(a) = self.acted.as_mut().filter(|a| a.mark == mark) else {
1956 return false;
1957 };
1958 let confirmed = confirm(a, Via::Owner);
1959 if confirmed && !self.running {
1960 self.ledger.last_known = false;
1961 }
1962 confirmed
1963 }
1964
1965 fn start(&mut self, doing: Doing<M>) -> Finished<M> {
1966 self.remember(doing.mark);
1967 let version = (!doing.mark.floor()).then_some((doing.mark, doing.revision));
1968 if let Some(prev) = self.acted
1969 && same_document((prev.kind, prev.content), (doing.kind, doing.content))
1970 {
1971 let l = &mut self.ledger;
1972 if !prev.mark.floor() && l.in_force.is_some_and(|(m, _)| m == prev.mark) {
1973 l.in_force = version;
1974 }
1975 l.observed = version;
1976 l.last_known = doing.via == Via::Archive;
1977 self.acted = Some(doing);
1978 return Finished::Adopted;
1979 }
1980 self.acted = Some(doing);
1981 self.running = true;
1982 Finished::Act(doing)
1983 }
1984
1985 pub fn finish(&mut self, ended: Ended<R>) -> Finished<M> {
1989 let Some(act) = self.acted.filter(|_| self.running) else {
1990 return Finished::Done;
1991 };
1992 self.running = false;
1993 let l = &mut self.ledger;
1994 let version = (act.mark, act.revision);
1995 if !act.mark.floor() {
1996 l.observed = Some(version);
1997 l.last_known = act.via == Via::Archive;
1998 } else if matches!(ended, Ended::Done) {
1999 l.observed = None;
2004 l.last_known = false;
2005 }
2006 l.refusal = None;
2007 match (act.kind, ended) {
2008 (ActKind::Apply, Ended::Done) => {
2009 l.source = Source::Desired;
2010 l.in_force = Some(version);
2011 l.outcome = Some(Outcome::Converged);
2012 }
2013 (ActKind::Revert, Ended::Done) => {
2014 l.source = Source::Baseline;
2015 l.in_force = None;
2016 l.outcome = Some(Outcome::Reverted);
2017 }
2018 (ActKind::Apply, Ended::Refused(why)) => {
2019 l.outcome = Some(Outcome::Refused);
2020 l.refusal = Some(why);
2021 }
2022 (kind, Ended::Refused(why) | Ended::Failed(why)) => {
2023 l.source = match kind {
2024 ActKind::Apply => Source::Desired,
2025 ActKind::Revert => Source::Baseline,
2026 };
2027 l.in_force = None;
2028 l.outcome = Some(Outcome::Failed);
2029 l.refusal = Some(why);
2030 }
2031 }
2032 match self.waiting.take() {
2033 Some(next) => self.start(next),
2034 None => Finished::Done,
2035 }
2036 }
2037
2038 pub fn call(&mut self) {
2042 self.ledger.source = Source::Call;
2043 self.ledger.in_force = None;
2044 }
2045 }
2046}
2047
2048impl machine::Mark for Stamp {
2049 type Epoch = u128;
2050 type Tick = u64;
2051 fn epoch(&self) -> u128 {
2052 self.id
2053 }
2054 fn tick(&self) -> u64 {
2055 self.time
2056 }
2057}
2058
2059impl From<machine::Doing<Stamp>> for Act {
2060 fn from(d: machine::Doing<Stamp>) -> Self {
2061 Self {
2062 kind: d.kind,
2063 stamp: d.mark,
2064 revision: d.revision,
2065 via: d.via,
2066 content: d.content,
2067 }
2068 }
2069}
2070
2071#[derive(Debug, Clone)]
2077pub struct Target {
2078 core: machine::Core<Stamp, Refusal>,
2079 key: Option<String>,
2080 running: Option<Act>,
2081 report: Report,
2082}
2083
2084impl Target {
2085 #[must_use]
2088 pub fn new(key: Option<String>) -> Self {
2089 Self {
2090 core: machine::Core::new(),
2091 running: None,
2092 report: Report::baseline(key.clone()),
2093 key,
2094 }
2095 }
2096
2097 #[must_use]
2099 pub fn report(&self) -> &Report {
2100 &self.report
2101 }
2102
2103 #[must_use]
2105 pub fn running(&self) -> Option<&Act> {
2106 self.running.as_ref()
2107 }
2108
2109 #[must_use]
2112 pub fn remembered(&self, id: u128) -> Option<u64> {
2113 self.core.remembered(id)
2114 }
2115
2116 fn sync(&mut self) {
2119 let version = |(stamp, revision): (Stamp, Option<u64>)| Version { stamp, revision };
2120 let l = self.core.ledger();
2121 self.report = Report {
2122 key: self.key.clone(),
2123 source: l.source,
2124 in_force: l.in_force.map(version),
2125 observed: l.observed.map(version),
2126 outcome: l.outcome,
2127 refusal: l.refusal.clone(),
2128 last_known: l.last_known,
2129 };
2130 self.running = self.core.running().map(|d| Act::from(*d));
2131 }
2132
2133 pub fn observe(&mut self, s: Sample) -> Step {
2139 let Some(stamp) = s.stamp else {
2140 return Step::Unstamped;
2141 };
2142 let act = Act::of(&s, stamp);
2143 let step = match self.core.observe(machine::Doing {
2144 kind: act.kind,
2145 mark: stamp,
2146 revision: act.revision,
2147 via: act.via,
2148 content: act.content,
2149 }) {
2150 machine::Judged::Act(d) => Step::Act(d.into()),
2151 machine::Judged::Adopted => Step::Adopted,
2152 machine::Judged::Held => Step::Held,
2153 machine::Judged::SameVersion => Step::SameVersion,
2154 machine::Judged::Older => Step::Older,
2155 machine::Judged::Confirmed => Step::Confirmed,
2156 };
2157 self.sync();
2158 step
2159 }
2160
2161 pub fn finish(&mut self, ended: Ended) -> Step {
2166 let step = match self.core.finish(ended) {
2167 machine::Finished::Done => Step::Done,
2168 machine::Finished::Adopted => Step::Adopted,
2169 machine::Finished::Act(d) => Step::Act(d.into()),
2170 };
2171 self.sync();
2172 step
2173 }
2174
2175 pub fn call(&mut self) {
2179 self.core.call();
2180 self.sync();
2181 }
2182}
2183
2184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2188pub enum Seen {
2189 Present,
2191 Absent,
2194 Incomplete,
2197 AcrossFace,
2201}
2202
2203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2205pub enum Listing {
2206 NotListed,
2208 Listed { bound: bool },
2210}
2211
2212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2214pub struct Facts {
2215 pub source: Source,
2216 pub outcome: Option<Outcome>,
2220 pub last_known: bool,
2221 pub in_force: bool,
2224}
2225
2226pub trait Reported {
2229 fn facts(&self) -> Option<Facts>;
2232}
2233
2234impl Reported for Report {
2235 fn facts(&self) -> Option<Facts> {
2236 self.check().is_empty().then(|| Facts {
2237 source: self.source,
2238 outcome: self.outcome,
2239 last_known: self.last_known,
2240 in_force: self.in_force.is_some(),
2241 })
2242 }
2243}
2244
2245#[derive(Debug)]
2248pub enum ReportRead<'a, R = Report> {
2249 NotRead,
2251 Unreadable,
2253 Read(&'a R),
2256}
2257
2258impl<R> Clone for ReportRead<'_, R> {
2259 fn clone(&self) -> Self {
2260 *self
2261 }
2262}
2263
2264impl<R> Copy for ReportRead<'_, R> {}
2265
2266#[derive(Debug)]
2268pub struct TargetReading<'a, R = Report> {
2269 pub presence: Seen,
2270 pub descriptor: Option<Listing>,
2272 pub deployment: Option<Listing>,
2276 pub report: ReportRead<'a, R>,
2277 pub freshness: freshness::Verdict,
2281}
2282
2283impl<R> Clone for TargetReading<'_, R> {
2284 fn clone(&self) -> Self {
2285 *self
2286 }
2287}
2288
2289impl<R> Copy for TargetReading<'_, R> {}
2290
2291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2293pub enum Current {
2294 NotRead,
2296 Incomplete,
2298 Silent,
2300 Put(Stamp),
2302 Delete(Stamp),
2304}
2305
2306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2308pub struct AuthorReading {
2309 pub presence: Seen,
2310 pub current: Current,
2311}
2312
2313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2316pub enum Answer {
2317 Yes,
2318 No,
2319 NotYet,
2321 Unobservable,
2323 NotAsked,
2325}
2326
2327impl Answer {
2328 #[must_use]
2330 pub fn as_str(self) -> &'static str {
2331 match self {
2332 Self::Yes => "yes",
2333 Self::No => "no",
2334 Self::NotYet => "not_yet",
2335 Self::Unobservable => "unobservable",
2336 Self::NotAsked => "not_asked",
2337 }
2338 }
2339}
2340
2341impl fmt::Display for Answer {
2342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2343 f.write_str(self.as_str())
2344 }
2345}
2346
2347#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2349pub enum Reason {
2350 TargetAbsent,
2351 PresenceIncomplete,
2352 NoDescriptor,
2353 NotATarget,
2354 Unbound,
2355 NoReport,
2356 NothingCrossed,
2357 ReportInvalid,
2358 ReportStale,
2359 ReportUnobservable,
2360 NotActed,
2361 Converged,
2362 Refused,
2363 Failed,
2364 Reverted,
2365 LastKnown,
2366 Current,
2367 Desired,
2368 Partial,
2369 Baseline,
2370 Call,
2371 AuthorAbsent,
2372 AuthorPresenceIncomplete,
2373 AuthorNotRead,
2374 AuthorReadIncomplete,
2375 AuthorSilent,
2376 Behind,
2377 Ahead,
2378 OtherEpoch,
2379}
2380
2381impl Reason {
2382 #[must_use]
2384 pub fn as_str(self) -> &'static str {
2385 match self {
2386 Self::TargetAbsent => "target_absent",
2387 Self::PresenceIncomplete => "presence_incomplete",
2388 Self::NoDescriptor => "no_descriptor",
2389 Self::NotATarget => "not_a_target",
2390 Self::Unbound => "unbound",
2391 Self::NoReport => "no_report",
2392 Self::NothingCrossed => "nothing_crossed",
2393 Self::ReportInvalid => "report_invalid",
2394 Self::ReportStale => "report_stale",
2395 Self::ReportUnobservable => "report_unobservable",
2396 Self::NotActed => "not_acted",
2397 Self::Converged => "converged",
2398 Self::Refused => "refused",
2399 Self::Failed => "failed",
2400 Self::Reverted => "reverted",
2401 Self::LastKnown => "last_known",
2402 Self::Current => "current",
2403 Self::Desired => "desired",
2404 Self::Partial => "partial",
2405 Self::Baseline => "baseline",
2406 Self::Call => "call",
2407 Self::AuthorAbsent => "author_absent",
2408 Self::AuthorPresenceIncomplete => "author_presence_incomplete",
2409 Self::AuthorNotRead => "author_not_read",
2410 Self::AuthorReadIncomplete => "author_read_incomplete",
2411 Self::AuthorSilent => "author_silent",
2412 Self::Behind => "behind",
2413 Self::Ahead => "ahead",
2414 Self::OtherEpoch => "other_epoch",
2415 }
2416 }
2417}
2418
2419impl fmt::Display for Reason {
2420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2421 f.write_str(self.as_str())
2422 }
2423}
2424
2425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2427pub struct Judged {
2428 pub answer: Answer,
2429 pub reason: Reason,
2430}
2431
2432impl Judged {
2433 const fn new(answer: Answer, reason: Reason) -> Self {
2434 Self { answer, reason }
2435 }
2436}
2437
2438fn premises<'a, R: Reported>(
2444 t: &TargetReading<'a, R>,
2445 unbound: Judged,
2446) -> Result<(&'a R, Facts), Judged> {
2447 use Answer::{NotAsked, Unobservable};
2448 let listing = match t.presence {
2449 Seen::Absent => return Err(Judged::new(NotAsked, Reason::TargetAbsent)),
2450 Seen::Incomplete => return Err(Judged::new(Unobservable, Reason::PresenceIncomplete)),
2451 Seen::AcrossFace => t.deployment,
2452 Seen::Present => t.descriptor,
2453 };
2454 match listing {
2455 None => return Err(Judged::new(Unobservable, Reason::NoDescriptor)),
2456 Some(Listing::NotListed) => return Err(Judged::new(NotAsked, Reason::NotATarget)),
2457 Some(Listing::Listed { bound: false }) => return Err(unbound),
2458 Some(Listing::Listed { bound: true }) => {}
2459 }
2460 let report = match t.report {
2461 ReportRead::NotRead => {
2462 return Err(Judged::new(
2463 Unobservable,
2464 if t.presence == Seen::AcrossFace {
2465 Reason::NothingCrossed
2466 } else {
2467 Reason::NoReport
2468 },
2469 ));
2470 }
2471 ReportRead::Unreadable => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
2472 ReportRead::Read(r) => match r.facts() {
2473 Some(f) => (r, f),
2474 None => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
2475 },
2476 };
2477 match t.freshness {
2478 freshness::Verdict::Stale => Err(Judged::new(Unobservable, Reason::ReportStale)),
2479 freshness::Verdict::Unobservable => {
2480 Err(Judged::new(Unobservable, Reason::ReportUnobservable))
2481 }
2482 freshness::Verdict::Fresh | freshness::Verdict::NotAsked => Ok(report),
2483 }
2484}
2485
2486const UNBOUND: Judged = Judged::new(Answer::NotAsked, Reason::Unbound);
2487
2488fn converging<'a, R: Reported>(
2491 t: &TargetReading<'a, R>,
2492 author: Seen,
2493) -> Result<(&'a R, Facts), Judged> {
2494 let r = premises(t, UNBOUND)?;
2495 match author {
2496 Seen::Absent => Err(Judged::new(Answer::NotAsked, Reason::AuthorAbsent)),
2497 Seen::Incomplete => Err(Judged::new(
2498 Answer::Unobservable,
2499 Reason::AuthorPresenceIncomplete,
2500 )),
2501 Seen::Present | Seen::AcrossFace => Ok(r),
2502 }
2503}
2504
2505fn compared<M: machine::Mark>(observed: &M, current: &M, outcome: Outcome) -> Judged {
2510 if observed == current {
2511 return match outcome {
2512 Outcome::Converged | Outcome::Reverted => {
2513 Judged::new(Answer::Yes, outcome_reason(outcome))
2514 }
2515 Outcome::Refused | Outcome::Failed => Judged::new(Answer::No, outcome_reason(outcome)),
2516 };
2517 }
2518 if observed.epoch() != current.epoch() {
2519 return Judged::new(Answer::NotYet, Reason::OtherEpoch);
2520 }
2521 if observed.tick() < current.tick() {
2522 Judged::new(Answer::NotYet, Reason::Behind)
2523 } else {
2524 Judged::new(Answer::Unobservable, Reason::Ahead)
2525 }
2526}
2527
2528fn outcome_reason(o: Outcome) -> Reason {
2529 match o {
2530 Outcome::Converged => Reason::Converged,
2531 Outcome::Refused => Reason::Refused,
2532 Outcome::Failed => Reason::Failed,
2533 Outcome::Reverted => Reason::Reverted,
2534 }
2535}
2536
2537#[must_use]
2540pub fn refused<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
2541 let r = match premises(t, UNBOUND) {
2542 Ok((_, f)) => f,
2543 Err(j) => return j,
2544 };
2545 match r.outcome {
2546 None => Judged::new(Answer::NotAsked, Reason::NotActed),
2547 Some(o @ (Outcome::Refused | Outcome::Failed)) => {
2548 Judged::new(Answer::Yes, outcome_reason(o))
2549 }
2550 Some(o) => Judged::new(Answer::No, outcome_reason(o)),
2551 }
2552}
2553
2554#[must_use]
2560pub fn last_known<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
2561 let r = match premises(t, UNBOUND) {
2562 Ok((_, f)) => f,
2563 Err(j) => return j,
2564 };
2565 match (r.outcome, r.last_known) {
2566 (None, _) => Judged::new(Answer::NotAsked, Reason::NotActed),
2567 (Some(_), true) => Judged::new(Answer::Yes, Reason::LastKnown),
2568 (Some(_), false) => Judged::new(Answer::No, Reason::Current),
2569 }
2570}
2571
2572#[must_use]
2576pub fn in_force<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
2577 let r = match premises(t, Judged::new(Answer::No, Reason::Unbound)) {
2578 Ok((_, f)) => f,
2579 Err(j) => return j,
2580 };
2581 match r.source {
2582 Source::Desired if r.in_force => Judged::new(Answer::Yes, Reason::Desired),
2583 Source::Desired => Judged::new(Answer::Yes, Reason::Partial),
2584 Source::Baseline => Judged::new(Answer::No, Reason::Baseline),
2585 Source::Call => Judged::new(Answer::No, Reason::Call),
2586 }
2587}
2588
2589#[must_use]
2594pub fn converged(t: &TargetReading<'_>, a: &AuthorReading) -> Judged {
2595 use Answer::{NotYet, Unobservable};
2596 let r = match converging(t, a.presence) {
2597 Ok((r, _)) => r,
2598 Err(j) => return j,
2599 };
2600 let current = match a.current {
2601 Current::NotRead => return Judged::new(Unobservable, Reason::AuthorNotRead),
2602 Current::Incomplete => return Judged::new(Unobservable, Reason::AuthorReadIncomplete),
2603 Current::Silent => return Judged::new(Unobservable, Reason::AuthorSilent),
2604 Current::Put(s) | Current::Delete(s) => s,
2605 };
2606 let (Some(observed), Some(outcome)) = (&r.observed, r.outcome) else {
2607 return Judged::new(NotYet, Reason::NotActed);
2608 };
2609 compared(&observed.stamp, ¤t, outcome)
2610}
2611
2612#[cfg(test)]
2613mod tests {
2614 use super::*;
2615
2616 fn st(time: u64, id: &str) -> Stamp {
2617 Stamp::parse(time, id).expect("a stamp")
2618 }
2619
2620 fn put(time: u64, id: &str) -> Sample {
2621 Sample {
2622 via: Via::Owner,
2623 mutation: Mutation::Put,
2624 stamp: Some(st(time, id)),
2625 revision: Some(time),
2626 content: Some(Content::of_json(&serde_json::json!({"revision": time}))),
2627 }
2628 }
2629
2630 #[test]
2631 fn stamps_read_as_zenoh_writes_them() {
2632 assert_eq!(
2633 parse_stamp("7386690599959157260/33"),
2634 Some(st(7_386_690_599_959_157_260, "33"))
2635 );
2636 assert_eq!(st(7, "1bc0").to_string(), "7/1bc0");
2637 assert_eq!(parse_stamp("0/1"), Some(st(0, "1")));
2638 assert_eq!(
2639 parse_stamp(&format!("{}/1", u64::MAX)),
2640 Some(st(u64::MAX, "1"))
2641 );
2642 for bad in [
2643 "",
2644 "1",
2645 "/1",
2646 "1/",
2647 "01/1",
2648 "1/01",
2649 "1/A",
2650 "+1/1",
2651 "1/0",
2652 "18446744073709551616/1",
2653 "1/1/1",
2654 " 1/1",
2655 ] {
2656 assert_eq!(parse_stamp(bad), None, "{bad:?}");
2657 }
2658 }
2659
2660 #[test]
2661 fn a_report_serializes_as_the_schema_names_it() {
2662 let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
2663 assert_eq!(
2664 t.report().to_json(),
2665 serde_json::json!({"key": "zk2/a/b/i.v1/state/x", "source": "baseline"})
2666 );
2667 assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
2668 t.finish(Ended::Done);
2669 let v = t.report().to_json();
2670 assert_eq!(
2671 v,
2672 serde_json::json!({
2673 "key": "zk2/a/b/i.v1/state/x",
2674 "source": "desired",
2675 "in_force": {"stamp": "100/a1", "revision": 100},
2676 "observed": {"stamp": "100/a1", "revision": 100},
2677 "outcome": "converged",
2678 })
2679 );
2680 let back: Report = serde_json::from_value(v.clone()).expect("serde reads it back");
2681 assert_eq!(&back, t.report());
2682 assert_eq!(Report::from_json(&v).as_ref(), Ok(t.report()));
2683 assert!(t.report().check().is_empty());
2684 }
2685
2686 #[test]
2687 fn every_report_the_machine_makes_is_consistent() {
2688 let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
2689 let mut seen = Vec::new();
2690 let steps = vec![
2691 put(100, "a1"),
2692 put(200, "a1"),
2693 Sample {
2694 mutation: Mutation::Delete,
2695 revision: None,
2696 ..put(300, "a1")
2697 },
2698 Sample {
2699 via: Via::Archive,
2700 ..put(400, "b2")
2701 },
2702 ];
2703 for (i, s) in steps.into_iter().enumerate() {
2704 assert!(
2705 matches!(t.observe(s), Step::Act(_)),
2706 "a new document is acted on"
2707 );
2708 let again = Sample {
2710 stamp: s.stamp.map(|x| Stamp {
2711 time: x.time + 1,
2712 ..x
2713 }),
2714 ..s
2715 };
2716 assert_eq!(t.observe(again), Step::Held);
2717 let ended = match i % 3 {
2718 0 => Ended::Done,
2719 1 => Ended::Refused(Refusal::new(REACH)),
2720 _ => Ended::Failed(Refusal::new(APPLY)),
2721 };
2722 assert_eq!(
2723 t.finish(ended),
2724 Step::Adopted,
2725 "the held re-put is the same document"
2726 );
2727 seen.push(t.report().clone());
2728 t.call();
2729 seen.push(t.report().clone());
2730 }
2731 for r in &seen {
2732 assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
2733 }
2734 }
2735
2736 #[test]
2737 fn numbers_compare_by_their_exact_value() {
2738 for (text, exact) in [
2739 ("0", "0"),
2740 ("-0", "0"),
2741 ("0.000", "0"),
2742 ("0e99", "0"),
2743 ("10", "1e1"),
2744 ("10.0", "1e1"),
2745 ("1e1", "1e1"),
2746 ("100E-1", "1e1"),
2747 ("1.5", "15e-1"),
2748 ("-0.25", "-25e-2"),
2749 ("9007199254740992", "9007199254740992e0"),
2750 ("9007199254740993", "9007199254740993e0"),
2751 ("18446744073709551617", "18446744073709551617e0"),
2752 ("1e+2", "1e2"),
2753 ] {
2754 assert_eq!(exact_number(text).as_deref(), Some(exact), "{text}");
2755 }
2756 for bad in ["", "-", "01", "1.", ".5", "+1", "1e", "1e+", "--1", "0x1"] {
2757 assert_eq!(exact_number(bad), None, "{bad:?}");
2758 }
2759 }
2760
2761 #[test]
2762 fn a_payload_and_its_decoded_value_compare_alike() {
2763 let same = |a: &str, b: &str| {
2764 Content::of_payload(a.as_bytes(), true) == Content::of_payload(b.as_bytes(), true)
2765 };
2766 assert!(same(
2767 r#"{"a":10,"b":[1,2]}"#,
2768 r#" { "b" : [1, 2.0], "a" : 1e1 } "#
2769 ));
2770 assert!(same(r#"{"s":"\u0041"}"#, r#"{"s":"A"}"#));
2771 assert!(!same(
2772 r#"{"revision":9007199254740992}"#,
2773 r#"{"revision":9007199254740993}"#
2774 ));
2775 assert!(!same(
2776 r#"{"revision":18446744073709551616}"#,
2777 r#"{"revision":18446744073709551617}"#
2778 ));
2779 assert!(!same(r#"{"x":0.1}"#, r#"{"x":0.10000000000000000555}"#));
2780 assert!(same(r#"{"a":1e400}"#, r#"{"a":1e400}"#));
2782 assert!(!same(r#"{"a":1e400}"#, r#"{"a": 1e400}"#));
2783 assert!(!same(r#"{"a":1,"a":1}"#, r#"{"a":1}"#));
2784 for text in [
2785 r#"{"mode":"run","rate_hz":10.0,"revision":1}"#,
2786 r#"{"revision":9007199254740993,"x":[-0.5,true,null,"é"]}"#,
2787 ] {
2788 let v = crate::strict::parse_json(text).expect("strict JSON");
2789 assert_eq!(
2790 Content::of_payload(text.as_bytes(), true),
2791 Content::of_json(&v),
2792 "{text}"
2793 );
2794 }
2795 assert_ne!(
2796 Content::of_payload(b"{}", false),
2797 Content::of_payload(b"{ }", false),
2798 "a payload that is not JSON compares byte for byte"
2799 );
2800 }
2801
2802 #[test]
2803 fn a_decoded_value_and_its_text_agree_where_the_text_says() {
2804 let of_json = |v: Value| Content::of_json(&serde_json::json!({ "x": v }));
2805 let of_text = |t: &str| Content::of_payload(format!(r#"{{"x":{t}}}"#).as_bytes(), true);
2806 assert_eq!(
2808 of_json(serde_json::json!(1e20)),
2809 of_text("100000000000000000000")
2810 );
2811 assert_eq!(of_json(serde_json::json!(1e20)), of_text("1e20"));
2812 assert_eq!(of_json(serde_json::json!(1e300)), of_text("1e300"));
2813 assert_eq!(
2814 of_json(serde_json::json!(1e300)),
2815 of_text(&format!("1{}", "0".repeat(300)))
2816 );
2817 assert_eq!(of_json(serde_json::json!(-0.0)), of_text("0"));
2818 assert_eq!(of_json(serde_json::json!(0)), of_text("-0.0"));
2819 assert_eq!(of_json(serde_json::json!(0.1)), of_text("0.1"));
2820 assert_eq!(
2821 of_json(serde_json::json!(9_007_199_254_740_993_u64)),
2822 of_text("9007199254740993")
2823 );
2824 assert_ne!(
2826 of_json(serde_json::json!(0.1)),
2827 of_text("0.10000000000000000555")
2828 );
2829 assert_ne!(
2830 of_json(serde_json::json!(9_007_199_254_740_992_u64)),
2831 of_text("9007199254740993")
2832 );
2833 assert_ne!(
2834 of_json(serde_json::json!(1e20)),
2835 of_text("100000000000000000001")
2836 );
2837 }
2838
2839 #[test]
2840 fn a_held_version_is_remembered_only_once_it_starts() {
2841 let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
2842 assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
2843 assert_eq!(t.observe(put(50, "b2")), Step::Held);
2844 assert_eq!(t.remembered(0xb2), None, "held waiting, not acted on");
2845 assert_eq!(t.remembered(0xa1), Some(100), "the running act counts");
2846 assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
2847 assert_eq!(t.remembered(0xb2), Some(50));
2848 t.finish(Ended::Done);
2849 let again = Sample {
2851 content: put(50, "b2").content,
2852 revision: Some(50),
2853 ..put(70, "b2")
2854 };
2855 assert_eq!(t.observe(again), Step::Adopted);
2856 assert_eq!(t.remembered(0xb2), Some(70));
2857 assert_eq!(t.observe(put(60, "b2")), Step::Older);
2858 }
2859
2860 #[test]
2861 fn finite_is_by_rounding() {
2862 let with = |n: &str| format!(r#"{{"source":"baseline","x":{n}}}"#);
2863 assert!(decode(with("1.7976931348623158e308").as_bytes()).is_ok());
2864 for n in ["1.7976931348623159e308", "1e400", "-1e400"] {
2865 assert!(
2866 matches!(decode(with(n).as_bytes()), Err(Unreadable::Json(_))),
2867 "{n}"
2868 );
2869 }
2870 let nested = |n: usize| {
2872 format!(
2873 r#"{{"source":"baseline","x":{}{}}}"#,
2874 "[".repeat(n),
2875 "]".repeat(n)
2876 )
2877 };
2878 assert!(decode(nested(MAX_DEPTH - 1).as_bytes()).is_ok());
2879 assert!(matches!(
2880 decode(nested(MAX_DEPTH).as_bytes()),
2881 Err(Unreadable::Json(_))
2882 ));
2883 assert!(matches!(
2884 decode(nested(100_000).as_bytes()),
2885 Err(Unreadable::Json(_))
2886 ));
2887 let deep = |n: usize, ws: &str| format!("{}{ws}{}", "[".repeat(n), "]".repeat(n));
2890 assert_eq!(
2891 Content::of_payload(deep(MAX_DEPTH, " ").as_bytes(), true),
2892 Content::of_payload(deep(MAX_DEPTH, "").as_bytes(), true)
2893 );
2894 assert_ne!(
2895 Content::of_payload(deep(MAX_DEPTH + 1, " ").as_bytes(), true),
2896 Content::of_payload(deep(MAX_DEPTH + 1, "").as_bytes(), true)
2897 );
2898 let big = format!("1{}", "0".repeat(400));
2899 assert!(matches!(
2900 decode(with(&big).as_bytes()),
2901 Err(Unreadable::Json(_))
2902 ));
2903 }
2904
2905 #[test]
2908 fn a_revision_reads_by_its_exact_value() {
2909 let rep = |r: &str| {
2910 format!(
2911 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"}}"#
2912 )
2913 };
2914 let observed = |r: &str| decode(rep(r).as_bytes()).map(|x| x.observed.unwrap().revision);
2915 assert_eq!(observed("18446744073709551615.0"), Ok(Some(u64::MAX)));
2916 assert_eq!(observed("30e-1"), Ok(Some(3)));
2917 assert_eq!(observed("-0.0"), Ok(Some(0)));
2918 assert_eq!(observed("1e19"), Ok(Some(10_000_000_000_000_000_000)));
2919 assert!(matches!(
2920 observed("18446744073709551616.0"),
2921 Err(Unreadable::RevisionRange(_))
2922 ));
2923 assert!(matches!(observed("1e400"), Err(Unreadable::Json(_))));
2924 assert!(
2925 matches!(observed("1e99999999999999999999"), Err(Unreadable::Json(_))),
2926 "never finite: not strict JSON, before the schema"
2927 );
2928 assert!(matches!(
2929 exact_revision("1e99999999999999999999"),
2930 Some(RevisionRead::TooLarge)
2931 ));
2932 assert!(exact_revision("1e-99999999999999999999").is_none());
2933 assert!(matches!(observed("1.5"), Err(Unreadable::Schema(_))));
2934 assert!(matches!(observed("-1"), Err(Unreadable::Schema(_))));
2935 let v: Value = serde_json::from_str(&rep("18446744073709551615.0")).unwrap();
2937 assert!(matches!(
2938 Report::from_json(&v),
2939 Err(Unreadable::RevisionRange(_))
2940 ));
2941 assert_eq!(
2942 revision_of_text(br#"{"revision": 3.0, "mode": "run"}"#),
2943 Some(3)
2944 );
2945 assert_eq!(
2946 revision_of_text(br#"{"revision": 18446744073709551615.0}"#),
2947 Some(u64::MAX)
2948 );
2949 for none in [
2950 &br#"{"revision": 1.5}"#[..],
2951 br#"{"revision": "1"}"#,
2952 br#"{"revision": 18446744073709551616}"#,
2953 br#"[1]"#,
2954 br#"{"rev": 1}"#,
2955 b"not json",
2956 ] {
2957 assert_eq!(
2958 revision_of_text(none),
2959 None,
2960 "{}",
2961 String::from_utf8_lossy(none)
2962 );
2963 }
2964 assert_eq!(
2965 revision_of_value(&serde_json::json!({"revision": "18446744073709551615"})),
2966 Some(u64::MAX),
2967 "protobuf's JSON mapping writes a 64-bit field as a string"
2968 );
2969 assert_eq!(
2970 revision_of_value(&serde_json::json!({"revision": 7})),
2971 Some(7)
2972 );
2973 assert_eq!(
2974 revision_of_value(&serde_json::json!({"revision": "x"})),
2975 None
2976 );
2977 }
2978
2979 #[test]
2980 fn an_id_forgotten_beyond_sixteen_is_read_as_new() {
2981 let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
2982 let ids: Vec<String> = (1..=17).map(|i| format!("{i:x}")).collect();
2983 for (n, id) in ids.iter().enumerate() {
2984 let s = Sample {
2985 revision: Some(n as u64),
2986 content: Some(Content::of_json(&serde_json::json!({"revision": n}))),
2987 ..put(500, id)
2988 };
2989 assert!(matches!(t.observe(s), Step::Act(_)), "{id}");
2990 t.finish(Ended::Done);
2991 }
2992 assert_eq!(t.remembered(2), Some(500));
2994 assert_eq!(t.observe(put(400, "2")), Step::Older);
2995 assert_eq!(t.observe(put(500, "2")), Step::SameVersion);
2996 assert_eq!(t.remembered(1), None);
2998 assert!(matches!(t.observe(put(400, "1")), Step::Act(_)));
2999 }
3000}