Skip to main content

zenkey_model/config/
v2.rs

1//! `config.v2`: a configuration declared in its contract, read back in one
2//! packed record (`spec/profiles/config/v2.md`, text 0.1, #985 G1).
3//!
4//! The profile's session-free half. `config.v2` keeps every rule of
5//! `config.v1` and replaces its wire, so this module reads the declaration,
6//! derives the types, writes and reads the record and the requests, and
7//! runs [`super`]'s validators and [`super::Owner`] unchanged under them:
8//!
9//! ```text
10//! Groups::read(annotation, packed files) ─▶ Groups │ [Invalid{entry, reason}]       §2.2
11//! Derived::of(&Groups)                   ─▶ Record, Set<T> per settable group, Control, Error   §3
12//! Interface::of(&Contract)               ─▶ the groups and their derived types
13//! lint(&Resources), lint_contract(c)     ─▶ [Finding{at, reason}], in §2.2's order
14//! Interface::write_record / read_record  ─▶ the record's bytes │ State │ RecordRefusal   §2.3
15//! Interface::decode_set / decode_control ─▶ the request, a query's payload (core §7.5)
16//! validate_set / validate_control        ─▶ () │ Refusal, config.v1's rows over the record's facts §2.5
17//! check_desired                          ─▶ () │ DesiredRefused, by declared names        §2.18
18//! deadline, apply_at                     ─▶ instants rounded up to the second           §2.8
19//! Owner (over config::Owner)             ─▶ puts, then the reply, then events, each stamped §2.3–§2.17
20//! ```
21//!
22//! A [`Mint`] stamps what the owner writes: the run it writes under, each
23//! seq, a new run when the seq or the token counter is spent (core §4.3),
24//! and each run's first token count. The runtime implements it over the
25//! service's own minter, since the seq is the instance's, shared by every
26//! state key and event it writes.
27
28use std::collections::{BTreeMap, BTreeSet};
29use std::fmt;
30use std::time::Duration;
31
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value as Json, json};
34
35use super::{
36    Act, Call, Class, Code, ConfigView, ControlOp, ControlRequest, DesiredConfig, DesiredOutcome,
37    DesiredReport, DeviceResult, Edit, Field, GroupDecl, Kind as V1Kind, Outcome, ParamDecl,
38    PersistPlan, REDACTED, Refusal, Schema, SetReply, SetRequest, Source, StartError, Time, Value,
39};
40use crate::authoring::{Fanout, Kind, Replies, Serving};
41use crate::contract::{self, Body as ContractBody, Contract, Rate};
42use crate::envelope::{Cause, Code as ErrorCode, ErrorForm};
43use crate::grammar::{IfaceId, KindToken};
44use crate::packed::{self, FieldKind, Item, Layout};
45use crate::schema::{Artifact, ArtifactData, SchemaKind, TypeId};
46use crate::wire::{self, Envelope, Request, Run, Seq, Stamp, Tag};
47
48/// The profile's id.
49pub const PROFILE: &str = "config.v2";
50/// The annotation that declares the groups (§4).
51pub const GROUPS: &str = "config.groups";
52/// The state that carries the record, `state/config` (§2.3).
53pub const CONFIG: &str = "config";
54/// The operations' templates beside `set/<group>` (§3).
55pub const CONTROLS: [&str; 4] = [super::CONFIRM, super::CANCEL, super::EXTEND, super::PERSIST];
56/// The change event's template (§2.17).
57pub const CHANGE: &str = "change";
58/// A marker of the declaration, and of `Record` (§2.2, §3).
59pub const MARKER: &str = packed::MARKER;
60/// The most groups a declaration holds, and the most parameters a group.
61pub const MAX_GROUPS: usize = 16;
62/// The most parameters a group type holds (§2.2).
63pub const MAX_PARAMETERS: usize = 16;
64/// The names a parameter may not take: the derived types use them (§2.2).
65pub const RESERVED_NAMES: [&str; 8] = [
66    "confirm_s",
67    "token",
68    "expected_revision",
69    "idempotency_key",
70    "dry_run",
71    "writable",
72    "pending",
73    "last",
74];
75/// The largest token, 48 bits (§2.6).
76pub const TOKEN_MAX: u64 = (1 << 48) - 1;
77/// The largest token count within one run (§2.6).
78pub const COUNTER_MAX: u32 = 65_535;
79/// The standard schema's first revision, by artifact id (§3).
80pub const STANDARD_SCHEMA: &str =
81    "sha256:0dadb0afae6b405abf958f23a2ff8d61063580028afb6980fdfc208d53a730f1";
82/// The change event's type in the standard schema (§2.17).
83pub const EVENT_TYPE: &str = "ConfigChangeEvent";
84/// The change event's rate and retention (§3).
85pub const EVENT_RATE: Rate = Rate::Burst(600);
86/// Seven days, in seconds.
87pub const EVENT_RETENTION_S: u64 = 7 * 86_400;
88/// The derived types' names beside `Set<T>`.
89pub const RECORD: &str = "Record";
90/// `Control`, the control operations' request.
91pub const CONTROL: &str = "Control";
92/// `Error`, every operation's `app` detail.
93pub const ERROR: &str = "Error";
94/// `Error`'s one code at this version (§2.5).
95pub const DEVICE_REFUSED: &str = "device_refused";
96/// The sources a parameter's `__source` field names, in code order (§4).
97pub const SOURCES: [&str; 4] = ["default", "file", "overlay", "runtime"];
98/// The desired outcomes, in code order (§4).
99pub const OUTCOMES: [&str; 3] = ["converged", "refused", "failed"];
100/// The desired refusal codes, in code order (§4).
101pub const DESIRED_CODES: [&str; 8] = [
102    "reach",
103    "contract",
104    "sensitive",
105    "not_found",
106    "invalid_request",
107    "unavailable",
108    "busy",
109    "device_refused",
110];
111
112/// Whether `s` is a group's or a parameter's name:
113/// `[a-z][a-z0-9]*(_[a-z0-9]+)*` (§2.2).
114#[must_use]
115pub fn is_name(s: &str) -> bool {
116    let b = s.as_bytes();
117    if !b.first().is_some_and(u8::is_ascii_lowercase) {
118        return false;
119    }
120    let mut underscore = false;
121    for &c in &b[1..] {
122        if c == b'_' {
123            if underscore {
124                return false;
125            }
126            underscore = true;
127        } else if c.is_ascii_lowercase() || c.is_ascii_digit() {
128            underscore = false;
129        } else {
130            return false;
131        }
132    }
133    !underscore
134}
135
136// --- the declaration (§2.2) -----------------------------------------------------
137
138/// Why a declaration is invalid (§2.2): the annotation whole, then each
139/// item's checks in this order.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
141pub enum Reason {
142    /// Not an array, no group, more than 16, or a marker first, last or
143    /// after a marker.
144    GroupsValue,
145    /// An item that is neither a table nor a marker, or a table holding a
146    /// member outside the five.
147    GroupValue,
148    /// `name` missing, not of the form, or an earlier group's.
149    GroupName,
150    /// `class` not `hot`, `reach` or `contract`.
151    GroupClass,
152    /// `type` not a packed type a group may name, or an earlier group's.
153    GroupType,
154    /// `units` not a table of `int` parameters' non-empty units.
155    GroupUnits,
156    /// `sensitive` not an array of parameter names, each once.
157    GroupSensitive,
158}
159
160impl Reason {
161    /// The fixtures' token.
162    #[must_use]
163    pub fn token(self) -> &'static str {
164        match self {
165            Self::GroupsValue => "groups_value",
166            Self::GroupValue => "group_value",
167            Self::GroupName => "group_name",
168            Self::GroupClass => "group_class",
169            Self::GroupType => "group_type",
170            Self::GroupUnits => "group_units",
171            Self::GroupSensitive => "group_sensitive",
172        }
173    }
174}
175
176/// One reason a declaration is invalid, at its item's index in the array
177/// (markers counted), or `None` for the annotation whole.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub struct Invalid {
180    pub entry: Option<usize>,
181    pub reason: Reason,
182}
183
184/// A parameter's kind at this version (§2.2): config.v1's `integer` with
185/// its bounds, or `bool`.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
187pub enum ParamKind {
188    Int { minimum: i64, maximum: i64 },
189    Bool,
190}
191
192/// One parameter: a field of its group's type.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct Parameter {
195    pub name: String,
196    pub kind: ParamKind,
197    /// Its width in bits (core §7.6).
198    pub width: u32,
199    /// Its unit, from the entry's `units`.
200    pub unit: Option<String>,
201    /// Write-only (§2.15).
202    pub sensitive: bool,
203    /// Its field's `description`, for a person.
204    pub description: Option<String>,
205}
206
207impl Parameter {
208    /// Its field in a derived type, optional or not.
209    fn field(&self, name: String, optional: bool) -> FieldDecl {
210        match self.kind {
211            ParamKind::Int { minimum, maximum } => FieldDecl::int(name, minimum, maximum, optional),
212            ParamKind::Bool => FieldDecl::boolean(name, optional),
213        }
214    }
215
216    /// Reads a JSON value as this parameter's: `true` or `false` for a
217    /// `bool`, an integer within the bounds for an `int`.
218    fn value_of(&self, v: &Json) -> Option<Value> {
219        match self.kind {
220            ParamKind::Bool => v.as_bool().map(Value::Bool),
221            ParamKind::Int { minimum, maximum } => v
222                .as_i64()
223                .filter(|i| (minimum..=maximum).contains(i))
224                .map(Value::Integer),
225        }
226    }
227}
228
229/// One group, as its entry and its type declare it.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Group {
232    pub name: String,
233    pub class: Class,
234    /// Its type's name in its packed file, without a stem.
235    pub type_name: String,
236    /// Its type's `description`, for a person.
237    pub description: Option<String>,
238    /// In its type's field order.
239    pub parameters: Vec<Parameter>,
240    /// Whether a marker comes before it: a later revision's group, every
241    /// field of which is optional in `Record` (§3).
242    pub appended: bool,
243}
244
245impl Group {
246    /// A `hot` or `reach` group, which has a `set` (§0).
247    #[must_use]
248    pub fn settable(&self) -> bool {
249        matches!(self.class, Class::Hot | Class::Reach)
250    }
251
252    /// The parameter by name, with its index in the group.
253    #[must_use]
254    pub fn parameter(&self, name: &str) -> Option<(usize, &Parameter)> {
255        self.parameters
256            .iter()
257            .enumerate()
258            .find(|(_, p)| p.name == name)
259    }
260
261    /// Its `set`'s request type's name, `Set<T>`.
262    #[must_use]
263    pub fn set_type(&self) -> String {
264        format!("Set{}", self.type_name)
265    }
266}
267
268/// An item of the declaration.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub enum Entry {
271    Group(Group),
272    /// `"..."`: the groups after it are a later revision's.
273    Marker,
274}
275
276/// A declaration read: its groups and markers, in the owner's order.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct Groups {
279    pub entries: Vec<Entry>,
280}
281
282/// A packed reference resolved: its file's stem, the type's name, and its
283/// declaration.
284struct Resolved<'a> {
285    stem: &'a str,
286    name: &'a str,
287    decl: &'a Json,
288    doc: &'a Json,
289}
290
291/// Resolves `packed:<Name>` or `packed:<stem>#<Name>` among the listed
292/// packed files, `(stem, document)`, as core §9.4 does: one file of that
293/// stem, or the one file that defines the name.
294fn resolve<'a>(reference: &'a str, files: &[(&'a str, &'a Json)]) -> Option<Resolved<'a>> {
295    let rest = reference.strip_prefix("packed:")?;
296    let (stem, name) = match rest.split_once('#') {
297        Some((s, n)) => (Some(s), n),
298        None => (None, rest),
299    };
300    let found: Vec<Resolved<'a>> = files
301        .iter()
302        .filter(|(s, _)| stem.is_none_or(|x| x == *s))
303        .filter_map(|(s, doc)| {
304            doc.get("types")?.get(name).map(|decl| Resolved {
305                stem: s,
306                name,
307                decl,
308                doc,
309            })
310        })
311        .collect();
312    match <[_; 1]>::try_from(found) {
313        Ok([r]) => Some(r),
314        Err(_) => None,
315    }
316}
317
318/// A group type's parameters, or `None` when the type is not one a group
319/// may name (§2.2): it must read as a packed type, and hold int and bool
320/// fields alone, at most 16, none optional, none with `reserved`, each
321/// named in a group name's form and none of [`RESERVED_NAMES`].
322fn group_type(r: &Resolved<'_>) -> Option<Vec<Parameter>> {
323    let fields = r.decl.get("fields")?.as_array()?;
324    if fields.len() > MAX_PARAMETERS {
325        return None;
326    }
327    for f in fields {
328        let f = f.as_object()?;
329        let name = f.get("name")?.as_str()?;
330        if f.get("optional").and_then(Json::as_bool) == Some(true)
331            || f.contains_key("reserved")
332            || !matches!(f.get("type").and_then(Json::as_str), Some("int" | "bool"))
333            || !is_name(name)
334            || RESERVED_NAMES.contains(&name)
335        {
336            return None;
337        }
338    }
339    let layout = packed::layout_in(r.doc, r.name).ok()?;
340    layout
341        .items
342        .iter()
343        .zip(fields)
344        .map(|(it, raw)| {
345            let Item::Field(f) = it else {
346                return None;
347            };
348            let kind = match f.kind {
349                FieldKind::Int {
350                    minimum, maximum, ..
351                } => ParamKind::Int { minimum, maximum },
352                FieldKind::Bool => ParamKind::Bool,
353                _ => return None,
354            };
355            Some(Parameter {
356                name: f.name.clone(),
357                kind,
358                width: f.width,
359                unit: None,
360                sensitive: false,
361                description: raw
362                    .get("description")
363                    .and_then(Json::as_str)
364                    .map(str::to_owned),
365            })
366        })
367        .collect()
368}
369
370const ENTRY_MEMBERS: [&str; 5] = ["name", "class", "type", "units", "sensitive"];
371
372impl Groups {
373    /// Reads `config.groups`, the annotation's value as TOML reads it into
374    /// JSON, against the contract's packed files, each `(stem, document)`
375    /// (§2.2): the groups, or every reason it is invalid, in the text's
376    /// order.
377    ///
378    /// # Errors
379    ///
380    /// The reasons, the annotation whole's alone when it is wrong.
381    pub fn read(annotation: &Json, files: &[(&str, &Json)]) -> Result<Self, Vec<Invalid>> {
382        let whole = || {
383            vec![Invalid {
384                entry: None,
385                reason: Reason::GroupsValue,
386            }]
387        };
388        let Some(items) = annotation.as_array() else {
389            return Err(whole());
390        };
391        let is_marker = |v: &Json| v.as_str() == Some(MARKER);
392        let groups = items.iter().filter(|v| !is_marker(v)).count();
393        let misplaced = items.first().is_some_and(is_marker)
394            || items.last().is_some_and(is_marker)
395            || items
396                .windows(2)
397                .any(|w| is_marker(&w[0]) && is_marker(&w[1]));
398        if groups == 0 || groups > MAX_GROUPS || misplaced {
399            return Err(whole());
400        }
401        let mut reasons = Vec::new();
402        let mut entries = Vec::new();
403        let mut names: Vec<&str> = Vec::new();
404        let mut types: Vec<(&str, &str)> = Vec::new();
405        let mut appended = false;
406        for (i, item) in items.iter().enumerate() {
407            let mut fail = |reason| {
408                reasons.push(Invalid {
409                    entry: Some(i),
410                    reason,
411                });
412            };
413            if is_marker(item) {
414                appended = true;
415                entries.push(Entry::Marker);
416                continue;
417            }
418            let Some(m) = item.as_object() else {
419                fail(Reason::GroupValue);
420                continue;
421            };
422            if m.keys().any(|k| !ENTRY_MEMBERS.contains(&k.as_str())) {
423                fail(Reason::GroupValue);
424            }
425            let name = m.get("name").and_then(Json::as_str);
426            let name_ok = name.is_some_and(|n| is_name(n) && !names.contains(&n));
427            if !name_ok {
428                fail(Reason::GroupName);
429            }
430            if let Some(n) = name {
431                names.push(n);
432            }
433            let class = match m.get("class").and_then(Json::as_str) {
434                Some("hot") => Some(Class::Hot),
435                Some("reach") => Some(Class::Reach),
436                Some("contract") => Some(Class::Contract),
437                _ => None,
438            };
439            if class.is_none() {
440                fail(Reason::GroupClass);
441            }
442            let resolved = m
443                .get("type")
444                .and_then(Json::as_str)
445                .and_then(|t| resolve(t, files));
446            let earlier = resolved
447                .as_ref()
448                .is_some_and(|r| types.contains(&(r.stem, r.name)));
449            let mut params = resolved.as_ref().filter(|_| !earlier).and_then(group_type);
450            if let Some(r) = &resolved {
451                types.push((r.stem, r.name));
452            }
453            if params.is_none() {
454                fail(Reason::GroupType);
455            }
456            if let Some(units) = m.get("units") {
457                let ok = match (units.as_object(), &params) {
458                    (None, _) => false,
459                    (Some(_), None) => true,
460                    (Some(u), Some(ps)) => u.iter().all(|(k, v)| {
461                        ps.iter()
462                            .any(|p| p.name == *k && matches!(p.kind, ParamKind::Int { .. }))
463                            && v.as_str().is_some_and(|s| !s.is_empty())
464                    }),
465                };
466                if ok {
467                    if let (Some(u), Some(ps)) = (units.as_object(), params.as_mut()) {
468                        for p in ps.iter_mut() {
469                            p.unit = u.get(&p.name).and_then(Json::as_str).map(str::to_owned);
470                        }
471                    }
472                } else {
473                    fail(Reason::GroupUnits);
474                }
475            }
476            if let Some(sensitive) = m.get("sensitive") {
477                let ok = match (sensitive.as_array(), &params) {
478                    (None, _) => false,
479                    (Some(_), None) => true,
480                    (Some(s), Some(ps)) => {
481                        let mut seen = BTreeSet::new();
482                        s.iter().all(|v| {
483                            v.as_str().is_some_and(|n| {
484                                ps.iter().any(|p| p.name == n) && seen.insert(n.to_owned())
485                            })
486                        })
487                    }
488                };
489                if ok {
490                    if let (Some(s), Some(ps)) = (sensitive.as_array(), params.as_mut()) {
491                        for p in ps.iter_mut() {
492                            p.sensitive = s.iter().any(|v| v.as_str() == Some(p.name.as_str()));
493                        }
494                    }
495                } else {
496                    fail(Reason::GroupSensitive);
497                }
498            }
499            if let (Some(n), Some(c), Some(ps), Some(r)) = (name, class, params, &resolved) {
500                entries.push(Entry::Group(Group {
501                    name: n.to_owned(),
502                    class: c,
503                    type_name: r.name.to_owned(),
504                    description: r
505                        .decl
506                        .get("description")
507                        .and_then(Json::as_str)
508                        .map(str::to_owned),
509                    parameters: ps,
510                    appended,
511                }));
512            }
513        }
514        if reasons.is_empty() {
515            Ok(Self { entries })
516        } else {
517            Err(reasons)
518        }
519    }
520
521    /// The groups, markers left out, in the declaration's order: a
522    /// group's index here is the one the record's desired report names.
523    pub fn iter(&self) -> impl Iterator<Item = &Group> {
524        self.entries.iter().filter_map(|e| match e {
525            Entry::Group(g) => Some(g),
526            Entry::Marker => None,
527        })
528    }
529
530    /// The group by name, with its index.
531    #[must_use]
532    pub fn group(&self, name: &str) -> Option<(usize, &Group)> {
533        self.iter().enumerate().find(|(_, g)| g.name == name)
534    }
535
536    /// The settable group by name: the one `set/<name>` reaches.
537    #[must_use]
538    pub fn settable(&self, name: &str) -> Option<&Group> {
539        self.group(name).map(|(_, g)| g).filter(|g| g.settable())
540    }
541
542    /// config.v1's schema of these groups, each `writable` where the
543    /// startup allowlist holds its name: what `config.v1`'s validators and
544    /// [`super::Owner`] run under, unchanged.
545    #[must_use]
546    pub fn schema(&self, writable: &BTreeSet<String>) -> Schema {
547        Schema {
548            groups: self
549                .iter()
550                .map(|g| GroupDecl {
551                    name: g.name.clone(),
552                    class: g.class,
553                    description: g.description.clone().unwrap_or_default(),
554                    writable: g.settable() && writable.contains(&g.name),
555                    parameters: g
556                        .parameters
557                        .iter()
558                        .map(|p| ParamDecl {
559                            name: p.name.clone(),
560                            kind: match p.kind {
561                                ParamKind::Int { minimum, maximum } => V1Kind::Integer {
562                                    min: Some(minimum),
563                                    max: Some(maximum),
564                                    unit: p.unit.clone(),
565                                },
566                                ParamKind::Bool => V1Kind::Bool,
567                            },
568                            description: p.description.clone().unwrap_or_default(),
569                            sensitive: p.sensitive,
570                        })
571                        .collect(),
572                })
573                .collect(),
574        }
575    }
576
577    /// The declaration as `derive.json` spells its groups: each group's
578    /// name, class, type, whether settable, and its parameters; a marker
579    /// where it stands.
580    #[must_use]
581    pub fn to_json(&self) -> Json {
582        Json::Array(
583            self.entries
584                .iter()
585                .map(|e| match e {
586                    Entry::Marker => json!(MARKER),
587                    Entry::Group(g) => json!({
588                        "name": g.name,
589                        "class": g.class.as_str(),
590                        "type": g.type_name,
591                        "settable": g.settable(),
592                        "parameters": g.parameters.iter().map(|p| {
593                            let (kind, minimum, maximum) = match p.kind {
594                                ParamKind::Int { minimum, maximum } => ("int", json!(minimum), json!(maximum)),
595                                ParamKind::Bool => ("bool", Json::Null, Json::Null),
596                            };
597                            json!({
598                                "name": p.name,
599                                "kind": kind,
600                                "minimum": minimum,
601                                "maximum": maximum,
602                                "width": p.width,
603                                "unit": p.unit,
604                                "sensitive": p.sensitive,
605                            })
606                        }).collect::<Vec<_>>(),
607                    }),
608                })
609                .collect(),
610        )
611    }
612}
613
614// --- the derived types (§3) -------------------------------------------------------
615
616/// One field of a derived type, as `zk2 config derive` writes it: its
617/// members in this order, and no description.
618#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
619struct FieldDecl {
620    name: String,
621    #[serde(rename = "type")]
622    ty: &'static str,
623    #[serde(skip_serializing_if = "Option::is_none")]
624    minimum: Option<i64>,
625    #[serde(skip_serializing_if = "Option::is_none")]
626    maximum: Option<i64>,
627    #[serde(skip_serializing_if = "Option::is_none")]
628    values: Option<Vec<&'static str>>,
629    #[serde(skip_serializing_if = "Option::is_none")]
630    escape: Option<bool>,
631    #[serde(skip_serializing_if = "Option::is_none")]
632    width: Option<u32>,
633    #[serde(skip_serializing_if = "Option::is_none")]
634    optional: Option<bool>,
635}
636
637impl FieldDecl {
638    fn new(name: String, ty: &'static str, optional: bool) -> Self {
639        Self {
640            name,
641            ty,
642            minimum: None,
643            maximum: None,
644            values: None,
645            escape: None,
646            width: None,
647            optional: optional.then_some(true),
648        }
649    }
650
651    fn int(name: impl Into<String>, minimum: i64, maximum: i64, optional: bool) -> Self {
652        Self {
653            minimum: Some(minimum),
654            maximum: Some(maximum),
655            ..Self::new(name.into(), "int", optional)
656        }
657    }
658
659    fn boolean(name: impl Into<String>, optional: bool) -> Self {
660        Self::new(name.into(), "bool", optional)
661    }
662
663    fn time(name: &str, optional: bool) -> Self {
664        Self::new(name.into(), "time", optional)
665    }
666
667    fn enumeration(
668        name: impl Into<String>,
669        values: &[&'static str],
670        escape: bool,
671        optional: bool,
672    ) -> Self {
673        Self {
674            values: Some(values.to_vec()),
675            escape: escape.then_some(true),
676            ..Self::new(name.into(), "enum", optional)
677        }
678    }
679}
680
681/// An item of a derived type's `fields`.
682#[derive(Debug, Clone, PartialEq, Eq)]
683enum FieldItem {
684    Field(FieldDecl),
685    Marker,
686}
687
688impl Serialize for FieldItem {
689    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
690        match self {
691            Self::Field(f) => f.serialize(s),
692            Self::Marker => s.serialize_str(MARKER),
693        }
694    }
695}
696
697/// A derived type's declaration: a description for a person, then its
698/// fields.
699#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
700struct TypeDecl {
701    description: String,
702    fields: Vec<FieldItem>,
703}
704
705/// The derived types of a declaration, each with its layout (§3): what
706/// `zk2 config derive` writes, and what the lint compares a contract's
707/// types with.
708#[derive(Debug, Clone)]
709pub struct Derived {
710    types: Vec<(String, TypeDecl)>,
711    layouts: BTreeMap<String, Layout>,
712    /// Each settable group's `Set<T>` type name, by group.
713    sets: BTreeMap<String, String>,
714}
715
716/// `Record`'s header (§3), in order.
717fn header() -> Vec<FieldItem> {
718    let u32_max = i64::from(u32::MAX);
719    let token_max = TOKEN_MAX as i64;
720    [
721        FieldDecl::int("instance", 0, u32_max, false),
722        FieldDecl::int("revision", 0, u32_max, false),
723        FieldDecl::int("floor_s", 1, i64::from(u16::MAX), false),
724        FieldDecl::boolean("would_be", false),
725        FieldDecl::int("pending_token", 0, token_max, true),
726        FieldDecl::time("pending_apply_at", true),
727        FieldDecl::time("pending_deadline", true),
728        FieldDecl::int("last_token", 0, token_max, true),
729        FieldDecl::enumeration("desired", &OUTCOMES, true, true),
730        FieldDecl::int("desired_revision", 0, u32_max, true),
731        FieldDecl::enumeration("desired_code", &DESIRED_CODES, true, true),
732        FieldDecl::int("desired_group", 0, 15, true),
733        FieldDecl::int("desired_parameter", 0, 15, true),
734    ]
735    .into_iter()
736    .map(FieldItem::Field)
737    .collect()
738}
739
740/// A group's fields in `Record`: its three bits when settable, then each
741/// parameter's source, and, unless sensitive, its `differs` bit and value.
742fn group_fields(g: &Group) -> Vec<FieldItem> {
743    let opt = g.appended;
744    let mut out = Vec::new();
745    if g.settable() {
746        for bit in ["writable", "pending", "last"] {
747            out.push(FieldDecl::boolean(format!("{}__{bit}", g.name), opt));
748        }
749    }
750    for p in &g.parameters {
751        let at = format!("{}__{}", g.name, p.name);
752        out.push(FieldDecl::enumeration(
753            format!("{at}__source"),
754            &SOURCES,
755            false,
756            true,
757        ));
758        if !p.sensitive {
759            out.push(FieldDecl::boolean(format!("{at}__differs"), opt));
760            out.push(p.field(at, true));
761        }
762    }
763    out.into_iter().map(FieldItem::Field).collect()
764}
765
766fn layout_of(name: &str, decl: &TypeDecl) -> Layout {
767    let doc = json!({ "types": { name: decl } });
768    packed::layout_in(&doc, name).expect("a derived type reads as a packed type")
769}
770
771impl Derived {
772    /// The derivation (§3): `Record`, then `Set<T>` for each settable group
773    /// in the groups' order, then `Control` and `Error`.
774    #[must_use]
775    pub fn of(groups: &Groups) -> Self {
776        let mut record = header();
777        for e in &groups.entries {
778            match e {
779                Entry::Group(g) => record.extend(group_fields(g)),
780                Entry::Marker => record.push(FieldItem::Marker),
781            }
782        }
783        record.push(FieldItem::Marker);
784        let mut types = vec![(
785            RECORD.to_owned(),
786            TypeDecl {
787                description:
788                    "config.v2's record, derived (v2.md 2.3, 3): state/config, every reply"
789                        .to_owned(),
790                fields: record,
791            },
792        )];
793        let mut sets = BTreeMap::new();
794        for g in groups.iter().filter(|g| g.settable()) {
795            let mut fields: Vec<FieldItem> = g
796                .parameters
797                .iter()
798                .map(|p| FieldItem::Field(p.field(p.name.clone(), true)))
799                .collect();
800            fields.extend(
801                [
802                    FieldDecl::int("confirm_s", 1, i64::from(u16::MAX), true),
803                    FieldDecl::int("token", 0, TOKEN_MAX as i64, true),
804                    FieldDecl::int("expected_revision", 0, i64::from(u32::MAX), true),
805                    FieldDecl::int("idempotency_key", 0, i64::from(u32::MAX), true),
806                    FieldDecl::boolean("dry_run", false),
807                ]
808                .into_iter()
809                .map(FieldItem::Field),
810            );
811            let name = g.set_type();
812            sets.insert(g.name.clone(), name.clone());
813            types.push((
814                name,
815                TypeDecl {
816                    description: format!(
817                        "set/{}'s request, derived from {} (v2.md 2.5, 3)",
818                        g.name, g.type_name
819                    ),
820                    fields,
821                },
822            ));
823        }
824        types.push((
825            CONTROL.to_owned(),
826            TypeDecl {
827                description:
828                    "confirm, cancel, extend and persist's request, derived (v2.md 2.10, 3)"
829                        .to_owned(),
830                fields: vec![
831                    FieldItem::Field(FieldDecl::int("token", 0, TOKEN_MAX as i64, false)),
832                    FieldItem::Field(FieldDecl::int("confirm_s", 1, i64::from(u16::MAX), true)),
833                ],
834            },
835        ));
836        types.push((
837            ERROR.to_owned(),
838            TypeDecl {
839                description: "Every operation's error detail, derived (v2.md 2.5, 3)".to_owned(),
840                fields: vec![FieldItem::Field(FieldDecl {
841                    width: Some(4),
842                    ..FieldDecl::enumeration("code", &[DEVICE_REFUSED], true, false)
843                })],
844            },
845        ));
846        let layouts = types
847            .iter()
848            .map(|(n, d)| (n.clone(), layout_of(n, d)))
849            .collect();
850        Self {
851            types,
852            layouts,
853            sets,
854        }
855    }
856
857    /// The derived types' names, in derivation order.
858    pub fn names(&self) -> impl Iterator<Item = &str> {
859        self.types.iter().map(|(n, _)| n.as_str())
860    }
861
862    /// A derived type's declaration as JSON, its description included.
863    #[must_use]
864    pub fn declaration(&self, name: &str) -> Option<Json> {
865        self.types
866            .iter()
867            .find(|(n, _)| n == name)
868            .map(|(_, d)| serde_json::to_value(d).expect("a declaration is JSON"))
869    }
870
871    /// A derived type's layout.
872    #[must_use]
873    pub fn layout(&self, name: &str) -> Option<&Layout> {
874        self.layouts.get(name)
875    }
876
877    /// `Record`'s layout.
878    #[must_use]
879    pub fn record(&self) -> &Layout {
880        &self.layouts[RECORD]
881    }
882
883    /// `Control`'s layout.
884    #[must_use]
885    pub fn control(&self) -> &Layout {
886        &self.layouts[CONTROL]
887    }
888
889    /// `Error`'s layout.
890    #[must_use]
891    pub fn error(&self) -> &Layout {
892        &self.layouts[ERROR]
893    }
894
895    /// A settable group's `Set<T>`: its name and layout.
896    #[must_use]
897    pub fn set(&self, group: &str) -> Option<(&str, &Layout)> {
898        let name = self.sets.get(group)?;
899        Some((name, &self.layouts[name]))
900    }
901
902    /// The derived types as a packed file's text, `{"types": {...}}`, in
903    /// derivation order, each field's members in a fixed order and indented
904    /// by two spaces: what `zk2 config derive` prints.
905    #[must_use]
906    pub fn to_text(&self) -> String {
907        struct Types<'a>(&'a [(String, TypeDecl)]);
908        impl Serialize for Types<'_> {
909            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
910                use serde::ser::SerializeMap as _;
911                let mut m = s.serialize_map(Some(self.0.len()))?;
912                for (n, d) in self.0 {
913                    m.serialize_entry(n, d)?;
914                }
915                m.end()
916            }
917        }
918        #[derive(Serialize)]
919        struct Doc<'a> {
920            types: Types<'a>,
921        }
922        serde_json::to_string_pretty(&Doc {
923            types: Types(&self.types),
924        })
925        .expect("a declaration is JSON")
926            + "\n"
927    }
928}
929
930/// A config interface's declaration and derived types: everything a
931/// writer and a reader of its wire need from its contract.
932#[derive(Debug, Clone)]
933pub struct Interface {
934    pub groups: Groups,
935    pub derived: Derived,
936}
937
938/// Why a contract has no config interface to read.
939#[derive(Debug, Clone, PartialEq, Eq)]
940pub enum Unread {
941    /// No state `config` with `config.groups`.
942    Missing,
943    /// The declaration is invalid.
944    Invalid(Vec<Invalid>),
945}
946
947impl fmt::Display for Unread {
948    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949        match self {
950            Self::Missing => write!(f, "no state `{CONFIG}` declaring `{GROUPS}`"),
951            Self::Invalid(r) => {
952                write!(f, "`{GROUPS}` is invalid:")?;
953                for i in r {
954                    match i.entry {
955                        Some(e) => write!(f, " [{e}] {}", i.reason.token())?,
956                        None => write!(f, " {}", i.reason.token())?,
957                    }
958                }
959                Ok(())
960            }
961        }
962    }
963}
964
965impl std::error::Error for Unread {}
966
967/// A contract's packed files, `(stem, document)`.
968fn packed_files(c: &Contract) -> Vec<(&str, &Json)> {
969    packed_files_of(&c.artifacts)
970}
971
972/// The packed files among a contract's artifacts, `(stem, document)`.
973fn packed_files_of(artifacts: &BTreeMap<String, Artifact>) -> Vec<(&str, &Json)> {
974    artifacts
975        .values()
976        .filter(|a| a.kind == SchemaKind::Packed)
977        .filter_map(|a| match &a.data {
978            ArtifactData::Json(doc) => Some((a.name.as_str(), doc)),
979            ArtifactData::Protobuf(_) => None,
980        })
981        .collect()
982}
983
984impl Interface {
985    /// Reads a declaration against its packed files, and derives its types.
986    ///
987    /// # Errors
988    ///
989    /// [`Groups::read`]'s reasons.
990    pub fn read(annotation: &Json, files: &[(&str, &Json)]) -> Result<Self, Vec<Invalid>> {
991        let groups = Groups::read(annotation, files)?;
992        let derived = Derived::of(&groups);
993        Ok(Self { groups, derived })
994    }
995
996    /// A contract's config interface: its state `config`'s `config.groups`.
997    /// A reader MUST NOT read a record by a contract whose lint has a
998    /// finding (§2.2); [`lint_contract`] says.
999    ///
1000    /// # Errors
1001    ///
1002    /// [`Unread`].
1003    pub fn of(contract: &Contract) -> Result<Self, Unread> {
1004        let ann = contract
1005            .resource(KindToken::State, CONFIG)
1006            .and_then(|r| r.annotations.get(GROUPS))
1007            .ok_or(Unread::Missing)?;
1008        Self::read(ann, &packed_files(contract)).map_err(Unread::Invalid)
1009    }
1010
1011    /// config.v1's schema of the groups (§2.1, [`Groups::schema`]).
1012    #[must_use]
1013    pub fn schema(&self, writable: &BTreeSet<String>) -> Schema {
1014        self.groups.schema(writable)
1015    }
1016}
1017
1018// --- the record (§2.3) ---------------------------------------------------------------
1019
1020/// The pending change as the record carries it.
1021#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1022pub struct Pending {
1023    pub token: u64,
1024    /// Its groups, in the contract's order.
1025    pub groups: Vec<String>,
1026    /// While a reach group waits: when the last to join applies, in
1027    /// milliseconds since the Unix epoch, a whole second.
1028    pub apply_at: Option<i64>,
1029    /// When its undo runs, in milliseconds since the Unix epoch.
1030    pub deadline: i64,
1031    /// Whether every group of it is applied: no `apply_at`.
1032    pub applied: bool,
1033}
1034
1035/// The last change as the record carries it.
1036#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1037pub struct Last {
1038    pub token: u64,
1039    /// Its groups, in the contract's order.
1040    pub groups: Vec<String>,
1041}
1042
1043/// A desired refusal's code (§4).
1044#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1045#[serde(rename_all = "snake_case")]
1046pub enum DesiredCode {
1047    Reach,
1048    Contract,
1049    Sensitive,
1050    NotFound,
1051    InvalidRequest,
1052    Unavailable,
1053    Busy,
1054    DeviceRefused,
1055}
1056
1057impl DesiredCode {
1058    /// Its name, as [`DESIRED_CODES`] spells it.
1059    #[must_use]
1060    pub fn as_str(self) -> &'static str {
1061        DESIRED_CODES[self as usize]
1062    }
1063
1064    fn from_name(s: &str) -> Option<Self> {
1065        use DesiredCode as D;
1066        [
1067            D::Reach,
1068            D::Contract,
1069            D::Sensitive,
1070            D::NotFound,
1071            D::InvalidRequest,
1072            D::Unavailable,
1073            D::Busy,
1074            D::DeviceRefused,
1075        ]
1076        .into_iter()
1077        .find(|c| c.as_str() == s)
1078    }
1079}
1080
1081impl From<super::DesiredCode> for DesiredCode {
1082    fn from(c: super::DesiredCode) -> Self {
1083        use super::DesiredCode as V;
1084        match c {
1085            V::Reach => Self::Reach,
1086            V::Contract => Self::Contract,
1087            V::Sensitive => Self::Sensitive,
1088            V::NotFound => Self::NotFound,
1089            V::InvalidRequest => Self::InvalidRequest,
1090            V::Unavailable => Self::Unavailable,
1091            V::Busy => Self::Busy,
1092            V::DeviceRefused => Self::DeviceRefused,
1093        }
1094    }
1095}
1096
1097/// Why a desired document was refused or failed, by declared names: a
1098/// group or a parameter the contract does not declare is `None`, since
1099/// the record carries indices (§2.18).
1100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1101pub struct DesiredRefused {
1102    /// `None`: a code this revision does not name, the escape.
1103    pub code: Option<DesiredCode>,
1104    pub group: Option<String>,
1105    pub parameter: Option<String>,
1106}
1107
1108/// The desired report as the record carries it (§2.18).
1109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1110pub struct Desired {
1111    /// `None`: an outcome this revision does not name, the escape.
1112    pub outcome: Option<DesiredOutcome>,
1113    pub observed_revision: u32,
1114    pub refusal: Option<DesiredRefused>,
1115}
1116
1117/// One parameter as the record carries it (§2.3).
1118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1119#[serde(untagged)]
1120pub enum ParamState {
1121    /// A parameter that is not sensitive: its source and value, absent
1122    /// when unknown, and whether its startup value differs.
1123    Plain {
1124        source: Option<Source>,
1125        differs: bool,
1126        value: Option<Value>,
1127    },
1128    /// A sensitive parameter: its source alone (§2.15).
1129    Sensitive { source: Option<Source> },
1130}
1131
1132/// One group as the record carries it.
1133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1134pub struct GroupState {
1135    /// A settable group's: whether the allowlist lets a `set` reach it.
1136    #[serde(default, skip_serializing_if = "Option::is_none")]
1137    pub writable: Option<bool>,
1138    pub params: BTreeMap<String, ParamState>,
1139}
1140
1141/// The record, as `config.v2` reads one (§2.3): the fixtures' `state`.
1142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1143pub struct State {
1144    /// The instance number: the run the instance first wrote under.
1145    pub instance: u32,
1146    pub revision: u32,
1147    pub floor_s: u16,
1148    /// Set only in a dry run's reply (§2.9).
1149    pub would_be: bool,
1150    pub pending: Option<Pending>,
1151    pub last: Option<Last>,
1152    pub desired: Option<Desired>,
1153    /// By name. A group an earlier revision's writer did not write is
1154    /// absent.
1155    pub groups: BTreeMap<String, GroupState>,
1156}
1157
1158/// Why a reader refused a record (§2.3): core §7.6's refusals, then
1159/// config.v2's, the first that applies.
1160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1161pub enum RecordRefusal {
1162    Packed(packed::ReadRefusal),
1163    /// A group behind a marker written in part.
1164    Group,
1165    /// The pending fields not all present or all absent, or a pending
1166    /// change in no group.
1167    Pending,
1168    /// A last token and no group's last bit, or the reverse.
1169    Last,
1170    /// The desired fields do not hold together (§3).
1171    Desired,
1172    /// A value and its source not both present or both absent, or
1173    /// `differs` set with no value.
1174    Parameter,
1175}
1176
1177impl RecordRefusal {
1178    /// The fixtures' token.
1179    #[must_use]
1180    pub fn token(self) -> &'static str {
1181        match self {
1182            Self::Packed(r) => r.token(),
1183            Self::Group => "group",
1184            Self::Pending => "pending",
1185            Self::Last => "last",
1186            Self::Desired => "desired",
1187            Self::Parameter => "parameter",
1188        }
1189    }
1190}
1191
1192impl fmt::Display for RecordRefusal {
1193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194        f.write_str(self.token())
1195    }
1196}
1197
1198impl std::error::Error for RecordRefusal {}
1199
1200fn source_name(s: Source) -> &'static str {
1201    s.as_str()
1202}
1203
1204fn source_of(s: &str) -> Option<Source> {
1205    match s {
1206        "default" => Some(Source::Default),
1207        "file" => Some(Source::File),
1208        "overlay" => Some(Source::Overlay),
1209        "runtime" => Some(Source::Runtime),
1210        _ => None,
1211    }
1212}
1213
1214fn outcome_of(s: &str) -> Option<DesiredOutcome> {
1215    match s {
1216        "converged" => Some(DesiredOutcome::Converged),
1217        "refused" => Some(DesiredOutcome::Refused),
1218        "failed" => Some(DesiredOutcome::Failed),
1219        _ => None,
1220    }
1221}
1222
1223fn outcome_name(o: DesiredOutcome) -> &'static str {
1224    match o {
1225        DesiredOutcome::Converged => "converged",
1226        DesiredOutcome::Refused => "refused",
1227        DesiredOutcome::Failed => "failed",
1228    }
1229}
1230
1231fn value_json(v: &Value) -> Json {
1232    serde_json::to_value(v).expect("a value is JSON")
1233}
1234
1235impl Interface {
1236    /// A record's JSON reading (core §7.6): its fields by name, an absent
1237    /// optional field no member, a time in milliseconds since the Unix
1238    /// epoch.
1239    #[must_use]
1240    pub fn fields(&self, s: &State) -> Json {
1241        let mut m = Map::new();
1242        m.insert("instance".into(), s.instance.into());
1243        m.insert("revision".into(), s.revision.into());
1244        m.insert("floor_s".into(), s.floor_s.into());
1245        m.insert("would_be".into(), s.would_be.into());
1246        if let Some(p) = &s.pending {
1247            m.insert("pending_token".into(), p.token.into());
1248            if let Some(a) = p.apply_at {
1249                m.insert("pending_apply_at".into(), a.into());
1250            }
1251            m.insert("pending_deadline".into(), p.deadline.into());
1252        }
1253        if let Some(l) = &s.last {
1254            m.insert("last_token".into(), l.token.into());
1255        }
1256        if let Some(d) = &s.desired {
1257            m.insert(
1258                "desired".into(),
1259                d.outcome.map_or(Json::Null, |o| outcome_name(o).into()),
1260            );
1261            m.insert("desired_revision".into(), d.observed_revision.into());
1262            if let Some(r) = &d.refusal {
1263                m.insert(
1264                    "desired_code".into(),
1265                    r.code.map_or(Json::Null, |c| c.as_str().into()),
1266                );
1267                if let Some((gi, g)) = r.group.as_deref().and_then(|n| self.groups.group(n)) {
1268                    m.insert("desired_group".into(), gi.into());
1269                    if let Some((pi, _)) = r.parameter.as_deref().and_then(|n| g.parameter(n)) {
1270                        m.insert("desired_parameter".into(), pi.into());
1271                    }
1272                }
1273            }
1274        }
1275        for g in self.groups.iter() {
1276            let Some(gs) = s.groups.get(&g.name) else {
1277                continue;
1278            };
1279            if g.settable() {
1280                let inside =
1281                    |groups: Option<&Vec<String>>| groups.is_some_and(|v| v.contains(&g.name));
1282                m.insert(
1283                    format!("{}__writable", g.name),
1284                    gs.writable.unwrap_or(false).into(),
1285                );
1286                m.insert(
1287                    format!("{}__pending", g.name),
1288                    inside(s.pending.as_ref().map(|p| &p.groups)).into(),
1289                );
1290                m.insert(
1291                    format!("{}__last", g.name),
1292                    inside(s.last.as_ref().map(|l| &l.groups)).into(),
1293                );
1294            }
1295            for p in &g.parameters {
1296                let at = format!("{}__{}", g.name, p.name);
1297                let (source, differs, value) = match gs.params.get(&p.name) {
1298                    Some(ParamState::Plain {
1299                        source,
1300                        differs,
1301                        value,
1302                    }) => (*source, *differs, value.as_ref()),
1303                    Some(ParamState::Sensitive { source }) => (*source, false, None),
1304                    None => (None, false, None),
1305                };
1306                if let Some(src) = source {
1307                    m.insert(format!("{at}__source"), source_name(src).into());
1308                }
1309                if !p.sensitive {
1310                    m.insert(format!("{at}__differs"), differs.into());
1311                    if let Some(v) = value {
1312                        m.insert(at, value_json(v));
1313                    }
1314                }
1315            }
1316        }
1317        Json::Object(m)
1318    }
1319
1320    /// Writes a record under the deployment epoch, in seconds (§2.3).
1321    ///
1322    /// # Errors
1323    ///
1324    /// The packed writer's refusal: a value outside its field, a time
1325    /// before the epoch or past its 32 bits.
1326    pub fn write_record(
1327        &self,
1328        s: &State,
1329        epoch: i64,
1330    ) -> Result<packed::Record, packed::WriteRefusal> {
1331        self.derived.record().write(&self.fields(s), Some(epoch))
1332    }
1333
1334    /// Reads a record under its CH's tag and the deployment epoch, refusing
1335    /// it for the first of §2.3's checks that applies.
1336    ///
1337    /// # Errors
1338    ///
1339    /// The [`RecordRefusal`].
1340    pub fn read_record(&self, tag: u8, bytes: &[u8], epoch: i64) -> Result<State, RecordRefusal> {
1341        let fields = self
1342            .derived
1343            .record()
1344            .read(tag, bytes, Some(epoch))
1345            .map_err(RecordRefusal::Packed)?;
1346        self.state_of(&fields)
1347    }
1348
1349    /// A record's JSON reading read as a [`State`], with §2.3's checks
1350    /// after core §7.6's: `group`, `pending`, `last`, `desired`, then
1351    /// `parameter`.
1352    ///
1353    /// # Errors
1354    ///
1355    /// The first [`RecordRefusal`] that applies.
1356    #[allow(clippy::too_many_lines)]
1357    pub fn state_of(&self, fields: &Json) -> Result<State, RecordRefusal> {
1358        let empty = Map::new();
1359        let f = fields.as_object().unwrap_or(&empty);
1360        let has = |k: &str| f.contains_key(k);
1361        let get_bool = |k: &str| f.get(k).and_then(Json::as_bool);
1362        let get_u64 = |k: &str| f.get(k).and_then(Json::as_u64);
1363        // Which groups an earlier revision's writer left out: none of their
1364        // fields present.
1365        let field_names = |g: &Group| {
1366            let mut v = Vec::new();
1367            if g.settable() {
1368                for bit in ["writable", "pending", "last"] {
1369                    v.push(format!("{}__{bit}", g.name));
1370                }
1371            }
1372            for p in &g.parameters {
1373                let at = format!("{}__{}", g.name, p.name);
1374                v.push(format!("{at}__source"));
1375                if !p.sensitive {
1376                    v.push(format!("{at}__differs"));
1377                    v.push(at);
1378                }
1379            }
1380            v
1381        };
1382        let present: Vec<&Group> = self
1383            .groups
1384            .iter()
1385            .filter(|g| !g.appended || field_names(g).iter().any(|n| has(n)))
1386            .collect();
1387        for g in &present {
1388            if !g.appended {
1389                continue;
1390            }
1391            let bits = ["writable", "pending", "last"].map(|b| has(&format!("{}__{b}", g.name)));
1392            if g.settable() && !bits.iter().all(|b| *b) {
1393                return Err(RecordRefusal::Group);
1394            }
1395            for p in g.parameters.iter().filter(|p| !p.sensitive) {
1396                let at = format!("{}__{}", g.name, p.name);
1397                if has(&at) && !has(&format!("{at}__differs")) {
1398                    return Err(RecordRefusal::Group);
1399                }
1400            }
1401        }
1402        let bit = |g: &Group, b: &str| get_bool(&format!("{}__{b}", g.name)) == Some(true);
1403        let pending_groups: Vec<String> = present
1404            .iter()
1405            .filter(|g| g.settable() && bit(g, "pending"))
1406            .map(|g| g.name.clone())
1407            .collect();
1408        let last_groups: Vec<String> = present
1409            .iter()
1410            .filter(|g| g.settable() && bit(g, "last"))
1411            .map(|g| g.name.clone())
1412            .collect();
1413        let token = get_u64("pending_token");
1414        let deadline = f.get("pending_deadline").and_then(Json::as_i64);
1415        let apply_at = f.get("pending_apply_at").and_then(Json::as_i64);
1416        if token.is_some() != deadline.is_some()
1417            || ((apply_at.is_some() || !pending_groups.is_empty()) && token.is_none())
1418            || (token.is_some() && pending_groups.is_empty())
1419        {
1420            return Err(RecordRefusal::Pending);
1421        }
1422        let last_token = get_u64("last_token");
1423        if last_token.is_some() != !last_groups.is_empty() {
1424            return Err(RecordRefusal::Last);
1425        }
1426        let desired = if has("desired") {
1427            let outcome = f.get("desired").and_then(Json::as_str).and_then(outcome_of);
1428            let escaped = f.get("desired").is_some_and(Json::is_null);
1429            let coded = has("desired_code");
1430            let code_wrong = match outcome {
1431                Some(DesiredOutcome::Converged) => coded,
1432                Some(_) => !coded,
1433                None => !escaped,
1434            };
1435            let group = get_u64("desired_group");
1436            let parameter = get_u64("desired_parameter");
1437            let g = group.and_then(|i| self.groups.iter().nth(usize::try_from(i).ok()?));
1438            let p = match (g, parameter) {
1439                (Some(g), Some(i)) => usize::try_from(i).ok().and_then(|i| g.parameters.get(i)),
1440                _ => None,
1441            };
1442            let Some(revision) = get_u64("desired_revision").and_then(|r| u32::try_from(r).ok())
1443            else {
1444                return Err(RecordRefusal::Desired);
1445            };
1446            if code_wrong
1447                || (group.is_some() && !coded)
1448                || (parameter.is_some() && group.is_none())
1449                || (group.is_some() && g.is_none())
1450                || (parameter.is_some() && p.is_none())
1451            {
1452                return Err(RecordRefusal::Desired);
1453            }
1454            Some(Desired {
1455                outcome,
1456                observed_revision: revision,
1457                refusal: coded.then(|| DesiredRefused {
1458                    code: f
1459                        .get("desired_code")
1460                        .and_then(Json::as_str)
1461                        .and_then(DesiredCode::from_name),
1462                    group: g.map(|g| g.name.clone()),
1463                    parameter: p.map(|p| p.name.clone()),
1464                }),
1465            })
1466        } else {
1467            if [
1468                "desired_revision",
1469                "desired_code",
1470                "desired_group",
1471                "desired_parameter",
1472            ]
1473            .iter()
1474            .any(|k| has(k))
1475            {
1476                return Err(RecordRefusal::Desired);
1477            }
1478            None
1479        };
1480        let mut groups = BTreeMap::new();
1481        for g in &present {
1482            let mut params = BTreeMap::new();
1483            for p in &g.parameters {
1484                let at = format!("{}__{}", g.name, p.name);
1485                let source = f
1486                    .get(&format!("{at}__source"))
1487                    .and_then(Json::as_str)
1488                    .and_then(source_of);
1489                let state = if p.sensitive {
1490                    ParamState::Sensitive { source }
1491                } else {
1492                    let value = f.get(&at).and_then(|v| p.value_of(v));
1493                    let differs = get_bool(&format!("{at}__differs")) == Some(true);
1494                    if value.is_some() != source.is_some() || (differs && value.is_none()) {
1495                        return Err(RecordRefusal::Parameter);
1496                    }
1497                    ParamState::Plain {
1498                        source,
1499                        differs,
1500                        value,
1501                    }
1502                };
1503                params.insert(p.name.clone(), state);
1504            }
1505            groups.insert(
1506                g.name.clone(),
1507                GroupState {
1508                    writable: g.settable().then(|| bit(g, "writable")),
1509                    params,
1510                },
1511            );
1512        }
1513        let int = |k: &str| get_u64(k).unwrap_or_default();
1514        Ok(State {
1515            instance: u32::try_from(int("instance")).unwrap_or(u32::MAX),
1516            revision: u32::try_from(int("revision")).unwrap_or(u32::MAX),
1517            floor_s: u16::try_from(int("floor_s")).unwrap_or(u16::MAX),
1518            would_be: get_bool("would_be") == Some(true),
1519            pending: token.map(|token| Pending {
1520                token,
1521                groups: pending_groups,
1522                apply_at,
1523                deadline: deadline.unwrap_or_default(),
1524                applied: apply_at.is_none(),
1525            }),
1526            last: last_token.map(|token| Last {
1527                token,
1528                groups: last_groups,
1529            }),
1530            desired,
1531            groups,
1532        })
1533    }
1534}
1535
1536// --- requests (§2.5, §2.10) -----------------------------------------------------------
1537
1538/// A `set`'s request, `Set<T>` read (§2.5).
1539#[derive(Debug, Clone, PartialEq, Eq, Default)]
1540pub struct Set {
1541    /// Some parameters of the group, by name.
1542    pub values: BTreeMap<String, Value>,
1543    pub confirm_s: Option<u16>,
1544    pub token: Option<u64>,
1545    pub expected_revision: Option<u32>,
1546    pub idempotency_key: Option<u32>,
1547    pub dry_run: bool,
1548}
1549
1550/// A control operation's request, `Control` read (§2.10).
1551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1552pub struct Control {
1553    pub token: u64,
1554    /// For `extend` alone.
1555    pub confirm_s: Option<u16>,
1556}
1557
1558/// Why a request does not parse: `invalid_request`, first (§2.5).
1559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1560pub enum RequestRefusal {
1561    /// Core §7.5's refusals for a query.
1562    Form(wire::Refusal),
1563    /// Core §7.6's for the request's type, its tag first.
1564    Record(packed::ReadRefusal),
1565}
1566
1567impl RequestRefusal {
1568    /// The refusal's token.
1569    #[must_use]
1570    pub fn token(self) -> &'static str {
1571        match self {
1572            Self::Form(r) => r.token(),
1573            Self::Record(r) => r.token(),
1574        }
1575    }
1576}
1577
1578impl fmt::Display for RequestRefusal {
1579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1580        write!(f, "the request does not parse: {}", self.token())
1581    }
1582}
1583
1584impl std::error::Error for RequestRefusal {}
1585
1586fn tag_of(layout: &Layout) -> Tag {
1587    Tag::new(layout.tag()).expect("a layout's tag is four bits")
1588}
1589
1590/// A query's payload read as a request of `layout`'s type: its JSON
1591/// reading.
1592fn read_request(layout: &Layout, payload: &[u8]) -> Result<Json, RequestRefusal> {
1593    let req = wire::read_query(payload).map_err(RequestRefusal::Form)?;
1594    layout
1595        .read(req.tag.get(), req.record, None)
1596        .map_err(RequestRefusal::Record)
1597}
1598
1599fn write_request(layout: &Layout, fields: &Json) -> Result<Vec<u8>, packed::WriteRefusal> {
1600    let rec = layout.write(fields, None)?;
1601    Ok(Request::new(tag_of(layout), &rec.bytes).write())
1602}
1603
1604impl Set {
1605    /// Its JSON reading (core §7.6).
1606    #[must_use]
1607    pub fn to_json(&self) -> Json {
1608        let mut m: Map<String, Json> = self
1609            .values
1610            .iter()
1611            .map(|(k, v)| (k.clone(), value_json(v)))
1612            .collect();
1613        if let Some(c) = self.confirm_s {
1614            m.insert("confirm_s".into(), c.into());
1615        }
1616        if let Some(t) = self.token {
1617            m.insert("token".into(), t.into());
1618        }
1619        if let Some(e) = self.expected_revision {
1620            m.insert("expected_revision".into(), e.into());
1621        }
1622        if let Some(k) = self.idempotency_key {
1623            m.insert("idempotency_key".into(), k.into());
1624        }
1625        m.insert("dry_run".into(), self.dry_run.into());
1626        Json::Object(m)
1627    }
1628
1629    fn of_json(group: &Group, f: &Json) -> Self {
1630        let num = |k: &str| f.get(k).and_then(Json::as_u64);
1631        Self {
1632            values: group
1633                .parameters
1634                .iter()
1635                .filter_map(|p| Some((p.name.clone(), p.value_of(f.get(&p.name)?)?)))
1636                .collect(),
1637            confirm_s: num("confirm_s").and_then(|v| u16::try_from(v).ok()),
1638            token: num("token"),
1639            expected_revision: num("expected_revision").and_then(|v| u32::try_from(v).ok()),
1640            idempotency_key: num("idempotency_key").and_then(|v| u32::try_from(v).ok()),
1641            dry_run: f.get("dry_run").and_then(Json::as_bool) == Some(true),
1642        }
1643    }
1644
1645    /// config.v1's request of this one, its token by `token`: the values
1646    /// as JSON, and no idempotency key, which [`Owner`] holds itself.
1647    fn to_v1(&self, token: impl Fn(u64) -> String) -> SetRequest {
1648        SetRequest {
1649            values: self
1650                .values
1651                .iter()
1652                .map(|(k, v)| (k.clone(), value_json(v)))
1653                .collect(),
1654            confirm_s: self.confirm_s.map(u64::from),
1655            token: self.token.map(token),
1656            expected_revision: self.expected_revision.map(u64::from),
1657            idempotency_key: None,
1658            dry_run: self.dry_run,
1659        }
1660    }
1661}
1662
1663impl Control {
1664    /// Its JSON reading (core §7.6).
1665    #[must_use]
1666    pub fn to_json(&self) -> Json {
1667        let mut m = Map::new();
1668        m.insert("token".into(), self.token.into());
1669        if let Some(c) = self.confirm_s {
1670            m.insert("confirm_s".into(), c.into());
1671        }
1672        Json::Object(m)
1673    }
1674
1675    fn to_v1(self, token: impl Fn(u64) -> String) -> ControlRequest {
1676        ControlRequest {
1677            token: token(self.token),
1678            confirm_s: self.confirm_s.map(u64::from),
1679            answer: None,
1680        }
1681    }
1682}
1683
1684impl Interface {
1685    /// A `set/<group>`'s query payload read as its `Set<T>`, with the
1686    /// request's JSON reading; `None` for a group with no `set`, which no
1687    /// queryable answers (§2.4).
1688    ///
1689    /// # Errors
1690    ///
1691    /// The [`RequestRefusal`].
1692    pub fn decode_set(
1693        &self,
1694        group: &str,
1695        payload: &[u8],
1696    ) -> Option<Result<(Set, Json), RequestRefusal>> {
1697        let g = self.groups.settable(group)?;
1698        let (_, layout) = self.derived.set(group)?;
1699        Some(read_request(layout, payload).map(|f| (Set::of_json(g, &f), f)))
1700    }
1701
1702    /// A `set/<group>`'s query payload: CH, then `Set<T>`'s record.
1703    ///
1704    /// # Errors
1705    ///
1706    /// The packed writer's refusal; [`packed::WriteRefusal::Unknown`] for a
1707    /// group with no `set`.
1708    pub fn encode_set(&self, group: &str, s: &Set) -> Result<Vec<u8>, packed::WriteRefusal> {
1709        let (_, layout) = self
1710            .derived
1711            .set(group)
1712            .ok_or(packed::WriteRefusal::Unknown)?;
1713        write_request(layout, &s.to_json())
1714    }
1715
1716    /// A control operation's query payload read as its `Control`.
1717    ///
1718    /// # Errors
1719    ///
1720    /// The [`RequestRefusal`].
1721    pub fn decode_control(&self, payload: &[u8]) -> Result<Control, RequestRefusal> {
1722        let f = read_request(self.derived.control(), payload)?;
1723        let num = |k: &str| f.get(k).and_then(Json::as_u64);
1724        Ok(Control {
1725            token: num("token").unwrap_or_default(),
1726            confirm_s: num("confirm_s").and_then(|v| u16::try_from(v).ok()),
1727        })
1728    }
1729
1730    /// A control operation's query payload.
1731    ///
1732    /// # Errors
1733    ///
1734    /// The packed writer's refusal.
1735    pub fn encode_control(&self, c: &Control) -> Result<Vec<u8>, packed::WriteRefusal> {
1736        write_request(self.derived.control(), &c.to_json())
1737    }
1738
1739    /// A `set`'s request as a log line may carry it (§2.15): its JSON
1740    /// reading, each sensitive parameter's value written [`REDACTED`].
1741    #[must_use]
1742    pub fn log_set(&self, group: &str, fields: &Json) -> Json {
1743        let mut out = fields.clone();
1744        if let (Some(g), Some(m)) = (self.groups.settable(group), out.as_object_mut()) {
1745            for p in g.parameters.iter().filter(|p| p.sensitive) {
1746                if let Some(v) = m.get_mut(&p.name) {
1747                    *v = Json::String(REDACTED.to_owned());
1748                }
1749            }
1750        }
1751        out
1752    }
1753}
1754
1755// --- answers: the value and error forms (§2.5, §2.9) ----------------------------------
1756
1757/// What an operation answered, as a caller reads it.
1758#[derive(Debug, Clone, PartialEq, Eq)]
1759pub enum Answer {
1760    /// The record, in core §7.5's value form, under the as-of mark.
1761    Value { stamp: Stamp, state: Box<State> },
1762    /// A refusal in the error form, under the as-of mark.
1763    Error {
1764        stamp: Stamp,
1765        code: ErrorCode,
1766        cause: Option<Cause>,
1767        /// `app`'s `Error` detail: `device_refused` at this version.
1768        app: bool,
1769        /// For a person: the device's words, with `device_refused` alone.
1770        message: Option<String>,
1771    },
1772}
1773
1774/// A reply: what it answered, and its payload's bytes.
1775#[derive(Debug, Clone, PartialEq, Eq)]
1776pub struct Reply {
1777    pub answer: Answer,
1778    pub payload: Vec<u8>,
1779}
1780
1781impl Interface {
1782    /// The record's value form: a reply's payload under the as-of mark.
1783    ///
1784    /// # Errors
1785    ///
1786    /// [`Interface::write_record`]'s.
1787    pub fn value(
1788        &self,
1789        state: &State,
1790        stamp: Stamp,
1791        epoch: i64,
1792    ) -> Result<Reply, packed::WriteRefusal> {
1793        let rec = self.write_record(state, epoch)?;
1794        let payload = Envelope::value(tag_of(self.derived.record()), stamp, &rec.bytes).write();
1795        Ok(Reply {
1796            answer: Answer::Value {
1797                stamp,
1798                state: Box::new(state.clone()),
1799            },
1800            payload,
1801        })
1802    }
1803
1804    /// A refusal's error form (§2.5): `Error`'s tag, the as-of mark, the
1805    /// code and `unavailable`'s cause `config`; with `app`, an `Error`
1806    /// detail and the device's words, where §2.15 lets them be carried.
1807    #[must_use]
1808    pub fn error(&self, r: &Refusal, stamp: Stamp) -> Reply {
1809        let code = match r.code {
1810            Code::InvalidRequest => ErrorCode::InvalidRequest,
1811            Code::NotFound => ErrorCode::NotFound,
1812            Code::Unavailable => ErrorCode::Unavailable,
1813            Code::Forbidden => ErrorCode::Forbidden,
1814            Code::Busy => ErrorCode::Busy,
1815            Code::App => ErrorCode::App,
1816        };
1817        let cause = (r.code == Code::Unavailable).then_some(Cause::Config);
1818        let app = r.app.is_some();
1819        let message = r
1820            .app
1821            .as_ref()
1822            .and_then(|a| a.detail.as_deref())
1823            .map(|m| crate::envelope::cut(m).to_owned());
1824        let detail = app.then(|| {
1825            self.derived
1826                .error()
1827                .write(&json!({ "code": DEVICE_REFUSED }), None)
1828                .expect("device_refused is Error's")
1829                .bytes
1830        });
1831        let form = ErrorForm {
1832            tag: tag_of(self.derived.error()),
1833            stamp,
1834            code,
1835            cause,
1836            message: message.as_deref(),
1837            detail: detail.as_deref(),
1838        };
1839        let payload = form
1840            .write()
1841            .expect("a cause on unavailable alone, a detail on app alone");
1842        Reply {
1843            answer: Answer::Error {
1844                stamp,
1845                code,
1846                cause,
1847                app,
1848                message,
1849            },
1850            payload,
1851        }
1852    }
1853}
1854
1855// --- times (§2.8) ----------------------------------------------------------------------
1856
1857/// The deadline of a window `max(confirm_s, floor_s)` counted from
1858/// `received`, rounded up to the next whole second (§2.8).
1859#[must_use]
1860pub fn deadline(received: Time, confirm_s: u16, floor_s: u16) -> Time {
1861    super::deadline(received, super::window(confirm_s.into(), floor_s.into())).ceil_second()
1862}
1863
1864/// The `apply_at` an owner writes for the instant its device states,
1865/// rounded up to the next whole second (§2.8).
1866#[must_use]
1867pub fn apply_at(device: Time) -> Time {
1868    device.ceil_second()
1869}
1870
1871// --- validation (§2.5, §2.10, §2.13, §2.18) ---------------------------------------------
1872
1873/// What a validator reads of an owner's state, as a record shows it.
1874#[derive(Debug, Clone, PartialEq, Eq, Default)]
1875pub struct Facts {
1876    pub revision: u32,
1877    pub pending: Option<PendingFacts>,
1878    pub last: Option<LastFacts>,
1879    /// Whether the owner has a persisted layer.
1880    pub persist: bool,
1881    /// Whether an act is in flight.
1882    pub in_flight: bool,
1883    /// The groups the startup allowlist lets a `set` reach.
1884    pub writable: BTreeSet<String>,
1885}
1886
1887/// The pending change, as a validator reads it.
1888#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1889pub struct PendingFacts {
1890    pub token: u64,
1891    pub applied: bool,
1892    pub deadline_passed: bool,
1893}
1894
1895/// The last change, as `persist` reads it.
1896#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1897pub struct LastFacts {
1898    pub token: u64,
1899    pub set_sensitive: bool,
1900}
1901
1902fn unparsed(r: RequestRefusal) -> Refusal {
1903    Refusal::new(Code::InvalidRequest, None, r.to_string())
1904}
1905
1906/// Runs `f` over config.v1's facts of `facts`, its tokens spelt in
1907/// decimal, as a request's are.
1908fn with_v1<T>(facts: &Facts, f: impl FnOnce(&super::Facts<'_>) -> T) -> T {
1909    let pending = facts.pending.map(|p| (p.token.to_string(), p));
1910    let last = facts.last.map(|l| (l.token.to_string(), l));
1911    let v1 = super::Facts {
1912        revision: facts.revision.into(),
1913        pending: pending.as_ref().map(|(t, p)| super::PendingFacts {
1914            token: t,
1915            applied: p.applied,
1916            deadline_passed: p.deadline_passed,
1917        }),
1918        last_change: last.as_ref().map(|(t, l)| super::LastFacts {
1919            token: t,
1920            set_sensitive: l.set_sensitive,
1921        }),
1922        persist: facts.persist,
1923        in_flight: facts.in_flight,
1924    };
1925    f(&v1)
1926}
1927
1928/// Checks a `set/<group>`'s request as §2.5 orders it: the payload's parse
1929/// (`invalid_request`), then config.v1's rows without rows 3, 8 and 11.
1930/// Rows 2 and 12 to 14 need the owner's keys, rate, deadline and device:
1931/// [`Owner::set`] adds them. `None` for a group with no `set`.
1932///
1933/// # Errors
1934///
1935/// The first [`Refusal`] that applies.
1936pub fn validate_set(
1937    iface: &Interface,
1938    facts: &Facts,
1939    group: &str,
1940    payload: &[u8],
1941) -> Option<Result<(), Refusal>> {
1942    let parsed = iface.decode_set(group, payload)?;
1943    Some(parsed.map_err(unparsed).and_then(|(s, _)| {
1944        let schema = iface.schema(&facts.writable);
1945        let req = s.to_v1(|t| t.to_string());
1946        with_v1(facts, |f| super::validate_set(&schema, f, group, &req)).map(|_| ())
1947    }))
1948}
1949
1950/// Checks a control operation's request as §2.10 and §2.13 order it:
1951/// `persist` without a persisted layer first, then the parse, then
1952/// config.v1's checks.
1953///
1954/// # Errors
1955///
1956/// The first [`Refusal`] that applies.
1957pub fn validate_control(
1958    iface: &Interface,
1959    op: ControlOp,
1960    facts: &Facts,
1961    payload: &[u8],
1962) -> Result<(), Refusal> {
1963    if op == ControlOp::Persist && !facts.persist {
1964        return with_v1(facts, |f| {
1965            super::validate_control(op, f, &ControlRequest::default())
1966        });
1967    }
1968    let c = iface.decode_control(payload).map_err(unparsed)?;
1969    with_v1(facts, |f| {
1970        super::validate_control(op, f, &c.to_v1(|t| t.to_string()))
1971    })
1972}
1973
1974/// A desired refusal by declared names (§2.18): a group or a parameter the
1975/// contract does not declare named `None`.
1976fn declared(
1977    iface: &Interface,
1978    code: DesiredCode,
1979    group: &str,
1980    parameter: Option<&str>,
1981) -> DesiredRefused {
1982    let g = iface.groups.group(group).map(|(_, g)| g);
1983    DesiredRefused {
1984        code: Some(code),
1985        group: g.map(|g| g.name.clone()),
1986        parameter: g
1987            .zip(parameter)
1988            .and_then(|(g, p)| g.parameter(p))
1989            .map(|(_, p)| p.name.clone()),
1990    }
1991}
1992
1993/// Checks a desired document (§2.18): its revision within 32 bits first,
1994/// then config.v1's order over the groups' schema.
1995///
1996/// # Errors
1997///
1998/// The [`DesiredRefused`].
1999pub fn check_desired(
2000    iface: &Interface,
2001    writable: &BTreeSet<String>,
2002    doc: &DesiredConfig,
2003) -> Result<(), DesiredRefused> {
2004    if doc.revision > u64::from(u32::MAX) {
2005        return Err(DesiredRefused {
2006            code: Some(DesiredCode::InvalidRequest),
2007            group: None,
2008            parameter: None,
2009        });
2010    }
2011    super::check_desired(&iface.schema(writable), doc)
2012        .map_err(|r| declared(iface, r.code.into(), &r.group, r.parameter.as_deref()))
2013}
2014
2015// --- the change event (§2.17) ------------------------------------------------------------
2016
2017/// One change as it ended, `ConfigChangeEvent` of `config.v2.json`.
2018#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2019pub struct ChangeEvent {
2020    pub service: String,
2021    /// The instance number.
2022    pub instance: u32,
2023    pub revision: u64,
2024    pub token: u64,
2025    pub outcome: Outcome,
2026    /// In the contract's order of groups, then of parameters.
2027    pub edits: Vec<Edit>,
2028    #[serde(default, skip_serializing_if = "Option::is_none")]
2029    pub actor: Option<String>,
2030    #[serde(default, skip_serializing_if = "Option::is_none")]
2031    pub request_id: Option<String>,
2032    #[serde(default, skip_serializing_if = "Option::is_none")]
2033    pub claimed_source: Option<String>,
2034}
2035
2036// --- the owner (§2.3 to §2.17) ------------------------------------------------------------
2037
2038/// What an owner writes under (core §4.3): the run, each seq, a new run
2039/// when the seq is spent or the owner asks, and each run's first token
2040/// count. The seq is the instance's, shared by every state key and event
2041/// it writes, so the runtime implements this over the service's minter.
2042pub trait Mint {
2043    /// The run written under now.
2044    fn run(&self) -> Run;
2045    /// The last seq minted under it, `None` when none was.
2046    fn last_seq(&self) -> Option<Seq>;
2047    /// Mints the next seq for a put or an event, taking a new run first
2048    /// when the seq is spent.
2049    fn stamp(&mut self) -> Stamp;
2050    /// Takes a new run now: the token counter is spent (§2.6), or the
2051    /// owner restarts.
2052    fn next_run(&mut self);
2053    /// The token counter's first value in the run written under now, the
2054    /// same each time it is asked within that run: drawn at random once
2055    /// per run (§2.6).
2056    fn counter_start(&mut self) -> u16;
2057}
2058
2059/// The as-of mark (core §5.1): the run written under, and the last seq
2060/// minted under it, or 0.
2061fn mark(mint: &dyn Mint) -> Stamp {
2062    Stamp {
2063        run: mint.run(),
2064        seq: mint.last_seq().unwrap_or(Seq::new(0).expect("0 is a seq")),
2065    }
2066}
2067
2068/// What a `config.v2` owner starts from.
2069#[derive(Debug, Clone)]
2070pub struct Start {
2071    /// The owner's address, `<system>/<service>`.
2072    pub service: String,
2073    /// The startup file's and the defaults' values, as config.v1's.
2074    pub startup: BTreeMap<String, BTreeMap<String, (Value, Source)>>,
2075    /// The persisted layer.
2076    pub overlay: BTreeMap<String, BTreeMap<String, Value>>,
2077    /// The floor, from 1 to 65,535 s (§2.8).
2078    pub floor_s: u16,
2079    /// When the device applies a reach `set` after receiving it, as
2080    /// config.v1's; the `apply_at` written is rounded up.
2081    pub apply_after: Duration,
2082    pub persist: bool,
2083    /// The startup allowlist: the settable groups a `set` may reach.
2084    pub writable: BTreeSet<String>,
2085    /// The change events already published, for the rate.
2086    pub events: Vec<Time>,
2087    /// The deployment epoch, in seconds (core §8.6): what times count from.
2088    pub epoch: i64,
2089}
2090
2091/// A put of the record.
2092#[derive(Debug, Clone, PartialEq, Eq)]
2093pub struct Put {
2094    pub stamp: Stamp,
2095    pub state: State,
2096    /// The put's payload: CH, form 0, the stamp, the record.
2097    pub payload: Vec<u8>,
2098}
2099
2100/// A change event to publish, under its stamp.
2101#[derive(Debug, Clone, PartialEq, Eq)]
2102pub struct Published {
2103    pub stamp: Stamp,
2104    pub event: ChangeEvent,
2105}
2106
2107/// What a step writes, in this order: the record's puts, the reply, then
2108/// the change events (§2.3, §2.9, §2.17).
2109#[derive(Debug, Clone, PartialEq, Eq, Default)]
2110pub struct Output {
2111    pub puts: Vec<Put>,
2112    /// `None` when no call is answered, or for a call to a group with no
2113    /// `set`, which no queryable answers.
2114    pub reply: Option<Reply>,
2115    pub events: Vec<Published>,
2116}
2117
2118/// What the owner does next: write, or have the runtime act on the device
2119/// and report back with [`Owner::finish`].
2120#[derive(Debug, Clone, PartialEq, Eq)]
2121pub enum Step {
2122    Done(Output),
2123    Act(Act),
2124}
2125
2126/// What converging a desired document asks next (§2.18).
2127#[derive(Debug, Clone, PartialEq, Eq)]
2128pub enum Converge {
2129    /// A change is pending, or an act is in flight.
2130    Wait,
2131    /// Refused whole: the report to carry.
2132    Refused(DesiredReport),
2133    /// One `set` without a window on this group.
2134    Set { group: String, request: Set },
2135    /// Every value the document names runs.
2136    Converged(DesiredReport),
2137}
2138
2139#[derive(Debug, Clone)]
2140struct Held {
2141    key: u32,
2142    group: String,
2143    payload: Vec<u8>,
2144    reply: Reply,
2145    at: Time,
2146}
2147
2148/// A `set` whose device act is in flight.
2149#[derive(Debug, Clone)]
2150struct InFlight {
2151    key: Option<(u32, String, Vec<u8>)>,
2152}
2153
2154/// One `config.v2` owner, as a pure state machine over
2155/// [`super::Owner`], which runs config.v1's rules unchanged with its
2156/// times rounded up to the second ([`super::Owner::whole_seconds`]).
2157///
2158/// It adds the wire (§2.3 to §2.17): it puts its record whenever a field
2159/// of it changes, and only then; it answers every call with the record in
2160/// the value form, or a refusal in the error form, under its as-of mark;
2161/// it publishes each change's event after the reply; it mints 48-bit
2162/// tokens, a new run before the counter passes 65,535; and it replays an
2163/// idempotent retry's first answer byte for byte.
2164#[derive(Debug, Clone)]
2165pub struct Owner {
2166    iface: Interface,
2167    inner: super::Owner,
2168    epoch: i64,
2169    instance: u32,
2170    /// The run the token counter counts in, and its next count.
2171    token_run: Option<Run>,
2172    counter: u32,
2173    /// config.v1's tokens of the pending and last changes, and their
2174    /// config.v2 numbers.
2175    tokens: Vec<(String, u64)>,
2176    keys: Vec<Held>,
2177    flight: Option<InFlight>,
2178    last_put: Option<Vec<u8>>,
2179}
2180
2181impl Owner {
2182    /// Starts an owner (§2.3): its instance number is the run `mint`
2183    /// writes under, and its first put is its record, before its tokens.
2184    ///
2185    /// # Errors
2186    ///
2187    /// config.v1's [`StartError`]s, and a floor of 0.
2188    pub fn start(
2189        iface: Interface,
2190        s: Start,
2191        mint: &mut dyn Mint,
2192    ) -> Result<(Self, Output), StartError> {
2193        let instance = mint.run().value();
2194        let inner = super::Owner::start(super::Start {
2195            service: s.service,
2196            instance: instance.to_string(),
2197            schema: iface.schema(&s.writable),
2198            startup: s.startup,
2199            overlay: s.overlay,
2200            floor_s: s.floor_s.into(),
2201            apply_after: s.apply_after,
2202            persist: s.persist,
2203            events: s.events,
2204        })?
2205        .whole_seconds();
2206        let mut owner = Self {
2207            iface,
2208            inner,
2209            epoch: s.epoch,
2210            instance,
2211            token_run: None,
2212            counter: 0,
2213            tokens: Vec::new(),
2214            keys: Vec::new(),
2215            flight: None,
2216            last_put: None,
2217        };
2218        let out = owner.settle(super::Done::default(), false, mint);
2219        Ok((owner, out))
2220    }
2221
2222    /// The owner after a restart (§2.12): a new instance under the next
2223    /// run `mint` takes, its startup values and persisted layer, nothing
2224    /// pending, no key held.
2225    #[must_use]
2226    pub fn restart(&self, mint: &mut dyn Mint) -> (Self, Output) {
2227        mint.next_run();
2228        self.restart_in(mint)
2229    }
2230
2231    /// [`Owner::restart`] in a new instance that took its run already, as a
2232    /// re-mint does (v1 §2.12, "A re-mint is a restart"; core §1.5, §4.3):
2233    /// its instance number is the run `mint` writes under now, under which
2234    /// nothing was written yet.
2235    #[must_use]
2236    pub fn restart_in(&self, mint: &mut dyn Mint) -> (Self, Output) {
2237        let instance = mint.run().value();
2238        let mut owner = Self {
2239            iface: self.iface.clone(),
2240            inner: self.inner.restart(instance.to_string()),
2241            epoch: self.epoch,
2242            instance,
2243            token_run: None,
2244            counter: 0,
2245            tokens: Vec::new(),
2246            keys: Vec::new(),
2247            flight: None,
2248            last_put: None,
2249        };
2250        let out = owner.settle(super::Done::default(), false, mint);
2251        (owner, out)
2252    }
2253
2254    /// What a re-mint returns the device to first (v1 §2.12, "A re-mint is
2255    /// a restart"): config.v1's [`super::Owner::restart_plan`] of the owner
2256    /// this one runs.
2257    ///
2258    /// # Errors
2259    ///
2260    /// `(group, parameter)` of a parameter with a running value and no
2261    /// startup value.
2262    pub fn restart_plan(&self) -> Result<Vec<super::Restore>, (String, String)> {
2263        self.inner.restart_plan()
2264    }
2265
2266    /// The config interface.
2267    #[must_use]
2268    pub fn interface(&self) -> &Interface {
2269        &self.iface
2270    }
2271
2272    /// config.v1's owner this one runs: its startup values, its due
2273    /// instants and its published events.
2274    #[must_use]
2275    pub fn inner(&self) -> &super::Owner {
2276        &self.inner
2277    }
2278
2279    /// The instance number.
2280    #[must_use]
2281    pub fn instance(&self) -> u32 {
2282        self.instance
2283    }
2284
2285    /// The deployment epoch its times count from, in seconds.
2286    #[must_use]
2287    pub fn epoch(&self) -> i64 {
2288        self.epoch
2289    }
2290
2291    /// Whether an act is in flight.
2292    #[must_use]
2293    pub fn in_flight(&self) -> bool {
2294        self.inner.in_flight()
2295    }
2296
2297    /// The next instant [`Owner::due`] has something to do.
2298    #[must_use]
2299    pub fn next_due(&self) -> Option<Time> {
2300        self.inner.next_due()
2301    }
2302
2303    /// The record as it stands.
2304    #[must_use]
2305    pub fn state(&self) -> State {
2306        self.render(&self.inner.view(), false)
2307    }
2308
2309    fn token_of(&self, v1: &str) -> u64 {
2310        self.tokens
2311            .iter()
2312            .find(|(t, _)| t == v1)
2313            .map(|(_, n)| *n)
2314            .expect("every config.v1 token is numbered when it appears")
2315    }
2316
2317    /// config.v1's spelling of a request's token: the change's, or one no
2318    /// change of config.v1 has, which matches none.
2319    fn v1_token(&self, token: u64) -> String {
2320        self.tokens
2321            .iter()
2322            .find(|(_, n)| *n == token)
2323            .map_or_else(|| format!("?{token}"), |(t, _)| t.clone())
2324    }
2325
2326    /// Mints a token (§2.6): the run written under, then the counter, a
2327    /// new run before it would pass 65,535.
2328    fn mint_token(&mut self, mint: &mut dyn Mint) -> u64 {
2329        if self.token_run != Some(mint.run()) {
2330            self.token_run = Some(mint.run());
2331            self.counter = mint.counter_start().into();
2332        }
2333        if self.counter > COUNTER_MAX {
2334            mint.next_run();
2335            self.token_run = Some(mint.run());
2336            self.counter = mint.counter_start().into();
2337        }
2338        let token = (u64::from(mint.run().value()) << 16) | u64::from(self.counter);
2339        self.counter += 1;
2340        token
2341    }
2342
2343    fn in_contract_order(&self, groups: &[String]) -> Vec<String> {
2344        self.iface
2345            .groups
2346            .iter()
2347            .filter(|g| groups.contains(&g.name))
2348            .map(|g| g.name.clone())
2349            .collect()
2350    }
2351
2352    fn render(&self, view: &ConfigView, would_be: bool) -> State {
2353        let apply_at = self.inner.apply_at().map(Time::millis);
2354        State {
2355            instance: self.instance,
2356            revision: u32::try_from(view.revision).unwrap_or(u32::MAX),
2357            floor_s: u16::try_from(view.confirm_floor_s).unwrap_or(u16::MAX),
2358            would_be,
2359            pending: view.pending.as_ref().map(|p| Pending {
2360                token: self.token_of(&p.token),
2361                groups: self.in_contract_order(&p.groups),
2362                apply_at,
2363                deadline: self.inner.deadline().map_or(0, Time::millis),
2364                applied: apply_at.is_none(),
2365            }),
2366            last: view.last_change.as_ref().map(|l| Last {
2367                token: self.token_of(&l.token),
2368                groups: self.in_contract_order(&l.groups),
2369            }),
2370            desired: view.desired.as_ref().map(|d| Desired {
2371                outcome: Some(d.outcome),
2372                observed_revision: u32::try_from(d.observed_revision).unwrap_or(u32::MAX),
2373                refusal: d.refusal.as_ref().map(|r| {
2374                    declared(&self.iface, r.code.into(), &r.group, r.parameter.as_deref())
2375                }),
2376            }),
2377            groups: view
2378                .groups
2379                .iter()
2380                .map(|g| {
2381                    let settable = self.iface.groups.settable(&g.name).is_some();
2382                    let params = g
2383                        .parameters
2384                        .iter()
2385                        .map(|p| {
2386                            let s = if p.sensitive {
2387                                ParamState::Sensitive { source: p.source }
2388                            } else {
2389                                ParamState::Plain {
2390                                    source: p.source,
2391                                    differs: p.startup.is_some(),
2392                                    value: p.value.clone(),
2393                                }
2394                            };
2395                            (p.name.clone(), s)
2396                        })
2397                        .collect();
2398                    (
2399                        g.name.clone(),
2400                        GroupState {
2401                            writable: settable.then_some(g.writable),
2402                            params,
2403                        },
2404                    )
2405                })
2406                .collect(),
2407        }
2408    }
2409
2410    fn event(&self, e: &super::ConfigChangeEvent) -> ChangeEvent {
2411        let order = |ed: &Edit| {
2412            self.iface.groups.group(&ed.group).map(|(gi, g)| {
2413                (
2414                    gi,
2415                    g.parameter(&ed.parameter).map_or(usize::MAX, |(pi, _)| pi),
2416                )
2417            })
2418        };
2419        let mut edits = e.edits.clone();
2420        edits.sort_by_key(|ed| order(ed).unwrap_or((usize::MAX, usize::MAX)));
2421        ChangeEvent {
2422            service: e.service.clone(),
2423            instance: self.instance,
2424            revision: e.revision,
2425            token: self.token_of(&e.token),
2426            outcome: e.outcome,
2427            edits,
2428            actor: e.actor.clone(),
2429            request_id: e.request_id.clone(),
2430            claimed_source: e.claimed_source.clone(),
2431        }
2432    }
2433
2434    fn record_bytes(&self, state: &State) -> Vec<u8> {
2435        self.iface
2436            .write_record(state, self.epoch)
2437            .expect("an owner's record is its Record type's: its times within 32 bits of the epoch")
2438            .bytes
2439    }
2440
2441    /// Ends a step config.v1 answered: numbers its new tokens, puts the
2442    /// record when a field of it changed, then the reply under the as-of
2443    /// mark, then the events, each under its own seq (§2.3, §2.9, §2.17).
2444    fn settle(&mut self, done: super::Done, dry_run: bool, mint: &mut dyn Mint) -> Output {
2445        let view = self.inner.view();
2446        let seen: Vec<String> = view
2447            .pending
2448            .iter()
2449            .map(|p| p.token.clone())
2450            .chain(view.last_change.iter().map(|l| l.token.clone()))
2451            .chain(done.events.iter().map(|e| e.token.clone()))
2452            .collect();
2453        for t in seen {
2454            if !self.tokens.iter().any(|(v, _)| *v == t) {
2455                let n = self.mint_token(mint);
2456                self.tokens.push((t, n));
2457            }
2458        }
2459        let events: Vec<ChangeEvent> = done.events.iter().map(|e| self.event(e)).collect();
2460        let mut out = Output::default();
2461        let state = self.render(&view, false);
2462        let bytes = self.record_bytes(&state);
2463        if self.last_put.as_deref() != Some(bytes.as_slice()) {
2464            let stamp = mint.stamp();
2465            let payload =
2466                Envelope::mutation(tag_of(self.iface.derived.record()), stamp, &bytes).write();
2467            out.puts.push(Put {
2468                stamp,
2469                state: state.clone(),
2470                payload,
2471            });
2472            self.last_put = Some(bytes);
2473        }
2474        let keep: Vec<String> = view
2475            .pending
2476            .iter()
2477            .map(|p| p.token.clone())
2478            .chain(view.last_change.iter().map(|l| l.token.clone()))
2479            .collect();
2480        self.tokens.retain(|(t, _)| keep.contains(t));
2481        if let Some(r) = done.reply {
2482            let stamp = mark(mint);
2483            out.reply = Some(match r {
2484                Ok(super::Reply::Set(SetReply::Applied(v))) if dry_run => {
2485                    let would_be = self.render(&v, true);
2486                    self.iface
2487                        .value(&would_be, stamp, self.epoch)
2488                        .expect("a would-be record is its Record type's")
2489                }
2490                Ok(_) => self
2491                    .iface
2492                    .value(&state, stamp, self.epoch)
2493                    .expect("the record was just written"),
2494                Err(e) => self.iface.error(&e, stamp),
2495            });
2496        }
2497        for event in events {
2498            out.events.push(Published {
2499                stamp: mint.stamp(),
2500                event,
2501            });
2502        }
2503        out
2504    }
2505
2506    fn refuse(&self, r: &Refusal, mint: &dyn Mint) -> Output {
2507        Output {
2508            reply: Some(self.iface.error(r, mark(mint))),
2509            ..Output::default()
2510        }
2511    }
2512
2513    fn step(&mut self, step: super::Step, dry_run: bool, mint: &mut dyn Mint) -> Step {
2514        match step {
2515            super::Step::Act(a) => Step::Act(a),
2516            super::Step::Done(d) => Step::Done(self.settle(d, dry_run, mint)),
2517        }
2518    }
2519
2520    fn hold(&mut self, now: Time, key: Option<(u32, String, Vec<u8>)>, out: &Output) {
2521        if let (Some((key, group, payload)), Some(reply)) = (key, &out.reply)
2522            && !self.keys.iter().any(|h| h.key == key)
2523        {
2524            self.keys.push(Held {
2525                key,
2526                group,
2527                payload,
2528                reply: reply.clone(),
2529                at: now,
2530            });
2531        }
2532    }
2533
2534    /// A call to `set/<group>` (§2.5, §2.9): the parse, an act in flight,
2535    /// a key held, then config.v1's rows and its owner; answered now, or an
2536    /// [`Act::Apply`] for a hot group, answered by [`Owner::finish`]. A
2537    /// group with no `set` reaches no queryable: nothing answers.
2538    pub fn set(
2539        &mut self,
2540        now: Time,
2541        group: &str,
2542        payload: &[u8],
2543        call: &Call,
2544        mint: &mut dyn Mint,
2545    ) -> Step {
2546        let Some(parsed) = self.iface.decode_set(group, payload) else {
2547            return Step::Done(Output::default());
2548        };
2549        let set = match parsed {
2550            Ok((s, _)) => s,
2551            Err(r) => return Step::Done(self.refuse(&unparsed(r), mint)),
2552        };
2553        if self.inner.in_flight() {
2554            return Step::Done(self.refuse(&super::in_flight(), mint));
2555        }
2556        self.keys.retain(|h| now.within(h.at, super::KEY_HELD));
2557        if let Some(k) = set.idempotency_key
2558            && let Some(h) = self.keys.iter().find(|h| h.key == k)
2559        {
2560            if h.group == group && h.payload == payload {
2561                return Step::Done(Output {
2562                    reply: Some(h.reply.clone()),
2563                    ..Output::default()
2564                });
2565            }
2566            return Step::Done(self.refuse(
2567                &Refusal::new(
2568                    Code::InvalidRequest,
2569                    Some(Field::member("idempotency_key")),
2570                    "this idempotency key was used for another request within 300 s",
2571                ),
2572                mint,
2573            ));
2574        }
2575        let key = set
2576            .idempotency_key
2577            .map(|k| (k, group.to_owned(), payload.to_vec()));
2578        let req = set.to_v1(|t| self.v1_token(t));
2579        match self.inner.set(now, group, &req, call) {
2580            super::Step::Act(a) => {
2581                self.flight = Some(InFlight { key });
2582                Step::Act(a)
2583            }
2584            super::Step::Done(d) => {
2585                let out = self.settle(d, set.dry_run, mint);
2586                self.hold(now, key, &out);
2587                Step::Done(out)
2588            }
2589        }
2590    }
2591
2592    fn control(
2593        &mut self,
2594        op: ControlOp,
2595        now: Time,
2596        payload: &[u8],
2597        call: &Call,
2598        mint: &mut dyn Mint,
2599    ) -> Step {
2600        let c = match self.iface.decode_control(payload) {
2601            Ok(c) => c,
2602            Err(r) => return Step::Done(self.refuse(&unparsed(r), mint)),
2603        };
2604        let req = c.to_v1(|t| self.v1_token(t));
2605        let step = match op {
2606            ControlOp::Confirm => self.inner.confirm(now, &req, call),
2607            ControlOp::Cancel => self.inner.cancel(now, &req, call),
2608            ControlOp::Extend => self.inner.extend(now, &req, call),
2609            ControlOp::Persist => unreachable!("persist is Owner::persist"),
2610        };
2611        if matches!(step, super::Step::Act(_)) {
2612            self.flight = Some(InFlight { key: None });
2613        }
2614        self.step(step, false, mint)
2615    }
2616
2617    /// `confirm` (§2.10): answered now.
2618    pub fn confirm(&mut self, now: Time, payload: &[u8], call: &Call, mint: &mut dyn Mint) -> Step {
2619        self.control(ControlOp::Confirm, now, payload, call, mint)
2620    }
2621
2622    /// `cancel` (§2.10): an [`Act::Undo`] when something of the change is
2623    /// applied, else answered now.
2624    pub fn cancel(&mut self, now: Time, payload: &[u8], call: &Call, mint: &mut dyn Mint) -> Step {
2625        self.control(ControlOp::Cancel, now, payload, call, mint)
2626    }
2627
2628    /// `extend` (§2.10): answered now, the deadline rounded up.
2629    pub fn extend(&mut self, now: Time, payload: &[u8], call: &Call, mint: &mut dyn Mint) -> Step {
2630        self.control(ControlOp::Extend, now, payload, call, mint)
2631    }
2632
2633    /// Admits a `persist` (§2.13): without a persisted layer `unavailable`
2634    /// before the request is read, then the parse, then config.v1's
2635    /// checks. The runtime writes the plan's entries, then calls
2636    /// [`Owner::persisted`].
2637    ///
2638    /// # Errors
2639    ///
2640    /// The refusal's [`Output`].
2641    pub fn persist(
2642        &mut self,
2643        now: Time,
2644        payload: &[u8],
2645        mint: &mut dyn Mint,
2646    ) -> Result<PersistPlan, Output> {
2647        let req = if self.inner.facts(now).persist {
2648            match self.iface.decode_control(payload) {
2649                Ok(c) => c.to_v1(|t| self.v1_token(t)),
2650                Err(r) => return Err(self.refuse(&unparsed(r), mint)),
2651            }
2652        } else {
2653            ControlRequest::default()
2654        };
2655        self.inner
2656            .persist_plan(now, &req)
2657            .map_err(|r| self.refuse(&r, mint))
2658    }
2659
2660    /// Commits a `persist` whose entries the runtime wrote: the record put
2661    /// when a source moved, then the reply.
2662    pub fn persisted(&mut self, plan: PersistPlan, mint: &mut dyn Mint) -> Output {
2663        let done = self.inner.persisted(plan);
2664        self.settle(done, false, mint)
2665    }
2666
2667    /// The act owed at `now`, if any (§2.9, §2.11): the deadline's undo, or
2668    /// the earliest reach apply whose `apply_at` has come.
2669    pub fn due(&mut self, now: Time, mint: &mut dyn Mint) -> Option<Step> {
2670        let step = self.inner.due(now)?;
2671        Some(self.step(step, false, mint))
2672    }
2673
2674    /// Reports the device's result for the act in flight, and answers what
2675    /// it owed.
2676    pub fn finish(&mut self, now: Time, result: DeviceResult, mint: &mut dyn Mint) -> Step {
2677        let flight = self.flight.take();
2678        match self.inner.finish(now, result) {
2679            super::Step::Act(a) => {
2680                self.flight = flight;
2681                Step::Act(a)
2682            }
2683            super::Step::Done(d) => {
2684                let out = self.settle(d, false, mint);
2685                self.hold(now, flight.and_then(|f| f.key), &out);
2686                Step::Done(out)
2687            }
2688        }
2689    }
2690
2691    /// Sets the desired report the record carries (§2.18), putting the
2692    /// record when it changed.
2693    pub fn report_desired(&mut self, report: Option<DesiredReport>, mint: &mut dyn Mint) -> Output {
2694        self.inner.report_desired(report);
2695        self.settle(super::Done::default(), false, mint)
2696    }
2697
2698    /// What converging `doc` asks next (§2.18): config.v1's, a revision
2699    /// above 32 bits refused whole, naming no group, before any group is
2700    /// read.
2701    #[must_use]
2702    pub fn converge(&self, doc: &DesiredConfig) -> Converge {
2703        let next = self.inner.converge(doc);
2704        if doc.revision > u64::from(u32::MAX) && next != super::Converge::Wait {
2705            return Converge::Refused(DesiredReport {
2706                observed_revision: doc.revision,
2707                outcome: DesiredOutcome::Refused,
2708                refusal: Some(super::DesiredRefusal {
2709                    code: super::DesiredCode::InvalidRequest,
2710                    group: String::new(),
2711                    parameter: None,
2712                }),
2713            });
2714        }
2715        match next {
2716            super::Converge::Wait => Converge::Wait,
2717            super::Converge::Refused(r) => Converge::Refused(r),
2718            super::Converge::Converged(r) => Converge::Converged(r),
2719            super::Converge::Set { group, request } => {
2720                let g = self.iface.groups.settable(&group);
2721                Converge::Set {
2722                    request: Set {
2723                        values: g.map_or_else(BTreeMap::new, |g| {
2724                            g.parameters
2725                                .iter()
2726                                .filter_map(|p| {
2727                                    Some((
2728                                        p.name.clone(),
2729                                        p.value_of(request.values.get(&p.name)?)?,
2730                                    ))
2731                                })
2732                                .collect()
2733                        }),
2734                        ..Set::default()
2735                    },
2736                    group,
2737                }
2738            }
2739        }
2740    }
2741
2742    /// The change events of the last hour, for the next instance.
2743    #[must_use]
2744    pub fn published(&self, now: Time) -> Vec<Time> {
2745        self.inner.published(now)
2746    }
2747}
2748
2749// --- the contract's lint (§2.2, §3) -------------------------------------------------------
2750
2751/// A finding of the contract's lint (§2.2), an error.
2752#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2753pub enum Lint {
2754    /// No resource `config` with `config.groups`.
2755    GroupsMissing,
2756    /// The declaration is invalid.
2757    GroupsInvalid,
2758    /// A resource §3 requires is absent.
2759    ResourceMissing,
2760    /// A resource is not of §3's kind, options or types.
2761    ResourceShape,
2762    /// A type is not its derivation.
2763    ConfigDerivation,
2764    /// `config` has no `freshness.ttl_s` above 0, or the contract does not
2765    /// use `freshness.v2`.
2766    Freshness,
2767    /// A `set` resource of no settable group.
2768    SetNotSettable,
2769    /// `config.groups` on a resource other than `config`.
2770    GroupsPlace,
2771}
2772
2773impl Lint {
2774    /// The fixtures' token.
2775    #[must_use]
2776    pub fn token(self) -> &'static str {
2777        match self {
2778            Self::GroupsMissing => "groups_missing",
2779            Self::GroupsInvalid => "groups_invalid",
2780            Self::ResourceMissing => "resource_missing",
2781            Self::ResourceShape => "resource_shape",
2782            Self::ConfigDerivation => "config_derivation",
2783            Self::Freshness => "freshness",
2784            Self::SetNotSettable => "set_not_settable",
2785            Self::GroupsPlace => "groups_place",
2786        }
2787    }
2788}
2789
2790/// One finding, at a resource's template.
2791#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2792pub struct Finding {
2793    pub at: String,
2794    pub reason: Lint,
2795}
2796
2797/// A type as the lint reads it.
2798#[derive(Debug, Clone, PartialEq, Eq)]
2799pub enum TypeRef {
2800    /// A packed type: its file's stem where known, and its name.
2801    Packed { stem: Option<String>, name: String },
2802    /// A JSON Schema type: its name and its artifact id.
2803    JsonSchema { name: String, schema: String },
2804    /// Any other type.
2805    Other,
2806}
2807
2808/// A resource's body as the lint reads it.
2809#[derive(Debug, Clone, PartialEq, Eq)]
2810pub enum ResBody {
2811    /// A stream, state or event.
2812    Data {
2813        type_: TypeRef,
2814        rate: Option<Rate>,
2815        retention_s: Option<u64>,
2816    },
2817    Operation {
2818        request: TypeRef,
2819        response: TypeRef,
2820        error: Option<TypeRef>,
2821        fanout: Fanout,
2822        idempotent: bool,
2823        serving: Serving,
2824        replies: Replies,
2825    },
2826}
2827
2828/// One resource, resolved (core §9.3), as the lint reads it.
2829#[derive(Debug, Clone, PartialEq)]
2830pub struct Res {
2831    pub template: String,
2832    pub kind: Kind,
2833    /// The template's parameters.
2834    pub params: Vec<String>,
2835    pub optional: bool,
2836    pub annotations: BTreeMap<String, Json>,
2837    pub body: ResBody,
2838}
2839
2840/// A contract as the lint reads it: its `uses`, its resources, and its
2841/// packed files, `(stem, document)`.
2842#[derive(Debug, Clone, PartialEq, Default)]
2843pub struct Resources {
2844    pub uses: Vec<String>,
2845    pub resources: Vec<Res>,
2846    pub packed: Vec<(String, Json)>,
2847}
2848
2849impl Resources {
2850    /// A loaded contract as the lint reads it.
2851    #[must_use]
2852    pub fn of(c: &Contract) -> Self {
2853        Self::of_parts(&c.uses, &c.resources, &c.artifacts)
2854    }
2855
2856    /// A contract's `uses`, resolved resources and artifacts as the lint
2857    /// reads them, before the contract is whole: what the loader asks
2858    /// [`derived_types`] with, for E051 (core §7.6, §9.2).
2859    #[must_use]
2860    pub fn of_parts(
2861        uses: &[IfaceId],
2862        resources: &[contract::Resource],
2863        artifacts: &BTreeMap<String, Artifact>,
2864    ) -> Self {
2865        let tref = |t: &TypeId| match t {
2866            TypeId::Packed { name, schema } => TypeRef::Packed {
2867                stem: artifacts.get(schema).map(|a| a.name.clone()),
2868                name: name.clone(),
2869            },
2870            TypeId::JsonSchema { name, schema } => TypeRef::JsonSchema {
2871                name: name.clone(),
2872                schema: schema.clone(),
2873            },
2874            _ => TypeRef::Other,
2875        };
2876        Self {
2877            uses: uses.iter().map(ToString::to_string).collect(),
2878            resources: resources
2879                .iter()
2880                .map(|r| Res {
2881                    template: r.template.as_str().to_owned(),
2882                    kind: r.kind,
2883                    params: r.params.keys().cloned().collect(),
2884                    optional: r.optional,
2885                    annotations: r.annotations.clone(),
2886                    body: match &r.body {
2887                        ContractBody::Data(d) => ResBody::Data {
2888                            type_: tref(&d.type_),
2889                            rate: d.rate,
2890                            retention_s: d.retention_s,
2891                        },
2892                        ContractBody::Operation(o) => ResBody::Operation {
2893                            request: tref(&o.request),
2894                            response: tref(&o.response),
2895                            error: o.error.as_ref().map(tref),
2896                            fanout: o.fanout,
2897                            idempotent: o.idempotent,
2898                            serving: o.serving,
2899                            replies: o.replies,
2900                        },
2901                    },
2902                })
2903                .collect(),
2904            packed: packed_files_of(artifacts)
2905                .into_iter()
2906                .map(|(s, d)| (s.to_owned(), d.clone()))
2907                .collect(),
2908        }
2909    }
2910
2911    fn resource(&self, template: &str) -> Option<&Res> {
2912        self.resources.iter().find(|r| r.template == template)
2913    }
2914
2915    fn files(&self) -> Vec<(&str, &Json)> {
2916        self.packed.iter().map(|(s, d)| (s.as_str(), d)).collect()
2917    }
2918
2919    /// A packed type's layout: `None` for one no listed file defines once,
2920    /// or whose declaration does not read.
2921    fn layout(&self, t: &TypeRef) -> Option<Layout> {
2922        self.resolved(t).map(|(_, l)| l)
2923    }
2924
2925    /// A packed type's file's stem and its layout, as [`Self::layout`].
2926    fn resolved(&self, t: &TypeRef) -> Option<(String, Layout)> {
2927        let TypeRef::Packed { stem, name } = t else {
2928            return None;
2929        };
2930        let reference = match stem {
2931            Some(s) => format!("packed:{s}#{name}"),
2932            None => format!("packed:{name}"),
2933        };
2934        let files = self.files();
2935        let r = resolve(&reference, &files)?;
2936        let layout = packed::layout_in(r.doc, r.name).ok()?;
2937        Some((r.stem.to_owned(), layout))
2938    }
2939}
2940
2941fn is_packed(t: &TypeRef) -> bool {
2942    matches!(t, TypeRef::Packed { .. })
2943}
2944
2945/// The lint of a contract's resources (§2.2): `groups_missing` or
2946/// `groups_invalid` alone; else, for `config`, each `set/<group>` in the
2947/// groups' order, `confirm`, `cancel`, `extend`, `persist` and `change`,
2948/// `resource_missing`, else `resource_shape`, else `config_derivation`,
2949/// with `freshness` after `config`'s; then `set_not_settable` and
2950/// `groups_place`, each in the byte order of the templates.
2951#[must_use]
2952#[allow(clippy::too_many_lines)]
2953pub fn lint(r: &Resources) -> Vec<Finding> {
2954    let find = |at: &str, reason| Finding {
2955        at: at.to_owned(),
2956        reason,
2957    };
2958    let config = r.resource(CONFIG);
2959    let Some(ann) = config.and_then(|c| c.annotations.get(GROUPS)) else {
2960        return vec![find(CONFIG, Lint::GroupsMissing)];
2961    };
2962    let Ok(iface) = Interface::read(ann, &r.files()) else {
2963        return vec![find(CONFIG, Lint::GroupsInvalid)];
2964    };
2965    let d = &iface.derived;
2966    let same = |t: &TypeRef, want: &Layout| r.layout(t).is_some_and(|l| l.items == want.items);
2967    let mut out = Vec::new();
2968    // `config`.
2969    if let Some(c) = config {
2970        let shaped = c.kind == Kind::State
2971            && !c.optional
2972            && c.params.is_empty()
2973            && matches!(&c.body, ResBody::Data { type_, .. } if is_packed(type_));
2974        if !shaped {
2975            out.push(find(CONFIG, Lint::ResourceShape));
2976        } else if !matches!(&c.body, ResBody::Data { type_, .. } if same(type_, d.record())) {
2977            out.push(find(CONFIG, Lint::ConfigDerivation));
2978        }
2979        let ttl = c
2980            .annotations
2981            .get(crate::freshness::TTL_S)
2982            .and_then(Json::as_f64)
2983            .is_some_and(|t| t > 0.0);
2984        if !ttl || !r.uses.iter().any(|u| u == crate::freshness::PROFILE_V2) {
2985            out.push(find(CONFIG, Lint::Freshness));
2986        }
2987    }
2988    // The operations.
2989    let sets: Vec<(String, &Layout)> = iface
2990        .groups
2991        .iter()
2992        .filter(|g| g.settable())
2993        .filter_map(|g| Some((format!("{}{}", SET_PREFIX, g.name), d.set(&g.name)?.1)))
2994        .collect();
2995    let ops = sets
2996        .iter()
2997        .map(|(t, l)| (t.as_str(), *l))
2998        .chain(CONTROLS.iter().map(|t| (*t, d.control())));
2999    for (template, request) in ops {
3000        let Some(res) = r.resource(template) else {
3001            out.push(find(template, Lint::ResourceMissing));
3002            continue;
3003        };
3004        let ResBody::Operation {
3005            request: req,
3006            response,
3007            error,
3008            fanout,
3009            idempotent,
3010            serving,
3011            replies,
3012        } = &res.body
3013        else {
3014            out.push(find(template, Lint::ResourceShape));
3015            continue;
3016        };
3017        let shaped = res.kind == Kind::Operation
3018            && res.params.is_empty()
3019            && res.optional == (template == super::PERSIST)
3020            && *fanout == Fanout::Forbidden
3021            && !idempotent
3022            && *serving == Serving::Exclusive
3023            && *replies == Replies::One
3024            && is_packed(req)
3025            && is_packed(response)
3026            && error.as_ref().is_some_and(is_packed);
3027        if !shaped {
3028            out.push(find(template, Lint::ResourceShape));
3029        } else if !(same(req, request)
3030            && same(response, d.record())
3031            && error.as_ref().is_some_and(|e| same(e, d.error())))
3032        {
3033            out.push(find(template, Lint::ConfigDerivation));
3034        }
3035    }
3036    // `change`.
3037    match r.resource(CHANGE) {
3038        None => out.push(find(CHANGE, Lint::ResourceMissing)),
3039        Some(c) => {
3040            let shaped = c.kind == Kind::Event
3041                && !c.optional
3042                && c.params.is_empty()
3043                && matches!(&c.body, ResBody::Data { type_: TypeRef::JsonSchema { name, schema }, rate, retention_s }
3044                    if name == EVENT_TYPE
3045                        && schema == STANDARD_SCHEMA
3046                        && *rate == Some(EVENT_RATE)
3047                        && *retention_s == Some(EVENT_RETENTION_S));
3048            if !shaped {
3049                out.push(find(CHANGE, Lint::ResourceShape));
3050            }
3051        }
3052    }
3053    let mut templates: Vec<&str> = r.resources.iter().map(|x| x.template.as_str()).collect();
3054    templates.sort_unstable();
3055    templates.dedup();
3056    for t in &templates {
3057        let set = *t == "set" || t.starts_with(SET_PREFIX);
3058        if set && !sets.iter().any(|(s, _)| s == t) {
3059            out.push(find(t, Lint::SetNotSettable));
3060        }
3061    }
3062    for t in &templates {
3063        if *t != CONFIG
3064            && r.resources
3065                .iter()
3066                .any(|x| x.template == *t && x.annotations.contains_key(GROUPS))
3067        {
3068            out.push(find(t, Lint::GroupsPlace));
3069        }
3070    }
3071    out
3072}
3073
3074/// The `set` operations' template prefix, `set/<group>`.
3075pub const SET_PREFIX: &str = "set/";
3076
3077/// The packed types this profile derives in a contract, each `(stem,
3078/// name)`: the types E051 does not read (core §7.6, "A derived type may be
3079/// 0"; §9.2, cascade 7; config.v2 0.6 §3, "One in 16 has the layout tag 0,
3080/// and E051 does not read it: its author writes no field of it").
3081///
3082/// A type is derived as §3's lint tells one, "field by field": a §3
3083/// resource names it in a derived role, and its layout's items are that
3084/// role's derivation's. The roles: `config`'s type (`Record`); each
3085/// settable group's `set/<group>`'s request (its `Set<T>`), response
3086/// (`Record`) and error (`Error`); and `confirm`, `cancel`, `extend` and
3087/// `persist`'s request (`Control`), response and error. A contract that
3088/// does not use `config.v2`, or whose declaration is invalid, derives none;
3089/// a type no such resource names, or one that differs from its
3090/// derivation, is its author's, and E051 reads it.
3091#[must_use]
3092pub fn derived_types(r: &Resources) -> BTreeSet<(String, String)> {
3093    let mut out = BTreeSet::new();
3094    if !r.uses.iter().any(|u| u == PROFILE) {
3095        return out;
3096    }
3097    let Some(ann) = r.resource(CONFIG).and_then(|c| c.annotations.get(GROUPS)) else {
3098        return out;
3099    };
3100    let Ok(iface) = Interface::read(ann, &r.files()) else {
3101        return out;
3102    };
3103    let d = &iface.derived;
3104    let mut roles: Vec<(&TypeRef, &Layout)> = Vec::new();
3105    if let Some(Res {
3106        body: ResBody::Data { type_, .. },
3107        ..
3108    }) = r.resource(CONFIG)
3109    {
3110        roles.push((type_, d.record()));
3111    }
3112    let sets = iface
3113        .groups
3114        .iter()
3115        .filter(|g| g.settable())
3116        .filter_map(|g| Some((format!("{SET_PREFIX}{}", g.name), d.set(&g.name)?.1)));
3117    let controls = CONTROLS.iter().map(|t| ((*t).to_owned(), d.control()));
3118    for (template, request) in sets.chain(controls) {
3119        if let Some(Res {
3120            body:
3121                ResBody::Operation {
3122                    request: req,
3123                    response,
3124                    error,
3125                    ..
3126                },
3127            ..
3128        }) = r.resource(&template)
3129        {
3130            roles.push((req, request));
3131            roles.push((response, d.record()));
3132            if let Some(e) = error {
3133                roles.push((e, d.error()));
3134            }
3135        }
3136    }
3137    for (t, want) in roles {
3138        if let TypeRef::Packed { name, .. } = t
3139            && let Some((stem, layout)) = r.resolved(t)
3140            && layout.items == want.items
3141        {
3142            out.insert((stem, name.clone()));
3143        }
3144    }
3145    out
3146}
3147
3148/// [`lint`] over a loaded contract that uses `config.v2`; none for any
3149/// other contract.
3150#[must_use]
3151pub fn lint_contract(c: &Contract) -> Vec<Finding> {
3152    if c.uses.iter().any(|u| u.to_string() == PROFILE) {
3153        lint(&Resources::of(c))
3154    } else {
3155        Vec::new()
3156    }
3157}
3158
3159#[cfg(test)]
3160mod tests {
3161    use super::*;
3162
3163    #[test]
3164    fn names_have_the_group_names_form() {
3165        for ok in ["duty", "fraction_ppm", "p0", "a1_b2"] {
3166            assert!(is_name(ok), "{ok}");
3167        }
3168        for bad in ["", "Duty", "tx__queue", "queue_", "_x", "1a", "a-b"] {
3169            assert!(!is_name(bad), "{bad}");
3170        }
3171    }
3172
3173    #[test]
3174    fn times_round_up_to_the_second() {
3175        let t = |ms| Time::from_millis(ms);
3176        assert_eq!(t(1000).ceil_second(), t(1000));
3177        assert_eq!(t(1001).ceil_second(), t(2000));
3178        assert_eq!(t(-1).ceil_second(), t(0));
3179        assert_eq!(deadline(t(300), 5, 10), t(11_000));
3180        assert_eq!(apply_at(t(1300)), t(2000));
3181    }
3182}