Skip to main content

zenkey_model/
desired.rs

1//! `desired.v1`: desired documents, from their author to their target
2//! (`spec/profiles/desired/v1.md`, #840).
3//!
4//! The profile's session-free half: the declaration read from a resolved
5//! resource (§2.2), a requirement's binding and its slice's key (§2.3), a
6//! stamp as a report writes it (§2.4), the standard `Report` with its
7//! reading and its consistency (§2.10), a target's state machine (§2.6 to
8//! §2.10), pure and two-phase like [`crate::config::Owner`], and §5's four
9//! questions as judgements in three states (§2.17).
10//!
11//! ```text
12//! declaration(kind, template, annotations) ─▶ declared [targets] │ invalid [reasons] │ not this profile's   §2.2
13//! binding(slice, requirement, own address) ─▶ bound {key} │ unbound (the kill switch) │ invalid [problems] §2.3
14//! parse_stamp(text) / Stamp's Display       ─▶ <time>/<id>, as zenoh writes a timestamp                    §2.4
15//! decode(bytes), Report::from_json(v)       ─▶ Report │ Unreadable{json, schema, stamp, revision_range}    §2.10
16//! Report::check()                           ─▶ the findings: keyless, key_form, observed_outcome, …        §2.10
17//! Content::of_payload(bytes, json)          ─▶ a put's document, JCS-equal by exact value for JSON, else byte-equal  §2.7
18//! revision_of_text(bytes) / revision_of_value(v) ─▶ a document's own revision, by its exact value          §2.4
19//! Target::observe(sample)                   ─▶ act │ revert │ adopted │ held │ unstamped │ same_version │ older │ confirmed  §2.6–§2.9
20//!   against the version held, every id remembered (16), then the one held waiting while an act runs
21//! Target::finish(ended)                     ─▶ the report updated; done, or the held version adopted or acted on  §2.7, §2.10
22//! Target::call()                            ─▶ source call                                                 §2.7
23//! converged(target, author)                 ─▶ §5 "has the target converged on its author's current document?"
24//! refused(target) / last_known(target) / in_force(target) ─▶ §5's other three questions              §2.17
25//! ```
26//!
27//! There is no I/O and no clock here. A target's runtime subscribes, seeds
28//! and reads an archive (§2.5, §2.9), hands each sample to
29//! [`Target::observe`] as it arrives, performs each [`Act`] on its own
30//! application (decode, check, apply or revert), tells
31//! [`Target::finish`] how it ended, and puts [`Target::report`] whenever it
32//! changes (§2.10). An author's writes, its diff and its record (§2.11) are
33//! the runtime's.
34//!
35//! [`v2`] is `desired.v2`'s half (`spec/profiles/desired/v2.md`, #986),
36//! which restates this major by reference. What the two share is here, one
37//! copy of each rule: the state machine (`machine`, a version ordered by
38//! a tick within an epoch, v1's time within an id and v2's seq within a
39//! run), and §5's judges, which read a report of either major through
40//! [`Reported`].
41
42use 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
57/// The profile's id, as a contract lists it in `uses`.
58pub const PROFILE: &str = "desired.v1";
59
60/// The profile's name, as an annotation key's prefix carries it.
61pub const NAME: &str = "desired";
62
63/// `desired.target_param` (§4).
64pub const TARGET_PARAM: &str = "desired.target_param";
65
66/// The published vocabulary (§4): the keys under `desired.`, which W105
67/// reads in place of core Appendix D's interim row (core 0.36). The interim
68/// `target` is retired, so W105 warns of it.
69pub const VOCABULARY: &[&str] = &["target_param"];
70
71/// The standard schema's stem (§3): `desired.v1.json`.
72pub const SCHEMA_STEM: &str = "desired.v1";
73/// The report's type name (§2.10, §3).
74pub const REPORT: &str = "desired.v1.Report";
75/// A version's type name (§2.4, §3).
76pub const VERSION: &str = "desired.v1.Version";
77/// A refusal's type name (§2.10, §3).
78pub const REFUSAL: &str = "desired.v1.Refusal";
79
80/// The standard schema's artifact ids the profile publishes (§3), oldest
81/// first: text 0.1's, then text 0.2's, whose descriptions say "acted on or
82/// adopted" (F-173). A type of one of these artifacts is the profile's.
83pub const PUBLISHED: &[&str] = &[
84    "sha256:8c5ffce35fadeb6196233a46e163ee3b15cbd2bd8339a05de2cf8fe22b52e9ef",
85    "sha256:43c952598f454ec903dba63bad36419f5dcff3312db727bd4e58a88dc1ca55ae",
86];
87
88/// Whether `id` is one of the standard schema's published artifact ids.
89#[must_use]
90pub fn is_published(id: &str) -> bool {
91    PUBLISHED.contains(&id)
92}
93
94/// R2's spelling of the target's own system (core §3.2).
95pub const SELF_SYSTEM: &str = "self.system";
96/// R2's spelling of the target's own service (core §3.2).
97pub const SELF_SERVICE: &str = "self.service";
98
99/// The longest refusal code, in characters (§3).
100pub const MAX_CODE: usize = 64;
101
102/// The profile's refusal codes (§2.7, §2.10): the document does not decode
103/// as its type.
104pub const UNDECODABLE: &str = "undecodable";
105/// It names what the target needs to reach the bus.
106pub const REACH: &str = "reach";
107/// It carries a sensitive value: a secret, a credential, a key
108/// (`config.v1`'s word).
109pub const SENSITIVE: &str = "sensitive";
110/// Its type, or the target's own validation of it, refuses it.
111pub const INVALID: &str = "invalid";
112/// An act that could not finish.
113pub const APPLY: &str = "apply";
114
115// --- §2.2: the declaration -----------------------------------------------------
116
117/// Which identity of the target fills a target parameter (§2.2).
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub enum Binds {
120    /// The one target parameter: `self.system` or `self.service`, as the
121    /// deployment chooses.
122    Either,
123    /// The first of two: `self.system`.
124    System,
125    /// The second of two: `self.service`.
126    Service,
127}
128
129impl Binds {
130    /// The fixture's token.
131    #[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    /// Whether a parameter binding spelled `bound` (core R2) is this one.
141    #[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/// One target parameter (§2.2).
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct TargetParam {
154    pub param: String,
155    pub binds: Binds,
156}
157
158/// Why a declaration is invalid (§2.2), in the order checked.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub enum Invalid {
161    /// The resource is not state.
162    NotState,
163    /// Not a string, nor an array of one or two strings.
164    Value,
165    /// A name twice.
166    Repeated,
167    /// A name that is no parameter of the template.
168    NotAParam,
169    /// A name of a rest parameter.
170    RestParam,
171    /// A template parameter the value does not name.
172    ParamNotTarget,
173    /// A target parameter, not a rest one, whose type is not `string`
174    /// (text 0.2, F-170).
175    NotString,
176    /// `desired.v2` §2.2 alone, checked last: a horizon above 0 in a
177    /// contract that does not use `freshness.v2` ([`v2::declaration`]).
178    /// [`declaration`], `desired.v1`'s reading, never gives it.
179    HorizonV1,
180}
181
182impl Invalid {
183    /// The fixture's token.
184    #[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    /// What it says, for a linter's line.
199    #[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/// A resource's declaration (§2.2).
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub enum Declaration {
227    /// No `desired.target_param`.
228    NotThisProfiles,
229    /// The reasons, in the order checked.
230    Invalid(Vec<Invalid>),
231    /// The target parameters, in the value's order.
232    Declared(Vec<TargetParam>),
233}
234
235impl Declaration {
236    /// The fixture's token.
237    #[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    /// The target parameters of a valid declaration.
247    #[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/// Reads the declaration of a resource of `kind`, `template` and parameter
257/// types `params` (core §2.2) from its resolved annotations (§2.2, core
258/// §9.3). Each check runs alone, and a check that needs a value an earlier
259/// one found wrong is skipped: `not_string` reads the type of a name that
260/// is a parameter and not a rest one, and a parameter `params` does not
261/// list (core E011's) is no finding here. A horizon, whatever its value,
262/// makes no declaration invalid: its re-puts are the same document, which
263/// a target adopts (§2.7).
264#[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            // A system or a service name is a string (0.2, F-170). A rest
306            // parameter is `path` (core §2.2), and `rest_param`'s alone.
307            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            // One or two names, by the match above.
332            _ => return Declaration::Invalid(vec![Invalid::Value]),
333        }),
334        _ => Declaration::Invalid(why),
335    }
336}
337
338/// [`declaration`] of a resource of a contract.
339#[must_use]
340pub fn declaration_of(r: &Resource) -> Declaration {
341    declaration(r.kind, &r.template, &r.params, &r.annotations)
342}
343
344// --- §2.3: the binding ---------------------------------------------------------
345
346/// A target's requirement on a desired resource, as its descriptor lists it
347/// (core §3.3).
348#[derive(Debug, Clone, Copy)]
349pub struct Requirement<'a> {
350    /// The provider addresses, `<system>/<service>`, a chunk possibly `*`.
351    pub bindings: &'a [String],
352    /// The parameter bindings, as configured (core R2, R3).
353    pub params: &'a BTreeMap<String, String>,
354    /// Whether the role is optional (core §3.1).
355    pub optional: bool,
356    /// How many desired resources of the author's declaration the
357    /// requirement names (text 0.6, F-218): one for a requirement §2.1
358    /// allows, one role per document type; two or more is
359    /// [`BindingProblem::TwoDocuments`].
360    pub documents: usize,
361}
362
363/// The desired resource a requirement binds (§2.3): its interface, kind
364/// token, template and target parameters.
365#[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/// Why a binding is invalid (§2.3), in the order checked.
374#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
375pub enum BindingProblem {
376    /// No binding, and the role is required.
377    RequiredUnbound,
378    /// The requirement names two or more desired resources of the author's
379    /// declaration (text 0.6, F-218): one role per document type (§2.1),
380    /// so there is no one slice to bind. Checked alone.
381    TwoDocuments,
382    /// More than one binding, or one with `*`, or one that is no address.
383    NotOneAuthor,
384    /// A target parameter `params` does not bind.
385    TargetUnbound,
386    /// A target parameter bound to anything but `self.system` or
387    /// `self.service`.
388    NotSelf,
389    /// Of two target parameters, one bound to the other's self.
390    WrongSelf,
391}
392
393impl BindingProblem {
394    /// The fixture's token.
395    #[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/// A requirement's binding (§2.3).
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum Binding {
411    /// No binding, an optional role: the kill switch (§2.12).
412    Unbound,
413    /// The problems, in the order checked.
414    Invalid(Vec<BindingProblem>),
415    /// The target's slice: its one document's key.
416    Bound { key: Key },
417}
418
419impl Binding {
420    /// The fixture's token.
421    #[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
431/// The one author a binding names: an exact address, or `None`.
432fn 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/// Reads a target's requirement on a desired resource (§2.3): the kill
443/// switch, a binding's problems, or the target's slice, built from the
444/// author's address and the target's own address `own`, each target
445/// parameter's value the target's system or service as its binding says,
446/// slugged (core §1.4). The problems in §2.3's order: `required_unbound`
447/// alone; `two_documents` alone (text 0.6); then `not_one_author`,
448/// `target_unbound`, `not_self` and `wrong_self`, each that applies.
449#[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    // One role per document type (§2.1; text 0.6, F-218): checked after
459    // the binding's absence, which reads nothing, and alone, since every
460    // check after it binds the one slice there is not.
461    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        // Every target parameter bound, every chunk a slug: only a template
505        // that is no desired one's reaches here.
506        None => Binding::Invalid(vec![BindingProblem::TargetUnbound]),
507    }
508}
509
510// --- §2.4: stamps ----------------------------------------------------------------
511
512/// Reads a stamp as a report writes it (§2.4): the NTP64 time in decimal,
513/// `0` or without a leading zero, at most 2^64−1; `/`; the id in lowercase
514/// hexadecimal without a leading zero, at most 32 digits. `None` for any
515/// other spelling. [`Stamp`]'s `Display` writes this form.
516#[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
526/// A stamp written as a string (§2.4).
527mod 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// --- §2.10: the report -----------------------------------------------------------
543
544/// What is in force (§2.10).
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
546#[serde(rename_all = "snake_case")]
547pub enum Source {
548    /// The target's own configuration, with no document.
549    Baseline,
550    /// A document the target acted on.
551    Desired,
552    /// A change the target's own operation made since.
553    Call,
554}
555
556impl Source {
557    /// The wire's and the fixture's token.
558    #[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/// What the last act did (§2.7, §2.8, §2.10).
575#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
576#[serde(rename_all = "snake_case")]
577pub enum Outcome {
578    /// Applied whole.
579    Converged,
580    /// Nothing applied; what was in force kept.
581    Refused,
582    /// Applied in part.
583    Failed,
584    /// A delete acted on, the baseline back in force.
585    Reverted,
586}
587
588impl Outcome {
589    /// The wire's and the fixture's token.
590    #[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/// One version of a document (§2.4): `desired.v1.Version`.
608#[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/// Why a document was refused, or failed to apply (§2.10):
617/// `desired.v1.Refusal`.
618#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
619pub struct Refusal {
620    /// The profile's code ([`UNDECODABLE`], [`REACH`], [`SENSITIVE`],
621    /// [`INVALID`], [`APPLY`]) or the type's own, 1 to 64 characters.
622    pub code: String,
623    /// Where in the document, a JSON Pointer (RFC 6901).
624    #[serde(default, skip_serializing_if = "Option::is_none")]
625    pub pointer: Option<String>,
626    /// A line for a person.
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub detail: Option<String>,
629}
630
631impl Refusal {
632    /// A refusal with a code alone.
633    #[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/// A target's report of one role (§2.10): `desired.v1.Report`. Its members
644/// serialize as the schema names them, an absent one left out.
645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646pub struct Report {
647    /// The slice's key, absent only for an unbound role (§2.12).
648    #[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    /// `true` when `observed` was read from an archive (§2.9).
660    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
661    pub last_known: bool,
662}
663
664/// Why a report does not read (§2.10): the first refusal only.
665#[derive(Debug, Clone, PartialEq, Eq)]
666pub enum Unreadable {
667    /// Bytes that are not strict JSON.
668    Json(String),
669    /// Outside `desired.v1.Report`.
670    Schema(String),
671    /// A stamp not in zenoh's form (§2.4).
672    Stamp(String),
673    /// A revision above 2^64−1.
674    RevisionRange(&'static str),
675}
676
677impl Unreadable {
678    /// The fixture's token.
679    #[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/// A report that reads, but breaks §2.10's consistency, of either major:
702/// [`Report::check`] gives `desired.v1`'s eight, [`v2::Fields::check`]
703/// `desired.v2`'s eight.
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
705pub enum Finding {
706    /// `desired.v2` alone: `source` or `outcome` is a later text's value.
707    Escape,
708    /// `desired.v2` alone: a version's fields do not hold together.
709    RunFields,
710    /// `desired.v1` alone: no key, and more than the baseline.
711    Keyless,
712    /// `desired.v1` alone: a key that is no state key.
713    KeyForm,
714    ObservedOutcome,
715    Refusal,
716    Source,
717    InForce,
718    RevisionOnRevert,
719    LastKnown,
720}
721
722impl Finding {
723    /// The fixture's token.
724    #[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
741/// A revision as the schema reads it: an integer from 0, an integral float
742/// that integer; whether it fits 64 bits is checked after the stamps.
743enum RevisionRead {
744    InRange(u64),
745    TooLarge,
746}
747
748/// A revision read from its number's exact value (text 0.3, F-181), as
749/// [`exact_number`] writes it: an integer from 0, whatever its spelling
750/// (`3`, `3.0`, `30e-1`, `18446744073709551615.0`), in range up to 2^64−1;
751/// `None` for a negative number or one with a fraction (`1.5`).
752fn 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    // The significant digits keep no trailing zero, so a negative exponent
762    // is a fraction.
763    if exp < 0 {
764        return None;
765    }
766    // A positive exponent is an integer, however large: past `usize` it is
767    // far past 2^64−1. (Such a number is never finite, so strict JSON
768    // refuses its text first, §2.10; this reads it as its text says.)
769    let Ok(zeros) = usize::try_from(exp) else {
770        return Some(RevisionRead::TooLarge);
771    };
772    // 2^64−1 has 20 digits.
773    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/// A document's own revision (§2.4): a top-level member `revision` of a
784/// JSON payload, an integer from 0 to 2^64−1 read by its exact value
785/// (F-181), as a report's is. `None` when the payload is not strict JSON
786/// (§2.10's reading), is not an object, has no such member, or holds one
787/// that is no such integer.
788#[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/// A document's own revision from its decoded value (§2.4): a top-level
804/// member `revision`, an integer from 0 to 2^64−1, an integral number read
805/// as that integer, or a decimal string, as protobuf's JSON mapping writes a
806/// 64-bit field. A JSON payload's is read from its text instead
807/// ([`revision_of_text`]), every number exact.
808#[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; // negative
830    }
831    let f = n.as_f64()?;
832    if !(f.is_finite() && f >= 0.0 && f.fract() == 0.0) {
833        return None;
834    }
835    // 2^64, exactly a double.
836    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
844/// A version's members, read by the schema's types.
845struct RawVersion<'a> {
846    stamp: &'a str,
847    revision: Option<RevisionRead>,
848}
849
850/// `exact` is the version's object as [`Exact`] read it from the report's
851/// text, when the reader had the text: its `revision` is then read by its
852/// exact value (text 0.3, F-181), never as a double.
853fn 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    /// A target's first report of a role (§2.10): its slice's key, or none
901    /// for an unbound role, and the baseline in force.
902    #[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    /// Reads a decoded payload (§2.10): the schema's members, types and
916    /// enums, an integral number read as an integer and a member the schema
917    /// does not name ignored; then each stamp's form; then each revision's
918    /// range. A decoded value holds a number with a fraction or an exponent
919    /// as its double, so a revision past 2^53 written so is read as that
920    /// double here; [`decode`] reads the text, every number by its exact
921    /// value (text 0.3, F-181).
922    ///
923    /// # Errors
924    ///
925    /// [`Unreadable`]: the first refusal, in that order.
926    pub fn from_json(v: &Value) -> Result<Self, Unreadable> {
927        Self::read(v, None)
928    }
929
930    /// [`Report::from_json`], each revision read from `exact`, the report's
931    /// text read with every number exact, when the reader has it
932    /// ([`decode`]; text 0.3, F-181).
933    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    /// The report's findings (§2.10), every one that applies, in the order
1025    /// checked. A report with one is malformed, and answers nothing
1026    /// (§2.17).
1027    #[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    /// The report as JSON, as a target puts it.
1077    #[must_use]
1078    pub fn to_json(&self) -> Value {
1079        serde_json::to_value(self).unwrap_or(Value::Null)
1080    }
1081}
1082
1083/// How deep a report or a document may nest (§2.10, text 0.2), counted as
1084/// `telemetry.v1` §2.6 counts it: an array or an object at the top is at
1085/// depth 1, one inside another one deeper, a scalar adding none.
1086pub const MAX_DEPTH: usize = crate::telemetry::decode::MAX_DEPTH;
1087
1088/// One JSON text as strict JSON (§2.10): UTF-8, RFC 8259's grammar,
1089/// nothing after the value but whitespace, no duplicate member at any
1090/// depth, every string with a UTF-8 form, every number finite by rounding,
1091/// and at most [`MAX_DEPTH`] arrays and objects deep (text 0.2), read by
1092/// `telemetry.v1`'s strict reader, which stops at the same place. `None`
1093/// when the bytes are not one. An integer within 64 bits is held exactly;
1094/// any other number as its nearest double.
1095#[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                // Beyond 64 bits, as `serde_json` reads one: its double.
1107                #[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            // JSON carries no byte string.
1119            D::Bytes(_) => return None,
1120        })
1121    }
1122    value(&crate::telemetry::decode::json(bytes)?)
1123}
1124
1125/// Reads a report's bytes (§2.10): strict JSON first, as `alarms.v1` §2.4
1126/// reads a document (UTF-8, RFC 8259, nothing after the value but
1127/// whitespace, no duplicate member at any depth, every number finite), at
1128/// most [`MAX_DEPTH`] deep, then [`Report::from_json`].
1129///
1130/// **Finite** is by rounding (text 0.2, F-167, as `telemetry.v1` §2.6
1131/// reads it): a number's text, an integer's included, is finite when its
1132/// exact value rounded to the nearest double is not an infinity, so 10^400
1133/// written out is not strict JSON, and `1.7976931348623158e308` is.
1134/// **Depth** (text 0.2): 256 nested arrays read, 257 do not; `serde_json`'s
1135/// own recursion limit decides nothing ([`strict_json`]). **Numbers**
1136/// (text 0.3, F-181) are read by their exact value, as §2.7 compares a
1137/// document's: a number with a zero fraction is that integer, so
1138/// `18446744073709551615.0` is the revision 2^64−1, and `1.5` is no
1139/// integer.
1140///
1141/// # Errors
1142///
1143/// [`Unreadable::Json`] for bytes that are not strict JSON, else
1144/// [`Report::from_json`]'s.
1145pub 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    // Every number by its exact value (text 0.3, F-181): a revision written
1152    // `18446744073709551615.0` is 2^64−1, in range.
1153    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// --- §2.6–§2.10: a target ------------------------------------------------------
1160
1161/// Which path a sample came by (§2.5, §2.9).
1162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1163pub enum Via {
1164    /// The author's own answer, or its put.
1165    Owner,
1166    /// An archive's last-known (core S5, S6).
1167    Archive,
1168}
1169
1170/// A sample's kind: a put, or a delete or a `reply_del`.
1171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1172pub enum Mutation {
1173    Put,
1174    Delete,
1175}
1176
1177/// A put's document, as a target compares two (§2.7): the SHA-256 of its
1178/// canonical form for a payload encoded as JSON that reads as strict JSON,
1179/// else of its bytes. Equal digests are the same document.
1180///
1181/// The canonical form is JCS's (RFC 8785), members in order and nothing
1182/// but the value, with one change (text 0.2, F-166): a number is written
1183/// by its exact value, never as the double RFC 8785 reads, so `10`, `10.0`
1184/// and `1e1` are one document and 2^53 and 2^53 + 1 are two. Its bytes are
1185/// strict JSON, a number spelled as [`exact_number`] writes it, so they are
1186/// their own canonical form, and never the bytes of a payload that does
1187/// not read.
1188#[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    /// A decoded JSON document, compared by its canonical form. A
1200    /// `serde_json` float is a double, so it compares as the double's
1201    /// shortest spelling; an integer within 64 bits is exact. A runtime
1202    /// compares a payload's bytes ([`Content::of_payload`]), whose every
1203    /// number is exact.
1204    #[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    /// A payload compared byte for byte: CBOR, protobuf, raw.
1212    #[must_use]
1213    pub fn of_bytes(bytes: &[u8]) -> Self {
1214        Self::digest(bytes)
1215    }
1216
1217    /// A payload as a target compares it (§2.7): one encoded as JSON
1218    /// (`json`) by its canonical form when it reads as strict JSON (§2.10's
1219    /// reading, [`strict_json`]: every number finite by rounding, at most
1220    /// [`MAX_DEPTH`] deep), and every other payload, or JSON that does not
1221    /// read, byte for byte.
1222    #[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/// A number's text (RFC 8259's grammar) as its exact value, canonical
1240/// (§2.7, text 0.2): `0`, or an optional `-`, the significant digits with
1241/// no leading and no trailing zero, `e`, and the exponent in decimal. So
1242/// `10`, `10.0`, `1e1` and `100e-1` are `1e1`; `-0` is `0`; 2^53 is
1243/// `9007199254740992e0` and 2^53 + 1 `9007199254740993e0`. `None` for text
1244/// outside the grammar, or an exponent whose text does not fit 128 bits,
1245/// which a comparison then reads byte for byte.
1246#[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
1291/// A JSON value as §2.7 compares it: members by name, every number by its
1292/// exact value.
1293enum 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                // Every spelling above is in RFC 8259's grammar.
1315                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    /// A text read as strict JSON (§2.10, [`strict_json`]), its numbers
1328    /// exact. `None` when it is not strict JSON, or a number's exponent does
1329    /// not fit (see [`exact_number`]). The strict read comes first, here,
1330    /// because [`ExactReader`] trusts what it accepted; this is the only
1331    /// way to it, and it is private to the module ([`Content::of_payload`]
1332    /// calls it).
1333    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                // JCS orders members by their names' UTF-16 code units.
1363                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
1385/// Reads a text [`strict_json`] already accepted, so that its numbers keep
1386/// their text: no duplicate, nothing after the value, and at most
1387/// [`MAX_DEPTH`] deep, which bounds its recursion.
1388///
1389/// **Precondition:** the text read as strict JSON. Only
1390/// [`Exact::of_strict_text`] builds one, after that read. The reader then
1391/// skips a string's escapes blindly (a `\` and the byte after it) and slices
1392/// the string's token by byte offsets, both right only for strict JSON;
1393/// every access is `get`, so text outside the precondition reads `None`,
1394/// never a panic.
1395struct 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/// One sample or reply of a target's slice, as its runtime received it
1505/// (§2.5).
1506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1507pub struct Sample {
1508    pub via: Via,
1509    pub mutation: Mutation,
1510    /// The author's stamp, `None` when the sample carries none.
1511    pub stamp: Option<Stamp>,
1512    /// The document type's own revision, when it carries one (§2.4). A
1513    /// delete has none.
1514    pub revision: Option<u64>,
1515    /// A put's document ([`Content`]); `None` for a delete, and for a put
1516    /// whose runtime did not compare it, which is then never the same
1517    /// document as another.
1518    pub content: Option<Content>,
1519}
1520
1521/// What an act does (§2.7, §2.8).
1522#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1523pub enum ActKind {
1524    /// Decode, check and apply the document.
1525    Apply,
1526    /// Apply the baseline.
1527    Revert,
1528}
1529
1530/// An act the target's runtime performs, then reports by
1531/// [`Target::finish`].
1532#[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    /// Whether `next` carries the same document as this act (§2.7): two
1562    /// puts whose documents compare equal, or two deletes.
1563    #[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    /// The act's version, as the report writes it.
1569    #[must_use]
1570    pub fn version(&self) -> Version {
1571        Version {
1572            stamp: self.stamp,
1573            revision: self.revision,
1574        }
1575    }
1576}
1577
1578/// How an act ended (§2.7, §2.10), with the refusal its major's report
1579/// carries: [`Refusal`] for `desired.v1`, [`v2::Refusal`] for `desired.v2`.
1580#[derive(Debug, Clone, PartialEq, Eq)]
1581pub enum Ended<R = Refusal> {
1582    /// Applied whole: a put converged, a delete reverted.
1583    Done,
1584    /// Refused whole, nothing applied. A revert is never refused: a
1585    /// refusal of one is read as [`Ended::Failed`].
1586    Refused(R),
1587    /// Applied in part.
1588    Failed(R),
1589}
1590
1591/// What a step of a target does (§2.6–§2.9).
1592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1593pub enum Step {
1594    /// Start this act now.
1595    Act(Act),
1596    /// Admitted, and the same document as the last version acted on or
1597    /// adopted: no act, and the report moved (§2.7).
1598    Adopted,
1599    /// Admitted while an act runs: held, replacing any version held before.
1600    Held,
1601    /// No stamp: never acted on (§2.6 step 1).
1602    Unstamped,
1603    /// The version held, received again (§2.6 step 3).
1604    SameVersion,
1605    /// An earlier time of the held version's id (§2.6 step 3).
1606    Older,
1607    /// The author's own sample of a version held from an archive (§2.9).
1608    /// When no act runs, the report changed: its `last_known` went.
1609    Confirmed,
1610    /// An act ended, and nothing is held.
1611    Done,
1612}
1613
1614impl Step {
1615    /// The fixture's token.
1616    #[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
1638/// How many ids a target remembers (§2.6, text 0.2, F-163): at least the
1639/// 16 most recent ids an instance acted on or adopted a version of. An id
1640/// forgotten beyond them is read as new. `desired.v2` remembers as many
1641/// runs ([`v2::REMEMBERED_RUNS`]).
1642pub const REMEMBERED_IDS: usize = 16;
1643
1644/// The state machine both majors share (v1 §2.6 to §2.10, which
1645/// `desired.v2` §2.6 to §2.10 restates over runs and seqs): one copy of
1646/// each rule that did not change. A major gives its [`machine::Mark`], the
1647/// place of a version in its author's order, and renders its own report
1648/// from the [`machine::Ledger`].
1649pub(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    /// A version's place in its author's order: an epoch nothing orders
1656    /// against another (v1: the stamp's id; v2: the run, with its width)
1657    /// and a tick within it (v1: the time; v2: the seq).
1658    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        /// A floor names no version (`desired.v2` §2.8's snapshot with no
1664        /// entry: its run and its asof): every version of its epoch at or
1665        /// below its tick is older, and it leaves no observed version.
1666        /// `desired.v1` has none.
1667        fn floor(&self) -> bool {
1668            false
1669        }
1670    }
1671
1672    /// An act, as the machine holds one: what a major's `Act` says, its
1673    /// stamp a [`Mark`].
1674    #[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    /// Whether two acts carry the same document (§2.7): two puts whose
1684    /// documents compare equal, or two that carry none.
1685    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    /// What a version received does (§2.6).
1697    #[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    /// What a floor received does (`desired.v2` §2.8).
1708    #[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    /// What follows an act's end (§2.7).
1717    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1718    pub(crate) enum Finished<M> {
1719        Done,
1720        Adopted,
1721        Act(Doing<M>),
1722    }
1723
1724    /// What a report says, whatever its major's record (§2.10): a version
1725    /// is its mark and its document's own revision.
1726    #[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        /// `None` until an act ends in this process.
1732        pub outcome: Option<Outcome>,
1733        pub refusal: Option<R>,
1734        pub last_known: bool,
1735    }
1736
1737    /// Why a version is not admitted over the one held.
1738    enum Not {
1739        Same,
1740        Older,
1741    }
1742
1743    /// Whether `incoming` is admitted over `held` (§2.6, core §4.3): by
1744    /// tick within one epoch, the first value under another epoch
1745    /// accepted. At or below a floor of its epoch, it is older.
1746    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    /// The author's own delivery of a version held from an archive
1758    /// confirms it (§2.9).
1759    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    /// One process of a target's role: the version it last acted on or
1768    /// adopted, the one it holds while an act runs, per epoch the highest
1769    /// tick it acted on or adopted, and what its report says.
1770    #[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        /// `(epoch, tick, floor)`, the epoch acted on or adopted most
1776        /// recently first, at most [`REMEMBERED_IDS`].
1777        remembered: Vec<(M::Epoch, M::Tick, bool)>,
1778        ledger: Ledger<M, R>,
1779    }
1780
1781    impl<M: Mark, R> Core<M, R> {
1782        /// At its start: nothing held, the baseline in force.
1783        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        /// The act that runs, if one does.
1805        pub fn running(&self) -> Option<&Doing<M>> {
1806            self.acted.as_ref().filter(|_| self.running)
1807        }
1808
1809        /// The latest it admitted (§2.5's held stamp): the one held
1810        /// waiting, else the running act's, else the last acted on or
1811        /// adopted.
1812        pub fn latest(&self) -> Option<&Doing<M>> {
1813            self.waiting.as_ref().or(self.acted.as_ref())
1814        }
1815
1816        /// The highest tick this process acted on or adopted under
1817        /// `epoch`, if it remembers the epoch (§2.6 step 4).
1818        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        /// Records a version acted on or adopted (§2.6 step 4). Called
1830        /// from `start`, as an act starts and as a version is adopted, so
1831        /// an adoption counts as an act does; a version held waiting
1832        /// counts only once its act starts or it is adopted, and one
1833        /// passed over never.
1834        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        /// Judges a version (§2.6): against the version last acted on or
1855        /// adopted (the running act's while one runs) and every epoch
1856        /// remembered, then, while an act runs, against the one held
1857        /// waiting (§2.7): an act to start, adopted, held while one runs,
1858        /// or ignored with why.
1859        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                    // Another epoch than the held one, acted on or adopted
1877                    // before in this process: never an older version of
1878                    // it, nor one acted on again. A version is its stamp
1879                    // (§2.4), so an equal one is the same version
1880                    // whatever document it carries.
1881                    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        /// Judges a floor (`desired.v2` §2.8): it reverts only a put's
1907        /// version of its own epoch at or below its tick, judged of the
1908        /// version last acted on or adopted, then of the one held waiting.
1909        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                // A floor follows a put, never the same document.
1942                Finished::Adopted | Finished::Done => Floored::NoVerdict,
1943            }
1944        }
1945
1946        /// The author's own word of `mark`, by an unchanged answer to a
1947        /// conditional read (`desired.v2` §2.5, §2.9): it confirms that
1948        /// version where the target holds it from an archive, acted on,
1949        /// running or waiting, and is no version received: nothing is
1950        /// judged, admitted or remembered. `true` when it confirmed one.
1951        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        /// Ends the running act (§2.7, §2.10): the ledger updated, then
1986        /// the held version, if one is held, adopted or its act started.
1987        /// With no act running, nothing changes.
1988        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                // A revert on a floor has no observed version
2000                // (`desired.v2` §2.8). One that could not finish keeps
2001                // the version it was reverting: a failed act with none
2002                // stated would be malformed (§2.10).
2003                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        /// The target's own operation changed what is in force (§2.7):
2039        /// `source` is `call`, and no version is wholly in force. The
2040        /// last act's report stands, and no version is acted on again.
2041        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/// One instance of a target's role (§2.6–§2.10): the version it last acted
2072/// on or adopted, the one it holds while an act runs, per id the latest
2073/// time it acted on or adopted (F-163), and its report. A restart is a new
2074/// `Target`, holding nothing (§2.7). Its rules are `machine::Core`'s,
2075/// which `desired.v2`'s target shares ([`v2::Target`]).
2076#[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    /// A role bound to the slice `key`, or unbound (`None`, §2.12), at its
2086    /// start: nothing held, its report the baseline's.
2087    #[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    /// The report, as the target puts it (§2.10).
2098    #[must_use]
2099    pub fn report(&self) -> &Report {
2100        &self.report
2101    }
2102
2103    /// The act that runs, if one does.
2104    #[must_use]
2105    pub fn running(&self) -> Option<&Act> {
2106        self.running.as_ref()
2107    }
2108
2109    /// The latest time this instance acted on or adopted a version of `id`
2110    /// at, if it remembers the id (§2.6 step 4).
2111    #[must_use]
2112    pub fn remembered(&self, id: u128) -> Option<u64> {
2113        self.core.remembered(id)
2114    }
2115
2116    /// The machine's ledger written as `desired.v1.Report`, and the
2117    /// running act as the runtime reads it.
2118    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    /// Judges a sample (§2.6): against the version last acted on or adopted
2134    /// (the running act's while one runs) and every id remembered, then,
2135    /// while an act runs, against the version held waiting (§2.7, text
2136    /// 0.2, F-162): an act to start, adopted, held while one runs, or
2137    /// ignored with why. After [`Step::Adopted`] the report changed.
2138    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    /// Ends the running act (§2.7, §2.10): the report updated, then the
2162    /// held version, if one is held, adopted or its act started, else
2163    /// [`Step::Done`]. With no act running, nothing changes, and it is
2164    /// [`Step::Done`].
2165    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    /// The target's own operation changed what is in force (§2.7): the
2176    /// report's `source` is `call`, and no version is wholly in force. The
2177    /// last act's report stands, and no version is acted on again.
2178    pub fn call(&mut self) {
2179        self.core.call();
2180        self.sync();
2181    }
2182}
2183
2184// --- §2.17, §5: what a tool may conclude ---------------------------------------
2185
2186/// A participant's presence, as the tool saw it (core §8.1, §8.5).
2187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2188pub enum Seen {
2189    /// Its instance token was seen.
2190    Present,
2191    /// A complete read held no instance token of it: absence (core §8.1,
2192    /// 0.37), never a withdrawal heard live (text 0.3, F-187).
2193    Absent,
2194    /// Not seen, in a read possibly incomplete or refused, or a read not
2195    /// made through a session cut off (core §8.1, 0.37).
2196    Incomplete,
2197    /// Across a constrained face, where presence does not cross and the
2198    /// deployment's word stands for the descriptor (§2.17, text 0.2,
2199    /// F-168).
2200    AcrossFace,
2201}
2202
2203/// What the target's descriptor says of the role (core §3.3).
2204#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2205pub enum Listing {
2206    /// Its `requires` do not list the role.
2207    NotListed,
2208    /// They list it, bound (`bound`) or with `"bindings": []`.
2209    Listed { bound: bool },
2210}
2211
2212/// What §2.17's step 5 reads of a report, of either major.
2213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2214pub struct Facts {
2215    pub source: Source,
2216    /// The last act's outcome, `None` with no act yet in this process: a
2217    /// `desired.v1` report with no `outcome`, a `desired.v2` one that says
2218    /// `not_acted`.
2219    pub outcome: Option<Outcome>,
2220    pub last_known: bool,
2221    /// Whether a version is wholly in force: v1's `in_force`, v2's
2222    /// `in_force` `observed` or `other`.
2223    pub in_force: bool,
2224}
2225
2226/// A report of either major, as §5's judges read one: [`Report`]
2227/// (`desired.v1`) or [`v2::Read`] (`desired.v2`).
2228pub trait Reported {
2229    /// What step 5 reads, or `None` for a malformed report (§2.10's
2230    /// consistency), which answers nothing.
2231    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/// The target's report of the role's slice, as the tool read it (§2.10):
2246/// `R` is the major's report as read, [`Report`] or [`v2::Read`].
2247#[derive(Debug)]
2248pub enum ReportRead<'a, R = Report> {
2249    /// None read.
2250    NotRead,
2251    /// Bytes that do not read ([`decode`] or [`v2::read`] refused them).
2252    Unreadable,
2253    /// A report that reads; malformed when it has a finding
2254    /// ([`Reported::facts`]).
2255    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/// What the tool read of the target (§2.17 steps 1 to 4).
2267#[derive(Debug)]
2268pub struct TargetReading<'a, R = Report> {
2269    pub presence: Seen,
2270    /// Its descriptor, `None` when not read. Ignored across a face.
2271    pub descriptor: Option<Listing>,
2272    /// Across a face, the deployment's word for what the descriptor would
2273    /// say, `None` when the tool has none (§2.17 step 2, text 0.2, F-168).
2274    /// Ignored elsewhere.
2275    pub deployment: Option<Listing>,
2276    pub report: ReportRead<'a, R>,
2277    /// The report's freshness by the `freshness` major its contract uses,
2278    /// [`freshness::Verdict::NotAsked`] when its resource declares no
2279    /// horizon.
2280    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/// The author's latest version of the slice, by S4's GET (§2.17 step 6).
2292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2293pub enum Current {
2294    /// No GET made.
2295    NotRead,
2296    /// A GET that ended at its timeout or with an error reply.
2297    Incomplete,
2298    /// A GET that drew nothing for the key.
2299    Silent,
2300    /// Its latest put.
2301    Put(Stamp),
2302    /// Its latest delete, or `reply_del`.
2303    Delete(Stamp),
2304}
2305
2306/// What the tool read of the author (§2.17 step 6).
2307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2308pub struct AuthorReading {
2309    pub presence: Seen,
2310    pub current: Current,
2311}
2312
2313/// A question of §5, answered in its states: the two poles, not yet, and
2314/// the two unestablished kinds apart (core O5).
2315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2316pub enum Answer {
2317    Yes,
2318    No,
2319    /// The target has not acted on the author's current version yet.
2320    NotYet,
2321    /// The question was put, and the reading could not answer it.
2322    Unobservable,
2323    /// Nobody put the question, or its premise does not hold.
2324    NotAsked,
2325}
2326
2327impl Answer {
2328    /// The fixture's token.
2329    #[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/// Why an answer is what it is: the fixture's reason (§2.17).
2348#[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    /// The fixture's token.
2383    #[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/// An answer and its reason.
2426#[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
2438/// §2.17 steps 1 to 4, shared by every question and by both majors: the
2439/// report to answer from with what step 5 reads of it, or the answer.
2440/// `unbound` is the answer for an unbound role. Across a face, the
2441/// deployment's word answers step 2 in the descriptor's place (text 0.2,
2442/// F-168).
2443fn 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
2488/// §5's first question up to step 6's read, for either major: the
2489/// premises, then the author's presence.
2490fn 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
2505/// Step 7, of either major: the report's observed version against the
2506/// author's. The same version answers by the last act's outcome; within
2507/// one epoch (v1: an id; v2: a run) a lower tick is behind and a higher
2508/// one ahead; another epoch is `other_epoch`.
2509fn 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/// §5's second question, "is the target's last act refused or failed?"
2538/// (§2.17), of a report of either major. Yes is the finding.
2539#[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/// §5's third question, "is what the target acted on last-known?" (§2.9,
2555/// §2.17), of a report of either major. Informative. Not asked with no act
2556/// yet: a consistent `desired.v1` report has an `observed` exactly when it
2557/// has an `outcome`, and a `desired.v2` one that reverted on a snapshot
2558/// with no entry has an outcome and no observed version.
2559#[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/// §5's fourth question, "is a desired document in force?" (§2.10,
2573/// §2.12, §2.17), of a report of either major. An unbound role answers no:
2574/// the kill switch. Informative.
2575#[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/// §5's first question, "has the target converged on its author's current
2590/// document?" (§2.17): the premises, then the author, then the comparison
2591/// of the report's `observed` with the author's version by value. No is the
2592/// finding.
2593#[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, &current, 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            // The same document again, under a later stamp, while the act runs.
2709            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        // Not strict JSON: byte for byte.
2781        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        // One value: a large integral float and its integer's text.
2807        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        // Two values: the text's exact value, never its double's.
2825        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        // An adoption counts as an act does.
2850        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        // Depth (0.2): the report's object at depth 1, then arrays.
2871        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        // A document past the depth compares byte for byte; one at it, by
2888        // its canonical form.
2889        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    /// Text 0.3, F-181: a revision reads by its exact value, in a report's
2906    /// text and in a document's.
2907    #[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        // A decoded value holds the double: 2^64 exactly.
2936        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        // The second id is the sixteenth most recent: still remembered.
2993        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        // The first is the seventeenth: forgotten, so new.
2997        assert_eq!(t.remembered(1), None);
2998        assert!(matches!(t.observe(put(400, "1")), Step::Act(_)));
2999    }
3000}