Skip to main content

zenkey_model/
config.rs

1//! `config.v1`: changing a running service's configuration
2//! (`spec/profiles/config/v1.md`, #768).
3//!
4//! The profile's session-free half: the wire types of its standard contract
5//! (§3), the validators every owner refuses with (§2.5, §2.10, §2.13,
6//! §2.18), the window (§2.8), redaction (§2.15), and [`Owner`], a pure
7//! state machine of one owner's configuration (§2.6 to §2.17), driven by
8//! explicit calls, device results and instants, which the runtime wraps.
9//!
10//! ```text
11//! validate_set(schema, facts, group, req)  ─▶ Admitted │ Refusal{code, field, app}      §2.5 rows 0, 1, 3–11
12//! validate_control(op, facts, req)         ─▶ ()       │ Refusal                        §2.10, §2.13
13//! decode_set(body), decode_control(body)   ─▶ the request │ Refusal: outside its type, before row 1 (0.3)
14//! check_desired(schema, doc)               ─▶ ()       │ DesiredRefusal{code, group, parameter}   §2.18
15//! window(confirm_s, floor_s), deadline(t, w)                                            §2.8
16//! log_request, device_detail                                                            §2.15
17//!
18//! Owner::set / confirm / cancel / extend ─▶ Step::Done{reply, events} │ Step::Act(Apply │ Undo)
19//! Owner::due(now)                        ─▶ the act owed at now: the deadline's undo, or a reach apply
20//! Owner::finish(now, DeviceResult)       ─▶ the act's outcome: the reply it owed, the events, or a next act
21//! Owner::persist_plan / persisted        ─▶ the last change into the persisted layer
22//! Owner::view / status                   ─▶ ConfigView │ ConfigStatus, its projection (§2.19)
23//! Owner::converge(doc)                   ─▶ Wait │ Refused │ Set{group, request} │ Converged   §2.18
24//! Owner::published(now)                  ─▶ the change events of the last hour, for the next instance §2.17
25//! device_words(schema, act, words)       ─▶ the device's words as a log line may carry them    §2.15
26//! ```
27//!
28//! There is no I/O and no clock here. The runtime receives calls, performs
29//! each [`Act`] on its device, writes the persisted layer, keeps the timers
30//! [`Owner::next_due`] names, and puts what [`Owner::view`],
31//! [`Owner::status`] and the events say.
32//!
33//! [`v2`] is `config.v2`'s half: the schema declared in each adopter's
34//! contract, one packed record, and an owner that runs this one.
35
36use std::collections::BTreeMap;
37use std::fmt;
38use std::time::Duration;
39
40use serde::{Deserialize, Serialize};
41use serde_json::Value as Json;
42
43pub mod v2;
44
45/// The profile's id, which is also its standard contract's interface id.
46pub const PROFILE: &str = "config.v1";
47
48/// The standard contract's interface id (§3).
49pub const IFACE: &str = "config.v1";
50
51/// The read-back's template (§2.3): `state/view`.
52pub const VIEW: &str = "view";
53/// The compact status's template (§2.19): `state/status`.
54pub const STATUS: &str = "status";
55/// The set operation's template (§2.5): `@op/set/{group}`.
56pub const SET: &str = "set/{group}";
57/// `@op/confirm` (§2.10).
58pub const CONFIRM: &str = "confirm";
59/// `@op/cancel` (§2.10).
60pub const CANCEL: &str = "cancel";
61/// `@op/extend` (§2.10).
62pub const EXTEND: &str = "extend";
63/// `@op/persist` (§2.13), optional.
64pub const PERSIST: &str = "persist";
65/// The change event's template (§2.17): `events/change/<occurrence>`.
66pub const CHANGE: &str = "change";
67
68/// The view's and the status's horizon, their `freshness.ttl_s` (§2.3).
69pub const TTL: Duration = Duration::from_secs(60);
70/// The owner's bound between two confirmations of either (`freshness.v1`
71/// §2.4).
72pub const REFRESH: Duration = Duration::from_secs(30);
73/// The contract's bound on a schema's groups, `set/{group}`'s cardinality
74/// (§2.2).
75pub const MAX_GROUPS: usize = 16;
76/// How long an owner keeps an idempotency key's first answer (§2.14).
77pub const KEY_HELD: Duration = Duration::from_secs(300);
78/// The change event's rate, per [`RATE_PERIOD`] (§2.17).
79pub const RATE: usize = 600;
80/// The change event's rate period, an hour (§2.17, core §2.7).
81pub const RATE_PERIOD: Duration = Duration::from_secs(3600);
82/// What a log line writes for a sensitive value (§2.15).
83pub const REDACTED: &str = "<redacted>";
84/// A token's longest form, in characters (§2.6).
85pub const MAX_TOKEN: usize = 64;
86/// An idempotency key's longest form, in characters (§2.14).
87pub const MAX_KEY: usize = 128;
88
89// --- vocabulary (§4) ----------------------------------------------------------
90
91/// A group's class (§2.4).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
93#[serde(rename_all = "lowercase")]
94pub enum Class {
95    /// Takes effect at once; a `set` answers the read-back after the apply.
96    Hot,
97    /// Decides whether the owner reaches the bus: a window or a join is
98    /// required, and the reply goes before the apply.
99    Reach,
100    /// What the owner's transport was started against: refused at runtime.
101    Contract,
102}
103
104impl Class {
105    /// The wire's token.
106    #[must_use]
107    pub fn as_str(self) -> &'static str {
108        match self {
109            Self::Hot => "hot",
110            Self::Reach => "reach",
111            Self::Contract => "contract",
112        }
113    }
114}
115
116/// Where a running value came from (§2.3).
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
118#[serde(rename_all = "lowercase")]
119pub enum Source {
120    /// The owner's built-in default.
121    Default,
122    /// Its startup file.
123    File,
124    /// Its persisted layer (§2.13).
125    Overlay,
126    /// A change in this instance.
127    Runtime,
128}
129
130impl Source {
131    /// The wire's token.
132    #[must_use]
133    pub fn as_str(self) -> &'static str {
134        match self {
135            Self::Default => "default",
136            Self::File => "file",
137            Self::Overlay => "overlay",
138            Self::Runtime => "runtime",
139        }
140    }
141}
142
143/// How a change ended (§2.17).
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "kebab-case")]
146pub enum Outcome {
147    /// Applied without a window, and permanent at once.
148    Applied,
149    /// A pending change kept by `confirm`.
150    Confirmed,
151    /// Undone: by `cancel`, at its deadline, or after its apply failed.
152    RolledBack,
153    /// Its undo failed: the read-back is the truth.
154    Partial,
155}
156
157impl Outcome {
158    /// The wire's token.
159    #[must_use]
160    pub fn as_str(self) -> &'static str {
161        match self {
162            Self::Applied => "applied",
163            Self::Confirmed => "confirmed",
164            Self::RolledBack => "rolled-back",
165            Self::Partial => "partial",
166        }
167    }
168}
169
170/// `ConfigError`'s code, the `app` detail of every operation (§2.5).
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
172#[serde(rename_all = "kebab-case")]
173pub enum ErrorCode {
174    /// A contract group: set it in the startup configuration and restart.
175    RestartRequired,
176    /// The device refused; its words, when they may be carried, in `detail`.
177    DeviceRefused,
178}
179
180impl ErrorCode {
181    /// The wire's token.
182    #[must_use]
183    pub fn as_str(self) -> &'static str {
184        match self {
185            Self::RestartRequired => "restart-required",
186            Self::DeviceRefused => "device-refused",
187        }
188    }
189}
190
191/// Which document a control operation's reply carries (§2.10).
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
193#[serde(rename_all = "lowercase")]
194pub enum Answer {
195    /// The read-back, the default.
196    #[default]
197    View,
198    /// The compact status (§2.19).
199    Status,
200}
201
202/// What an owner did with the last desired document it acted on (§2.18).
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "lowercase")]
205pub enum DesiredOutcome {
206    /// Every value it names is the running value.
207    Converged,
208    /// Refused whole, before anything applied.
209    Refused,
210    /// A `set` made to converge it was refused.
211    Failed,
212}
213
214/// Why a desired document was not converged (§2.18).
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
216pub enum DesiredCode {
217    /// It names a reach group.
218    #[serde(rename = "reach")]
219    Reach,
220    /// It names a contract group.
221    #[serde(rename = "contract")]
222    Contract,
223    /// It names a sensitive parameter.
224    #[serde(rename = "sensitive")]
225    Sensitive,
226    /// A group or a parameter the schema does not declare.
227    #[serde(rename = "not_found")]
228    NotFound,
229    /// A value of the wrong kind or out of bounds.
230    #[serde(rename = "invalid_request")]
231    InvalidRequest,
232    /// A group outside the allowlist.
233    #[serde(rename = "unavailable")]
234    Unavailable,
235    /// For `failed`: the event's rate was spent.
236    #[serde(rename = "busy")]
237    Busy,
238    /// For `failed`: the device refused.
239    #[serde(rename = "device-refused")]
240    DeviceRefused,
241}
242
243impl DesiredCode {
244    /// The wire's token.
245    #[must_use]
246    pub fn as_str(self) -> &'static str {
247        match self {
248            Self::Reach => "reach",
249            Self::Contract => "contract",
250            Self::Sensitive => "sensitive",
251            Self::NotFound => "not_found",
252            Self::InvalidRequest => "invalid_request",
253            Self::Unavailable => "unavailable",
254            Self::Busy => "busy",
255            Self::DeviceRefused => "device-refused",
256        }
257    }
258}
259
260// --- the schema (§2.2) ----------------------------------------------------------
261
262/// A parameter's kind, tagged by `kind` on the wire (§2.2).
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(tag = "kind", rename_all = "lowercase")]
265pub enum Kind {
266    /// `true` or `false`.
267    Bool,
268    /// A signed 64-bit integer, with optional inclusive bounds and a unit.
269    Integer {
270        /// The smallest value accepted, inclusive.
271        #[serde(default, skip_serializing_if = "Option::is_none")]
272        min: Option<i64>,
273        /// The largest value accepted, inclusive.
274        #[serde(default, skip_serializing_if = "Option::is_none")]
275        max: Option<i64>,
276        /// A word for a person: `s`, `By`, `Hz`.
277        #[serde(default, skip_serializing_if = "Option::is_none")]
278        unit: Option<String>,
279    },
280    /// Any string.
281    Text,
282}
283
284/// Why a JSON value is not one of a kind's (§2.5).
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum Misfit {
287    /// Not a value of the kind: `1` for a bool, `2.0` for an integer, `null`.
288    Kind,
289    /// An integer below the declared minimum.
290    Below(i64),
291    /// An integer above the declared maximum.
292    Above(i64),
293    /// An integer beyond the signed 64-bit range.
294    Range,
295}
296
297impl Kind {
298    /// The kind's name on the wire.
299    #[must_use]
300    pub fn as_str(&self) -> &'static str {
301        match self {
302            Self::Bool => "bool",
303            Self::Integer { .. } => "integer",
304            Self::Text => "text",
305        }
306    }
307
308    /// Reads `v` as a value of this kind, within its bounds (§2.5). An
309    /// integer is a JSON number written without a fraction or an exponent.
310    ///
311    /// # Errors
312    ///
313    /// The [`Misfit`].
314    pub fn check(&self, v: &Json) -> Result<Value, Misfit> {
315        match (self, v) {
316            (Self::Bool, Json::Bool(b)) => Ok(Value::Bool(*b)),
317            (Self::Text, Json::String(s)) => Ok(Value::Text(s.clone())),
318            (Self::Integer { min, max, .. }, Json::Number(n)) => {
319                let Some(i) = n.as_i64() else {
320                    return Err(if n.is_u64() {
321                        Misfit::Range
322                    } else {
323                        Misfit::Kind
324                    });
325                };
326                if let Some(m) = min
327                    && i < *m
328                {
329                    return Err(Misfit::Below(*m));
330                }
331                if let Some(m) = max
332                    && i > *m
333                {
334                    return Err(Misfit::Above(*m));
335                }
336                Ok(Value::Integer(i))
337            }
338            _ => Err(Misfit::Kind),
339        }
340    }
341}
342
343/// One parameter a group declares (§2.2).
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345pub struct ParamDecl {
346    /// Its name, unique in its group.
347    pub name: String,
348    /// Its kind.
349    #[serde(flatten)]
350    pub kind: Kind,
351    /// One line for a person.
352    pub description: String,
353    /// Write-only (§2.15).
354    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
355    pub sensitive: bool,
356}
357
358/// One group a schema declares (§2.2).
359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
360pub struct GroupDecl {
361    /// Its name, the `{group}` of `@op/set/{group}`.
362    pub name: String,
363    /// Its class (§2.4).
364    pub class: Class,
365    /// One line for a person.
366    pub description: String,
367    /// Whether the startup allowlist lets a `set` reach it (§2.16).
368    pub writable: bool,
369    /// Its parameters, in the owner's order.
370    pub parameters: Vec<ParamDecl>,
371}
372
373impl GroupDecl {
374    /// The parameter by name, if declared.
375    #[must_use]
376    pub fn parameter(&self, name: &str) -> Option<&ParamDecl> {
377        self.parameters.iter().find(|p| p.name == name)
378    }
379
380    fn is_sensitive(&self, name: &str) -> bool {
381        self.parameter(name).is_none_or(|p| p.sensitive)
382    }
383}
384
385/// An owner's schema: its groups, as the view serves them (§2.2).
386#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
387#[serde(transparent)]
388pub struct Schema {
389    /// The groups, in the owner's order.
390    pub groups: Vec<GroupDecl>,
391}
392
393impl Schema {
394    /// The group by name, if declared. Names compare exactly.
395    #[must_use]
396    pub fn group(&self, name: &str) -> Option<&GroupDecl> {
397        self.groups.iter().find(|g| g.name == name)
398    }
399
400    /// The schema a view serves, without its values: what a tool checks a
401    /// change against before it sends it (§2.5).
402    #[must_use]
403    pub fn of_view(view: &ConfigView) -> Self {
404        Self {
405            groups: view
406                .groups
407                .iter()
408                .map(|g| GroupDecl {
409                    name: g.name.clone(),
410                    class: g.class,
411                    description: g.description.clone(),
412                    writable: g.writable,
413                    parameters: g
414                        .parameters
415                        .iter()
416                        .map(|p| ParamDecl {
417                            name: p.name.clone(),
418                            kind: p.kind.clone(),
419                            description: p.description.clone(),
420                            sensitive: p.sensitive,
421                        })
422                        .collect(),
423                })
424                .collect(),
425        }
426    }
427}
428
429// --- values and time ------------------------------------------------------------------
430
431/// One parameter's value, untagged on the wire: the kind says which (§3).
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(untagged)]
434pub enum Value {
435    /// A `bool`'s.
436    Bool(bool),
437    /// An `integer`'s.
438    Integer(i64),
439    /// A `text`'s.
440    Text(String),
441}
442
443impl fmt::Display for Value {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        match self {
446            Self::Bool(b) => write!(f, "{b}"),
447            Self::Integer(i) => write!(f, "{i}"),
448            Self::Text(t) => write!(f, "{t:?}"),
449        }
450    }
451}
452
453/// An instant on the owner's clock, in milliseconds since the Unix epoch
454/// (§2.8). Negative before 1970.
455#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
456pub struct Time(i64);
457
458impl Time {
459    /// The instant `ms` milliseconds after the Unix epoch.
460    #[must_use]
461    pub const fn from_millis(ms: i64) -> Self {
462        Self(ms)
463    }
464
465    /// Milliseconds since the Unix epoch.
466    #[must_use]
467    pub const fn millis(self) -> i64 {
468        self.0
469    }
470
471    /// The instant `secs` seconds after the epoch, to the millisecond.
472    #[must_use]
473    pub fn from_secs_f64(secs: f64) -> Self {
474        Self((secs * 1000.0).round() as i64)
475    }
476
477    /// This instant plus `d`, saturating.
478    #[must_use]
479    pub fn plus(self, d: Duration) -> Self {
480        Self(
481            self.0
482                .saturating_add(i64::try_from(d.as_millis()).unwrap_or(i64::MAX)),
483        )
484    }
485
486    /// This instant plus `secs` seconds, saturating.
487    #[must_use]
488    pub fn plus_secs(self, secs: u64) -> Self {
489        self.plus(Duration::from_secs(secs))
490    }
491
492    /// The first whole second at or after this instant: itself on a whole
493    /// second, else the next one (`config.v2` §2.8, which rounds a deadline
494    /// and an `apply_at` up so that a window is never shorter than asked).
495    #[must_use]
496    pub fn ceil_second(self) -> Self {
497        let r = self.0.rem_euclid(1000);
498        if r == 0 {
499            self
500        } else {
501            Self(self.0.saturating_add(1000 - r))
502        }
503    }
504
505    /// Whether `self` is less than `d` after `earlier`.
506    fn within(self, earlier: Self, d: Duration) -> bool {
507        i128::from(self.0) - i128::from(earlier.0)
508            < i128::try_from(d.as_millis()).unwrap_or(i128::MAX)
509    }
510
511    /// The owner's spelling (§2.8): RFC 3339 in UTC,
512    /// `YYYY-MM-DDTHH:MM:SS.sssZ`, always three fraction digits.
513    #[must_use]
514    pub fn rfc3339(self) -> String {
515        let days = self.0.div_euclid(86_400_000);
516        let ms = self.0.rem_euclid(86_400_000);
517        let (y, m, d) = civil_from_days(days);
518        let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
519        let (mi, rest) = (rest / 60_000, rest % 60_000);
520        let (s, frac) = (rest / 1000, rest % 1000);
521        format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}.{frac:03}Z")
522    }
523
524    /// Reads any RFC 3339 date-time (§2.8): `Z` or an offset, a fraction of
525    /// any length, kept to the millisecond (truncated). `None` when it is
526    /// not one.
527    #[must_use]
528    pub fn parse(s: &str) -> Option<Self> {
529        let b = s.as_bytes();
530        let num = |r: std::ops::Range<usize>| -> Option<i64> {
531            let t = s.get(r)?;
532            if t.is_empty() || !t.bytes().all(|c| c.is_ascii_digit()) {
533                return None;
534            }
535            t.parse().ok()
536        };
537        if b.len() < 20
538            || b[4] != b'-'
539            || b[7] != b'-'
540            || !matches!(b[10], b'T' | b't')
541            || b[13] != b':'
542            || b[16] != b':'
543        {
544            return None;
545        }
546        let (y, mo, d) = (num(0..4)?, num(5..7)?, num(8..10)?);
547        let (h, mi, sec) = (num(11..13)?, num(14..16)?, num(17..19)?);
548        if !(1..=12).contains(&mo)
549            || d < 1
550            || d > days_in_month(y, mo)
551            || h > 23
552            || mi > 59
553            || sec > 60
554        {
555            return None;
556        }
557        let mut i = 19;
558        let mut ms = 0;
559        if b.get(i) == Some(&b'.') {
560            let start = i + 1;
561            i = start;
562            while b.get(i).is_some_and(u8::is_ascii_digit) {
563                i += 1;
564            }
565            if i == start {
566                return None;
567            }
568            let digits = &s[start..i];
569            let three: String = digits.chars().chain("000".chars()).take(3).collect();
570            ms = three.parse::<i64>().ok()?;
571        }
572        let offset_min = match b.get(i)? {
573            b'Z' | b'z' if i + 1 == b.len() => 0,
574            sign @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
575                let (oh, om) = (num(i + 1..i + 3)?, num(i + 4..i + 6)?);
576                if oh > 23 || om > 59 {
577                    return None;
578                }
579                let o = oh * 60 + om;
580                if *sign == b'-' { -o } else { o }
581            }
582            _ => return None,
583        };
584        let days = days_from_civil(y, mo, d);
585        let secs = days * 86_400 + h * 3600 + mi * 60 + sec - offset_min * 60;
586        Some(Self(secs * 1000 + ms))
587    }
588}
589
590impl fmt::Display for Time {
591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592        f.write_str(&self.rfc3339())
593    }
594}
595
596fn days_in_month(y: i64, m: i64) -> i64 {
597    match m {
598        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
599        4 | 6 | 9 | 11 => 30,
600        _ if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 => 29,
601        _ => 28,
602    }
603}
604
605/// Days since 1970-01-01 of a proleptic Gregorian date (H. Hinnant's
606/// `days_from_civil`).
607fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
608    let y = if m <= 2 { y - 1 } else { y };
609    let era = y.div_euclid(400);
610    let yoe = y - era * 400;
611    let mp = (m + 9) % 12;
612    let doy = (153 * mp + 2) / 5 + d - 1;
613    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
614    era * 146_097 + doe - 719_468
615}
616
617/// The date of a day count since 1970-01-01 (`civil_from_days`).
618fn civil_from_days(z: i64) -> (i64, i64, i64) {
619    let z = z + 719_468;
620    let era = z.div_euclid(146_097);
621    let doe = z - era * 146_097;
622    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
623    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
624    let mp = (5 * doy + 2) / 153;
625    let d = doy - (153 * mp + 2) / 5 + 1;
626    let m = if mp < 10 { mp + 3 } else { mp - 9 };
627    let y = yoe + era * 400 + i64::from(m <= 2);
628    (y, m, d)
629}
630
631/// The window of a `confirm_s`, raised to the floor: `max(confirm_s,
632/// floor_s)` seconds (§2.8).
633#[must_use]
634pub fn window(confirm_s: u64, floor_s: u64) -> u64 {
635    confirm_s.max(floor_s)
636}
637
638/// The deadline of a window counted from `received` (§2.8).
639#[must_use]
640pub fn deadline(received: Time, window_s: u64) -> Time {
641    received.plus_secs(window_s)
642}
643
644// --- the wire types (§3) --------------------------------------------------------------
645
646/// One parameter as the view shows it (§2.3): its declaration, and what the
647/// owner runs with. A sensitive parameter never carries `value` or
648/// `startup`.
649#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
650pub struct Parameter {
651    /// Its name.
652    pub name: String,
653    /// Its kind, with an integer's bounds and unit.
654    #[serde(flatten)]
655    pub kind: Kind,
656    /// One line for a person.
657    pub description: String,
658    /// Write-only (§2.15).
659    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
660    pub sensitive: bool,
661    /// The running value; absent when sensitive or unknown.
662    #[serde(default, skip_serializing_if = "Option::is_none")]
663    pub value: Option<Value>,
664    /// Where the running value came from.
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub source: Option<Source>,
667    /// What a restart would run with, when it differs from a known running
668    /// value; never for a sensitive parameter.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub startup: Option<Value>,
671}
672
673/// One group as the view shows it (§2.2).
674#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
675pub struct GroupView {
676    /// Its name.
677    pub name: String,
678    /// Its class.
679    pub class: Class,
680    /// One line for a person.
681    pub description: String,
682    /// Whether the allowlist lets a `set` reach it (§2.16).
683    pub writable: bool,
684    /// Its parameters, in the owner's order.
685    pub parameters: Vec<Parameter>,
686}
687
688/// The pending change, as the view and the status show it (§2.7, §2.9).
689#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
690pub struct Pending {
691    /// Its token.
692    pub token: String,
693    /// Its groups, in the order they first joined.
694    pub groups: Vec<String>,
695    /// When its undo runs, on the owner's clock (§2.8).
696    pub deadline: String,
697    /// Whether every group of it is applied.
698    pub applied: bool,
699}
700
701/// The last change made permanent in this instance (§2.6).
702#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703pub struct LastChange {
704    /// Its token.
705    pub token: String,
706    /// Its groups.
707    pub groups: Vec<String>,
708}
709
710/// Why a desired document was not converged, and where (§2.18).
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
712pub struct DesiredRefusal {
713    /// The code.
714    pub code: DesiredCode,
715    /// The group.
716    pub group: String,
717    /// The parameter, for a parameter's check.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub parameter: Option<String>,
720}
721
722/// What the owner did with the last desired document it acted on (§2.18).
723#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
724pub struct DesiredReport {
725    /// The document's revision.
726    pub observed_revision: u64,
727    /// Converged, refused or failed.
728    pub outcome: DesiredOutcome,
729    /// Why, for refused and failed.
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub refusal: Option<DesiredRefusal>,
732}
733
734/// The read-back, `state/view` (§2.3).
735#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
736pub struct ConfigView {
737    /// The owner's address, `<system>/<service>`.
738    pub service: String,
739    /// Its instance id.
740    pub instance: String,
741    /// The count of acts that moved its running values.
742    pub revision: u64,
743    /// Its floor, in seconds (§2.8).
744    pub confirm_floor_s: u64,
745    /// The pending change, if any.
746    #[serde(default, skip_serializing_if = "Option::is_none")]
747    pub pending: Option<Pending>,
748    /// The last change, if any.
749    #[serde(default, skip_serializing_if = "Option::is_none")]
750    pub last_change: Option<LastChange>,
751    /// The desired report, for an owner that converges desired state.
752    #[serde(default, skip_serializing_if = "Option::is_none")]
753    pub desired: Option<DesiredReport>,
754    /// The groups.
755    pub groups: Vec<GroupView>,
756}
757
758/// The compact status, `state/status`: the view's projection (§2.19).
759#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
760pub struct ConfigStatus {
761    /// The instance id.
762    pub instance: String,
763    /// The revision.
764    pub revision: u64,
765    /// The floor, in seconds.
766    pub confirm_floor_s: u64,
767    /// The pending change, if any.
768    #[serde(default, skip_serializing_if = "Option::is_none")]
769    pub pending: Option<Pending>,
770    /// The last change, if any.
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub last_change: Option<LastChange>,
773    /// The desired report, if any.
774    #[serde(default, skip_serializing_if = "Option::is_none")]
775    pub desired: Option<DesiredReport>,
776    /// The values by group and name: no sensitive or unknown value, and no
777    /// group left without one.
778    pub values: BTreeMap<String, BTreeMap<String, Value>>,
779}
780
781impl ConfigStatus {
782    /// The status a view projects to (§2.19).
783    #[must_use]
784    pub fn of(view: &ConfigView) -> Self {
785        let mut values = BTreeMap::new();
786        for g in &view.groups {
787            let shown: BTreeMap<String, Value> = g
788                .parameters
789                .iter()
790                .filter(|p| !p.sensitive)
791                .filter_map(|p| p.value.clone().map(|v| (p.name.clone(), v)))
792                .collect();
793            if !shown.is_empty() {
794                values.insert(g.name.clone(), shown);
795            }
796        }
797        Self {
798            instance: view.instance.clone(),
799            revision: view.revision,
800            confirm_floor_s: view.confirm_floor_s,
801            pending: view.pending.clone(),
802            last_change: view.last_change.clone(),
803            desired: view.desired.clone(),
804            values,
805        }
806    }
807}
808
809/// The body of `@op/set/{group}` (§2.5). Its values stay JSON until the
810/// validator reads them against the schema, so a value of the wrong kind is
811/// row 11's refusal, naming its parameter.
812#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
813pub struct SetRequest {
814    /// Values for some parameters of the group.
815    pub values: BTreeMap<String, Json>,
816    /// The window, in seconds, at least 1.
817    #[serde(default, skip_serializing_if = "Option::is_none")]
818    pub confirm_s: Option<u64>,
819    /// The pending change's token, to join it.
820    #[serde(default, skip_serializing_if = "Option::is_none")]
821    pub token: Option<String>,
822    /// The revision the caller read.
823    #[serde(default, skip_serializing_if = "Option::is_none")]
824    pub expected_revision: Option<u64>,
825    /// A key that makes a retry return the first answer (§2.14).
826    #[serde(default, skip_serializing_if = "Option::is_none")]
827    pub idempotency_key: Option<String>,
828    /// Check, and answer the would-be view, touching nothing.
829    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
830    pub dry_run: bool,
831}
832
833/// A reach `set`'s reply, before the apply (§2.9).
834#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
835pub struct PendingReply {
836    /// The change's token.
837    pub token: String,
838    /// When the group applies, on the owner's clock.
839    pub apply_at: String,
840    /// When the change rolls back unless confirmed.
841    pub deadline: String,
842}
843
844/// The reply to a `set` (§2.9, §3): `{applied: ConfigView}` or `{pending:
845/// PendingReply}`.
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(rename_all = "lowercase")]
848pub enum SetReply {
849    /// The read-back after the apply, or a dry run's would-be read-back.
850    Applied(Box<ConfigView>),
851    /// A reach group's pending reply.
852    Pending(PendingReply),
853}
854
855/// The body of `confirm`, `cancel`, `extend` and `persist` (§2.10).
856#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
857pub struct ControlRequest {
858    /// The change's token.
859    pub token: String,
860    /// For `extend` alone: the new window from now, in seconds.
861    #[serde(default, skip_serializing_if = "Option::is_none")]
862    pub confirm_s: Option<u64>,
863    /// The document the reply carries, the view by default.
864    #[serde(default, skip_serializing_if = "Option::is_none")]
865    pub answer: Option<Answer>,
866}
867
868/// The reply to a control operation (§2.10): `{view: ConfigView}` or
869/// `{status: ConfigStatus}`.
870#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
871#[serde(rename_all = "lowercase")]
872pub enum ControlReply {
873    /// The read-back after the act.
874    View(Box<ConfigView>),
875    /// The compact status after the act.
876    Status(Box<ConfigStatus>),
877}
878
879/// One parameter a change set, in its event (§2.17).
880#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
881pub struct Edit {
882    /// Its group.
883    pub group: String,
884    /// Its name.
885    pub parameter: String,
886    /// Its value before the change; absent when unknown or redacted.
887    #[serde(default, skip_serializing_if = "Option::is_none")]
888    pub old: Option<Value>,
889    /// The value the change set; absent when redacted.
890    #[serde(default, skip_serializing_if = "Option::is_none")]
891    pub new: Option<Value>,
892    /// A sensitive parameter's edit, with neither value.
893    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
894    pub redacted: bool,
895}
896
897/// One change as it ended, `events/change/<occurrence>` (§2.17).
898#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
899pub struct ConfigChangeEvent {
900    /// The owner's address.
901    pub service: String,
902    /// Its instance id.
903    pub instance: String,
904    /// The revision after the act that ended the change.
905    pub revision: u64,
906    /// The change's token.
907    pub token: String,
908    /// How it ended.
909    pub outcome: Outcome,
910    /// Its edits.
911    pub edits: Vec<Edit>,
912    /// The actor the `set` that started it claimed (core O7).
913    #[serde(default, skip_serializing_if = "Option::is_none")]
914    pub actor: Option<String>,
915    /// The request id it claimed.
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub request_id: Option<String>,
918    /// Where the call came from, best effort, unauthenticated.
919    #[serde(default, skip_serializing_if = "Option::is_none")]
920    pub claimed_source: Option<String>,
921}
922
923/// The `app` detail of every operation (§2.5).
924#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
925pub struct ConfigError {
926    /// `restart-required` or `device-refused`.
927    pub code: ErrorCode,
928    /// For a person: the device's own words, when they may be carried.
929    #[serde(default, skip_serializing_if = "Option::is_none")]
930    pub detail: Option<String>,
931}
932
933/// A desired document for a `config.v1` owner (§2.18). Its values stay JSON
934/// until [`check_desired`] reads them.
935#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
936pub struct DesiredConfig {
937    /// The author's revision.
938    pub revision: u64,
939    /// Values by group and parameter.
940    pub values: BTreeMap<String, BTreeMap<String, Json>>,
941}
942
943// --- refusals ---------------------------------------------------------------------------
944
945/// The core §5.2 code of a refusal this profile makes. `fanout_forbidden`
946/// and `internal` are the runtime's.
947#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
948pub enum Code {
949    /// `invalid_request`.
950    InvalidRequest,
951    /// `not_found`.
952    NotFound,
953    /// `unavailable`, always with cause `config` here.
954    Unavailable,
955    /// `forbidden`.
956    Forbidden,
957    /// `busy`.
958    Busy,
959    /// `app`, with a [`ConfigError`].
960    App,
961}
962
963impl Code {
964    /// The error's code.
965    #[must_use]
966    pub fn as_str(self) -> &'static str {
967        match self {
968            Self::InvalidRequest => "invalid_request",
969            Self::NotFound => "not_found",
970            Self::Unavailable => "unavailable",
971            Self::Forbidden => "forbidden",
972            Self::Busy => "busy",
973            Self::App => "app",
974        }
975    }
976}
977
978/// What a refusal is about, as the fixtures name it.
979#[derive(Debug, Clone, PartialEq, Eq, Hash)]
980pub enum Field {
981    /// The key's `{group}`.
982    Group,
983    /// A member of the request, as a JSON pointer (RFC 6901).
984    Member(String),
985}
986
987impl Field {
988    /// `"group"`, or the pointer.
989    #[must_use]
990    pub fn as_str(&self) -> &str {
991        match self {
992            Self::Group => "group",
993            Self::Member(p) => p,
994        }
995    }
996
997    fn member(name: &str) -> Self {
998        Self::Member(format!("/{name}"))
999    }
1000
1001    fn value(name: &str) -> Self {
1002        Self::Member(format!(
1003            "/values/{}",
1004            name.replace('~', "~0").replace('/', "~1")
1005        ))
1006    }
1007}
1008
1009/// A refusal, before or after an act: the error's code, its `app`
1010/// detail, what it is about, and a message for a person that never carries
1011/// a sensitive value (§2.15).
1012#[derive(Debug, Clone, PartialEq, Eq)]
1013pub struct Refusal {
1014    /// The code.
1015    pub code: Code,
1016    /// The `ConfigError`, with [`Code::App`] alone.
1017    pub app: Option<ConfigError>,
1018    /// What the refusal is about: `None` for the owner's state or the
1019    /// operation.
1020    pub field: Option<Field>,
1021    /// For a person, never parsed.
1022    pub message: String,
1023}
1024
1025impl Refusal {
1026    fn new(code: Code, field: Option<Field>, message: impl Into<String>) -> Self {
1027        Self {
1028            code,
1029            app: None,
1030            field,
1031            message: message.into(),
1032        }
1033    }
1034
1035    fn app(code: ErrorCode, detail: Option<String>, message: impl Into<String>) -> Self {
1036        Self {
1037            code: Code::App,
1038            app: Some(ConfigError { code, detail }),
1039            field: Some(Field::Group),
1040            message: message.into(),
1041        }
1042    }
1043
1044    fn busy(message: impl Into<String>) -> Self {
1045        Self::new(Code::Busy, None, message)
1046    }
1047
1048    /// The error's cause: `config` for `unavailable`, else none.
1049    #[must_use]
1050    pub fn cause(&self) -> Option<&'static str> {
1051        (self.code == Code::Unavailable).then_some("config")
1052    }
1053}
1054
1055impl fmt::Display for Refusal {
1056    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1057        write!(f, "{}: {}", self.code.as_str(), self.message)
1058    }
1059}
1060
1061impl std::error::Error for Refusal {}
1062
1063// --- the validators (§2.5, §2.10, §2.13, §2.18) ----------------------------------------
1064
1065/// What a validator needs of the owner's state.
1066#[derive(Debug, Clone, Copy, Default)]
1067pub struct Facts<'a> {
1068    /// The revision.
1069    pub revision: u64,
1070    /// The pending change, if any.
1071    pub pending: Option<PendingFacts<'a>>,
1072    /// The last change, if any.
1073    pub last_change: Option<LastFacts<'a>>,
1074    /// Whether the owner has a persisted layer.
1075    pub persist: bool,
1076    /// Whether an act is in flight.
1077    pub in_flight: bool,
1078}
1079
1080/// The pending change, as a validator reads it.
1081#[derive(Debug, Clone, Copy)]
1082pub struct PendingFacts<'a> {
1083    /// Its token.
1084    pub token: &'a str,
1085    /// Whether every group of it is applied.
1086    pub applied: bool,
1087    /// Whether its deadline has passed with its undo not yet run.
1088    pub deadline_passed: bool,
1089}
1090
1091/// The last change, as `persist` reads it.
1092#[derive(Debug, Clone, Copy)]
1093pub struct LastFacts<'a> {
1094    /// Its token.
1095    pub token: &'a str,
1096    /// Whether it set a sensitive parameter.
1097    pub set_sensitive: bool,
1098}
1099
1100/// A `set` that passed §2.5's rows 0, 1 and 3 to 11.
1101#[derive(Debug, Clone, PartialEq, Eq)]
1102pub struct Admitted {
1103    /// The group's class.
1104    pub class: Class,
1105    /// The values, read against their kinds.
1106    pub values: BTreeMap<String, Value>,
1107    /// Whether it joins the pending change.
1108    pub joins: bool,
1109    /// Whether it is a dry run.
1110    pub dry_run: bool,
1111}
1112
1113/// A control operation (§2.10, §2.13).
1114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1115pub enum ControlOp {
1116    /// `confirm`.
1117    Confirm,
1118    /// `cancel`.
1119    Cancel,
1120    /// `extend`.
1121    Extend,
1122    /// `persist`.
1123    Persist,
1124}
1125
1126impl ControlOp {
1127    /// The operation's template.
1128    #[must_use]
1129    pub fn as_str(self) -> &'static str {
1130        match self {
1131            Self::Confirm => CONFIRM,
1132            Self::Cancel => CANCEL,
1133            Self::Extend => EXTEND,
1134            Self::Persist => PERSIST,
1135        }
1136    }
1137}
1138
1139fn too_long(s: &str, max: usize) -> bool {
1140    s.is_empty() || s.chars().count() > max
1141}
1142
1143/// Whether `v` is a `ParamValue`, the type of `SetRequest`'s values (§3):
1144/// a boolean, a string, or an integer as JSON Schema reads one, a number
1145/// with no fractional part. `2.0` and an integer beyond 64 bits are; row 11
1146/// then refuses them against the parameter's kind (§2.5, text 0.2, F-107).
1147fn is_param_value(v: &Json) -> bool {
1148    match v {
1149        Json::Bool(_) | Json::String(_) => true,
1150        Json::Number(n) => {
1151            n.is_i64()
1152                || n.is_u64()
1153                || n.as_f64()
1154                    .is_some_and(|f| f.is_finite() && f.fract() == 0.0)
1155        }
1156        _ => false,
1157    }
1158}
1159
1160/// The request's own type, before row 1 (§2.5): its members in the
1161/// bytewise order of their names, `values` last, and in it the first value
1162/// outside `ParamValue` by name (text 0.2, F-107).
1163fn check_set_shape(req: &SetRequest) -> Result<(), Refusal> {
1164    if req.confirm_s == Some(0) {
1165        return Err(Refusal::new(
1166            Code::InvalidRequest,
1167            Some(Field::member("confirm_s")),
1168            "confirm_s is a window of at least 1 s",
1169        ));
1170    }
1171    if let Some(k) = &req.idempotency_key
1172        && too_long(k, MAX_KEY)
1173    {
1174        return Err(Refusal::new(
1175            Code::InvalidRequest,
1176            Some(Field::member("idempotency_key")),
1177            format!("an idempotency key is 1 to {MAX_KEY} characters"),
1178        ));
1179    }
1180    if let Some(t) = &req.token
1181        && too_long(t, MAX_TOKEN)
1182    {
1183        return Err(Refusal::new(
1184            Code::InvalidRequest,
1185            Some(Field::member("token")),
1186            format!("a token is 1 to {MAX_TOKEN} characters"),
1187        ));
1188    }
1189    if let Some((name, _)) = req.values.iter().find(|(_, v)| !is_param_value(v)) {
1190        return Err(Refusal::new(
1191            Code::InvalidRequest,
1192            Some(Field::value(name)),
1193            format!(
1194                "{name}: not a boolean, an integer or a string, so outside the request's type \
1195                 (SetRequest's ParamValue)"
1196            ),
1197        ));
1198    }
1199    Ok(())
1200}
1201
1202/// A control request's own type, in the bytewise order of its members'
1203/// names, as §2.5 takes a set's (§2.10; text 0.3): `confirm_s` before
1204/// `token`. `answer` is its decode's.
1205fn check_control_shape(req: &ControlRequest) -> Result<(), Refusal> {
1206    if req.confirm_s == Some(0) {
1207        return Err(Refusal::new(
1208            Code::InvalidRequest,
1209            Some(Field::member("confirm_s")),
1210            "confirm_s is a window of at least 1 s",
1211        ));
1212    }
1213    if too_long(&req.token, MAX_TOKEN) {
1214        return Err(Refusal::new(
1215            Code::InvalidRequest,
1216            Some(Field::member("token")),
1217            format!("a token is 1 to {MAX_TOKEN} characters"),
1218        ));
1219    }
1220    Ok(())
1221}
1222
1223/// Whether `v` is an unsigned integer as core §3.3 reads one: a JSON number
1224/// written without a fraction or an exponent, within the unsigned 64-bit
1225/// range. `30.0`, `3e1` and `2^64` are integers to JSON Schema, and not
1226/// this (text 0.3, F-115).
1227fn is_u64(v: &Json) -> bool {
1228    v.as_number().is_some_and(serde_json::Number::is_u64)
1229}
1230
1231/// A request member's own check, before row 1 (§2.5, "A request outside its
1232/// type"; text 0.3, F-115): the member's JSON form against its type.
1233fn member_fits(name: &str, v: &Json) -> Result<(), Refusal> {
1234    let refuse = |why: String| {
1235        Err(Refusal::new(
1236            Code::InvalidRequest,
1237            Some(Field::member(name)),
1238            why,
1239        ))
1240    };
1241    match name {
1242        "confirm_s" if !(is_u64(v) && v.as_u64() != Some(0)) => refuse(
1243            "confirm_s is a window of at least 1 s, an integer written without a fraction or an \
1244             exponent"
1245                .to_owned(),
1246        ),
1247        "expected_revision" if !is_u64(v) => refuse(
1248            "expected_revision is a revision, an unsigned integer written without a fraction or \
1249             an exponent"
1250                .to_owned(),
1251        ),
1252        "dry_run" if !v.is_boolean() => refuse("dry_run is true or false".to_owned()),
1253        "idempotency_key" if !v.as_str().is_some_and(|k| !too_long(k, MAX_KEY)) => {
1254            refuse(format!("an idempotency key is 1 to {MAX_KEY} characters"))
1255        }
1256        "token" if !v.as_str().is_some_and(|t| !too_long(t, MAX_TOKEN)) => {
1257            refuse(format!("a token is 1 to {MAX_TOKEN} characters"))
1258        }
1259        "answer" if !matches!(v.as_str(), Some("view" | "status")) => {
1260            refuse("answer is view or status".to_owned())
1261        }
1262        _ => Ok(()),
1263    }
1264}
1265
1266/// Decodes a `set`'s body as a `SetRequest`, refusing a request outside its
1267/// type as §2.5 orders it, before row 1: its members in the bytewise order
1268/// of their names, `values` last, and in `values` the first value outside
1269/// `ParamValue` by name. A member it does not know is ignored (§3: each
1270/// type is an open object). `confirm_s` and `expected_revision` are read as
1271/// core §3.3 reads an integer, so `30.0` is outside the type, though a
1272/// `2.0` in `values` is a `ParamValue` row 11 refuses (text 0.3, F-115).
1273///
1274/// # Errors
1275///
1276/// The first [`Refusal`], `invalid_request` naming the member.
1277pub fn decode_set(body: &Json) -> Result<SetRequest, Refusal> {
1278    let Some(members) = body.as_object() else {
1279        return Err(Refusal::new(
1280            Code::InvalidRequest,
1281            None,
1282            "a SetRequest is a JSON object",
1283        ));
1284    };
1285    let mut names: Vec<&String> = members.keys().filter(|k| *k != "values").collect();
1286    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
1287    for name in names {
1288        member_fits(name, &members[name])?;
1289    }
1290    let Some(values) = members.get("values").and_then(Json::as_object) else {
1291        return Err(Refusal::new(
1292            Code::InvalidRequest,
1293            Some(Field::member("values")),
1294            "values is an object of parameter values",
1295        ));
1296    };
1297    let mut names: Vec<&String> = values.keys().collect();
1298    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
1299    if let Some(name) = names.into_iter().find(|n| !is_param_value(&values[*n])) {
1300        return Err(Refusal::new(
1301            Code::InvalidRequest,
1302            Some(Field::value(name)),
1303            format!(
1304                "{name}: not a boolean, an integer or a string, so outside the request's type \
1305                 (SetRequest's ParamValue)"
1306            ),
1307        ));
1308    }
1309    serde_json::from_value(body.clone())
1310        .map_err(|e| Refusal::new(Code::InvalidRequest, None, format!("not a SetRequest: {e}")))
1311}
1312
1313/// Decodes a control operation's body as a `ControlRequest`, refusing one
1314/// outside its type in the bytewise order of its members' names (§2.10,
1315/// "as §2.5 says of a set"; text 0.3).
1316///
1317/// # Errors
1318///
1319/// The first [`Refusal`], `invalid_request` naming the member.
1320pub fn decode_control(body: &Json) -> Result<ControlRequest, Refusal> {
1321    let Some(members) = body.as_object() else {
1322        return Err(Refusal::new(
1323            Code::InvalidRequest,
1324            None,
1325            "a ControlRequest is a JSON object",
1326        ));
1327    };
1328    if !members.contains_key("token") {
1329        return Err(Refusal::new(
1330            Code::InvalidRequest,
1331            Some(Field::member("token")),
1332            format!("a token is 1 to {MAX_TOKEN} characters"),
1333        ));
1334    }
1335    let mut names: Vec<&String> = members.keys().collect();
1336    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
1337    for name in names {
1338        member_fits(name, &members[name])?;
1339    }
1340    serde_json::from_value(body.clone()).map_err(|e| {
1341        Refusal::new(
1342            Code::InvalidRequest,
1343            None,
1344            format!("not a ControlRequest: {e}"),
1345        )
1346    })
1347}
1348
1349/// [`validate_set`] over a body as it arrived: [`decode_set`], then the
1350/// rows.
1351///
1352/// # Errors
1353///
1354/// The first [`Refusal`] that applies.
1355pub fn validate_set_json(
1356    schema: &Schema,
1357    facts: &Facts<'_>,
1358    group: &str,
1359    body: &Json,
1360) -> Result<Admitted, Refusal> {
1361    let req = decode_set(body)?;
1362    validate_set(schema, facts, group, &req)
1363}
1364
1365/// [`validate_control`] over a body as it arrived: `persist`'s missing
1366/// persisted layer first (§2.13, row 1: before the request's type), then
1367/// [`decode_control`], then the rest.
1368///
1369/// # Errors
1370///
1371/// The first [`Refusal`] that applies.
1372pub fn validate_control_json(op: ControlOp, facts: &Facts<'_>, body: &Json) -> Result<(), Refusal> {
1373    if op == ControlOp::Persist && !facts.persist {
1374        return validate_control(op, facts, &ControlRequest::default());
1375    }
1376    let req = decode_control(body)?;
1377    validate_control(op, facts, &req)
1378}
1379
1380fn in_flight() -> Refusal {
1381    Refusal::busy("an act is in flight on this service's device; call again once it ends")
1382}
1383
1384fn misfit_message(p: &ParamDecl, why: Misfit, v: &Json) -> String {
1385    let unit = match &p.kind {
1386        Kind::Integer { unit: Some(u), .. } => format!(" {u}"),
1387        _ => String::new(),
1388    };
1389    let shown = if p.sensitive {
1390        String::new()
1391    } else {
1392        format!(", got {v}")
1393    };
1394    match why {
1395        Misfit::Kind => format!(
1396            "{}: expected a value of kind {}{shown}",
1397            p.name,
1398            p.kind.as_str()
1399        ),
1400        Misfit::Below(m) => format!("{}: below the minimum of {m}{unit}{shown}", p.name),
1401        Misfit::Above(m) => format!("{}: above the maximum of {m}{unit}{shown}", p.name),
1402        Misfit::Range => format!("{}: beyond the signed 64-bit range{shown}", p.name),
1403    }
1404}
1405
1406/// §2.5's rows 3 to 11: what a `set` is refused for by the schema and the
1407/// state, before the rate, a reach join's deadline and the device.
1408fn check_rows(
1409    schema: &Schema,
1410    facts: &Facts<'_>,
1411    group: &str,
1412    req: &SetRequest,
1413) -> Result<Admitted, Refusal> {
1414    let Some(g) = schema.group(group) else {
1415        return Err(Refusal::new(
1416            Code::NotFound,
1417            Some(Field::Group),
1418            format!("no group {group:?}: the view names every group this service accepts"),
1419        ));
1420    };
1421    if !g.writable {
1422        return Err(Refusal::new(
1423            Code::Unavailable,
1424            Some(Field::Group),
1425            format!("group {group:?} is outside this service's startup allowlist"),
1426        ));
1427    }
1428    if let Some(p) = &facts.pending
1429        && (req.token.as_deref() != Some(p.token) || p.deadline_passed)
1430    {
1431        return Err(Refusal::busy(format!(
1432            "a change is pending on this service (token {}); confirm, cancel or extend it, or carry its token",
1433            p.token
1434        )));
1435    }
1436    if req.token.is_some() && facts.pending.is_none() {
1437        return Err(Refusal::new(
1438            Code::NotFound,
1439            Some(Field::member("token")),
1440            "no change is pending: the token names nothing",
1441        ));
1442    }
1443    if let Some(e) = req.expected_revision
1444        && e != facts.revision
1445    {
1446        return Err(Refusal::new(
1447            Code::InvalidRequest,
1448            Some(Field::member("expected_revision")),
1449            format!(
1450                "the change expects revision {e} and the view is at {}; read it back and decide again",
1451                facts.revision
1452            ),
1453        ));
1454    }
1455    if g.class == Class::Contract {
1456        return Err(Refusal::app(
1457            ErrorCode::RestartRequired,
1458            None,
1459            format!(
1460                "group {group:?} is part of what this service was started against; set it in its startup \
1461                 configuration and restart"
1462            ),
1463        ));
1464    }
1465    if req.token.is_some() && req.confirm_s.is_some() {
1466        return Err(Refusal::new(
1467            Code::InvalidRequest,
1468            Some(Field::member("confirm_s")),
1469            "a change joining a pending one takes its window; drop confirm_s (extend moves the deadline)",
1470        ));
1471    }
1472    if g.class == Class::Reach && req.confirm_s.is_none() && req.token.is_none() && !req.dry_run {
1473        return Err(Refusal::new(
1474            Code::InvalidRequest,
1475            Some(Field::member("confirm_s")),
1476            format!(
1477                "group {group:?} can cut the link this reply travels on; send it with a window (confirm_s) and \
1478                 confirm over the new link"
1479            ),
1480        ));
1481    }
1482    let mut values = BTreeMap::new();
1483    for (name, v) in &req.values {
1484        let Some(p) = g.parameter(name) else {
1485            return Err(Refusal::new(
1486                Code::NotFound,
1487                Some(Field::value(name)),
1488                format!("group {group:?} declares no parameter {name:?}"),
1489            ));
1490        };
1491        match p.kind.check(v) {
1492            Ok(value) => {
1493                values.insert(name.clone(), value);
1494            }
1495            Err(why) => {
1496                return Err(Refusal::new(
1497                    Code::InvalidRequest,
1498                    Some(Field::value(name)),
1499                    misfit_message(p, why, v),
1500                ));
1501            }
1502        }
1503    }
1504    Ok(Admitted {
1505        class: g.class,
1506        values,
1507        joins: req.token.is_some(),
1508        dry_run: req.dry_run,
1509    })
1510}
1511
1512/// Checks a `set` as §2.5 orders it: the request's own type (row 0), an act
1513/// in flight (row 1), then rows 3 to 11. Row 2, an idempotency key the owner
1514/// holds, needs the keys, and rows 12 to 14 the rate, the deadline and the
1515/// device: [`Owner::set`] adds them. A tool runs this against a view before
1516/// it sends (§2.5, "A caller that checks first").
1517///
1518/// # Errors
1519///
1520/// The first [`Refusal`] that applies.
1521pub fn validate_set(
1522    schema: &Schema,
1523    facts: &Facts<'_>,
1524    group: &str,
1525    req: &SetRequest,
1526) -> Result<Admitted, Refusal> {
1527    check_set_shape(req)?;
1528    if facts.in_flight {
1529        return Err(in_flight());
1530    }
1531    check_rows(schema, facts, group, req)
1532}
1533
1534/// Checks a control operation as §2.10 and §2.13 order it.
1535///
1536/// # Errors
1537///
1538/// The first [`Refusal`] that applies.
1539pub fn validate_control(
1540    op: ControlOp,
1541    facts: &Facts<'_>,
1542    req: &ControlRequest,
1543) -> Result<(), Refusal> {
1544    if op == ControlOp::Persist && !facts.persist {
1545        return Err(Refusal::new(
1546            Code::Unavailable,
1547            None,
1548            "this service has no persisted layer: persist is unavailable here",
1549        ));
1550    }
1551    check_control_shape(req)?;
1552    if facts.in_flight {
1553        return Err(in_flight());
1554    }
1555    let window_wrong = match op {
1556        ControlOp::Extend => req.confirm_s.is_none(),
1557        _ => req.confirm_s.is_some(),
1558    };
1559    if window_wrong {
1560        return Err(Refusal::new(
1561            Code::InvalidRequest,
1562            Some(Field::member("confirm_s")),
1563            if op == ControlOp::Extend {
1564                "extend carries confirm_s, the new window from now".to_owned()
1565            } else {
1566                format!("{} carries no confirm_s", op.as_str())
1567            },
1568        ));
1569    }
1570    if op == ControlOp::Persist {
1571        if let Some(p) = &facts.pending
1572            && p.token == req.token
1573        {
1574            return Err(Refusal::busy(format!(
1575                "change {} is still pending; confirm it first",
1576                p.token
1577            )));
1578        }
1579        let Some(last) = facts.last_change.filter(|l| l.token == req.token) else {
1580            return Err(Refusal::new(
1581                Code::NotFound,
1582                Some(Field::member("token")),
1583                "persist takes the last change's token, and nothing older",
1584            ));
1585        };
1586        if last.set_sensitive {
1587            return Err(Refusal::new(
1588                Code::Forbidden,
1589                Some(Field::member("token")),
1590                "the last change set a sensitive value, which is never written to the persisted layer",
1591            ));
1592        }
1593        return Ok(());
1594    }
1595    let Some(p) = facts.pending.filter(|p| p.token == req.token) else {
1596        return Err(Refusal::new(
1597            Code::NotFound,
1598            Some(Field::member("token")),
1599            "no pending change by this token",
1600        ));
1601    };
1602    if p.deadline_passed {
1603        return Err(Refusal::busy(
1604            "the change's deadline has passed and its undo is running; it can no longer be kept",
1605        ));
1606    }
1607    if op == ControlOp::Confirm && !p.applied {
1608        return Err(Refusal::busy(
1609            "the change is not applied yet; confirm it once the view shows it applied",
1610        ));
1611    }
1612    Ok(())
1613}
1614
1615/// Checks a desired document (§2.18): `Ok` when the owner may converge it,
1616/// else the first problem, in the profile's order.
1617///
1618/// # Errors
1619///
1620/// The [`DesiredRefusal`].
1621pub fn check_desired(schema: &Schema, doc: &DesiredConfig) -> Result<(), DesiredRefusal> {
1622    let refuse = |code, group: &str, parameter: Option<&str>| DesiredRefusal {
1623        code,
1624        group: group.to_owned(),
1625        parameter: parameter.map(str::to_owned),
1626    };
1627    for (gname, params) in &doc.values {
1628        let Some(g) = schema.group(gname) else {
1629            return Err(refuse(DesiredCode::NotFound, gname, None));
1630        };
1631        match g.class {
1632            Class::Contract => return Err(refuse(DesiredCode::Contract, gname, None)),
1633            Class::Reach => return Err(refuse(DesiredCode::Reach, gname, None)),
1634            Class::Hot => {}
1635        }
1636        if !g.writable {
1637            return Err(refuse(DesiredCode::Unavailable, gname, None));
1638        }
1639        for (pname, v) in params {
1640            let Some(p) = g.parameter(pname) else {
1641                return Err(refuse(DesiredCode::NotFound, gname, Some(pname)));
1642            };
1643            if p.sensitive {
1644                return Err(refuse(DesiredCode::Sensitive, gname, Some(pname)));
1645            }
1646            if p.kind.check(v).is_err() {
1647                return Err(refuse(DesiredCode::InvalidRequest, gname, Some(pname)));
1648            }
1649        }
1650    }
1651    Ok(())
1652}
1653
1654// --- redaction (§2.15) -------------------------------------------------------------------
1655
1656/// A `set` request as a log line may carry it (§2.15): every value whose
1657/// parameter is sensitive, or that the owner cannot tell is not (an unknown
1658/// group or parameter), written [`REDACTED`].
1659#[must_use]
1660pub fn log_request(schema: &Schema, group: &str, req: &SetRequest) -> Json {
1661    let g = schema.group(group);
1662    let mut out = serde_json::to_value(req).unwrap_or(Json::Null);
1663    if let Some(values) = out.get_mut("values").and_then(Json::as_object_mut) {
1664        for (name, v) in values.iter_mut() {
1665            if g.is_none_or(|g| g.is_sensitive(name)) {
1666                *v = Json::String(REDACTED.to_owned());
1667            }
1668        }
1669    }
1670    out
1671}
1672
1673/// Whether a `set` carries a value whose parameter is sensitive, or one the
1674/// owner cannot tell is not.
1675#[must_use]
1676pub fn carries_sensitive(schema: &Schema, group: &str, req: &SetRequest) -> bool {
1677    let g = schema.group(group);
1678    req.values
1679        .keys()
1680        .any(|n| g.is_none_or(|g| g.is_sensitive(n)))
1681}
1682
1683/// The `detail` of a `device-refused` envelope (§2.15): the device's
1684/// words, left out when the change carries a sensitive value, since they
1685/// may repeat it.
1686#[must_use]
1687pub fn device_detail(
1688    schema: &Schema,
1689    group: &str,
1690    req: &SetRequest,
1691    words: Option<&str>,
1692) -> Option<String> {
1693    if carries_sensitive(schema, group, req) {
1694        None
1695    } else {
1696        words.map(str::to_owned)
1697    }
1698}
1699
1700// --- the owner (§2.6 to §2.17) -----------------------------------------------------------
1701
1702/// The call metadata a call claimed (core O7): never authentication.
1703#[derive(Debug, Clone, PartialEq, Eq, Default)]
1704pub struct Call {
1705    /// The claimed actor.
1706    pub actor: Option<String>,
1707    /// The claimed request id.
1708    pub request_id: Option<String>,
1709}
1710
1711/// What an owner starts from: its address, schema, startup layers and
1712/// device facts.
1713#[derive(Debug, Clone)]
1714pub struct Start {
1715    /// The owner's address, `<system>/<service>`.
1716    pub service: String,
1717    /// The instance id; tokens are minted `<instance>-<n>`.
1718    pub instance: String,
1719    /// The schema.
1720    pub schema: Schema,
1721    /// The startup file's and the defaults' values, `{group: {parameter:
1722    /// (value, source)}}`, each source `file` or `default`. A parameter
1723    /// absent here starts unknown.
1724    pub startup: BTreeMap<String, BTreeMap<String, (Value, Source)>>,
1725    /// The persisted layer, `{group: {parameter: value}}`.
1726    pub overlay: BTreeMap<String, BTreeMap<String, Value>>,
1727    /// The floor, in seconds, at least 1 (§2.8).
1728    pub floor_s: u64,
1729    /// How long after receiving a reach `set` the device applies it: the
1730    /// `apply_at` it states (§2.9). Less than the floor, so that a new
1731    /// reach change applies before its deadline.
1732    pub apply_after: Duration,
1733    /// Whether the owner has a persisted layer (§2.13).
1734    pub persist: bool,
1735    /// The change events already published, for the rate (§2.17).
1736    pub events: Vec<Time>,
1737}
1738
1739/// Why [`Owner::start`] refused a [`Start`].
1740#[derive(Debug, Clone, PartialEq, Eq)]
1741pub struct StartError(pub String);
1742
1743impl fmt::Display for StartError {
1744    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1745        f.write_str(&self.0)
1746    }
1747}
1748
1749impl std::error::Error for StartError {}
1750
1751/// A device act the runtime performs, then reports with
1752/// [`Owner::finish`].
1753#[derive(Debug, Clone, PartialEq, Eq)]
1754pub enum Act {
1755    /// Apply these values of one group.
1756    Apply {
1757        /// The group.
1758        group: String,
1759        /// The values, by parameter.
1760        values: BTreeMap<String, Value>,
1761    },
1762    /// The undo, once: restore each parameter to its value before the
1763    /// change (§2.11).
1764    Undo {
1765        /// What to restore.
1766        restore: Vec<Restore>,
1767    },
1768}
1769
1770/// One parameter an undo restores.
1771#[derive(Debug, Clone, PartialEq, Eq)]
1772pub struct Restore {
1773    /// Its group.
1774    pub group: String,
1775    /// Its name.
1776    pub parameter: String,
1777    /// Its value before the change.
1778    pub value: Value,
1779}
1780
1781/// What the device said of an act. An apply reported `Failed` reads as
1782/// refused, and an undo reported `Refused` as failed with nothing read
1783/// back.
1784#[derive(Debug, Clone, PartialEq, Eq)]
1785pub enum DeviceResult {
1786    /// Done.
1787    Ok,
1788    /// An apply refused, in the device's words.
1789    Refused(String),
1790    /// An undo failed, in the device's words, with what the owner read
1791    /// back: `{group: {parameter: value}}`, a parameter not in it unknown.
1792    Failed {
1793        /// The device's words.
1794        words: String,
1795        /// What was read back.
1796        readback: BTreeMap<String, BTreeMap<String, Value>>,
1797    },
1798}
1799
1800impl Act {
1801    /// Whether the act sets a value whose parameter is sensitive, or one
1802    /// the owner cannot tell is not (an unknown group or parameter): an
1803    /// apply of such a value, or an undo restoring one (§2.15).
1804    #[must_use]
1805    pub fn carries_sensitive(&self, schema: &Schema) -> bool {
1806        let sensitive = |g: &str, p: &str| schema.group(g).is_none_or(|g| g.is_sensitive(p));
1807        match self {
1808            Self::Apply { group, values } => values.keys().any(|p| sensitive(group, p)),
1809            Self::Undo { restore } => restore.iter().any(|r| sensitive(&r.group, &r.parameter)),
1810        }
1811    }
1812}
1813
1814/// The device's words about `act` as a log line may carry them (§2.15):
1815/// left out when the act sets a sensitive value, since they may repeat it.
1816#[must_use]
1817pub fn device_words<'w>(schema: &Schema, act: &Act, words: &'w str) -> Option<&'w str> {
1818    (!act.carries_sensitive(schema)).then_some(words)
1819}
1820
1821/// What converging a desired document asks of the owner next (§2.18),
1822/// from [`Owner::converge`].
1823#[derive(Debug, Clone, PartialEq)]
1824pub enum Converge {
1825    /// A change is pending, or an act is in flight: wait until it ends.
1826    Wait,
1827    /// Refused whole, before anything applied: the report to carry.
1828    Refused(DesiredReport),
1829    /// One `set` without a window, on the first group by bytewise name
1830    /// whose values differ from the document: its own change, `applied`.
1831    /// A refusal of it is the report [`desired_failed`] makes.
1832    Set {
1833        /// The group.
1834        group: String,
1835        /// The request: the values that differ, and nothing else.
1836        request: SetRequest,
1837    },
1838    /// Every value the document names is the running value.
1839    Converged(DesiredReport),
1840}
1841
1842/// The report of a document whose converging `set` on `group` was refused
1843/// (§2.18): `failed`, with that refusal's code (`busy` for the rate,
1844/// `device-refused`) and group.
1845#[must_use]
1846pub fn desired_failed(revision: u64, group: &str, refusal: &Refusal) -> DesiredReport {
1847    let code = match refusal.code {
1848        Code::Busy => DesiredCode::Busy,
1849        Code::App => DesiredCode::DeviceRefused,
1850        Code::InvalidRequest => DesiredCode::InvalidRequest,
1851        Code::NotFound => DesiredCode::NotFound,
1852        // A set never answers `forbidden`; and `unavailable` is the
1853        // allowlist's, which check_desired refused first.
1854        Code::Unavailable | Code::Forbidden => DesiredCode::Unavailable,
1855    };
1856    DesiredReport {
1857        observed_revision: revision,
1858        outcome: DesiredOutcome::Failed,
1859        refusal: Some(DesiredRefusal {
1860            code,
1861            group: group.to_owned(),
1862            parameter: None,
1863        }),
1864    }
1865}
1866
1867/// A reply an owner sends.
1868#[derive(Debug, Clone, PartialEq, Eq)]
1869pub enum Reply {
1870    /// To a `set`.
1871    Set(SetReply),
1872    /// To a control operation.
1873    Control(ControlReply),
1874}
1875
1876impl Reply {
1877    /// The reply's JSON.
1878    #[must_use]
1879    pub fn to_json(&self) -> Json {
1880        match self {
1881            Self::Set(r) => serde_json::to_value(r),
1882            Self::Control(r) => serde_json::to_value(r),
1883        }
1884        .unwrap_or(Json::Null)
1885    }
1886}
1887
1888/// An answered step: the reply owed to the call, if any, and the change
1889/// events to publish, in order.
1890#[derive(Debug, Clone, PartialEq, Eq, Default)]
1891pub struct Done {
1892    /// The reply, or the refusal, owed to the call; `None` when no call is
1893    /// answered (a deadline, a reach apply).
1894    pub reply: Option<Result<Reply, Refusal>>,
1895    /// The events to publish.
1896    pub events: Vec<ConfigChangeEvent>,
1897}
1898
1899/// What the owner does next: answer, or have the runtime act on the device
1900/// and report back with [`Owner::finish`]. A call answered with an act
1901/// gets its reply from the act's finish.
1902#[derive(Debug, Clone, PartialEq, Eq)]
1903pub enum Step {
1904    /// Answered now.
1905    Done(Done),
1906    /// An act to perform first.
1907    Act(Act),
1908}
1909
1910/// A `persist` the owner admitted: the entries the runtime writes, then
1911/// commits with [`Owner::persisted`].
1912#[derive(Debug, Clone, PartialEq, Eq)]
1913pub struct PersistPlan {
1914    /// The last change's token.
1915    pub token: String,
1916    /// The values to write, `{group: {parameter: value}}`.
1917    pub entries: BTreeMap<String, BTreeMap<String, Value>>,
1918    answer: Answer,
1919}
1920
1921type Key = (String, String);
1922
1923#[derive(Debug, Clone)]
1924struct Slot {
1925    value: Option<Value>,
1926    source: Option<Source>,
1927}
1928
1929#[derive(Debug, Clone)]
1930struct EditRec {
1931    old: Option<Value>,
1932    old_source: Option<Source>,
1933    new: Value,
1934    applied: bool,
1935    sensitive: bool,
1936}
1937
1938#[derive(Debug, Clone)]
1939struct Wait {
1940    group: String,
1941    values: BTreeMap<String, Value>,
1942    apply_at: Time,
1943}
1944
1945#[derive(Debug, Clone)]
1946struct Change {
1947    token: String,
1948    groups: Vec<String>,
1949    deadline: Time,
1950    call: Call,
1951    edits: BTreeMap<Key, EditRec>,
1952    waiting: Vec<Wait>,
1953}
1954
1955#[derive(Debug, Clone)]
1956struct Last {
1957    token: String,
1958    groups: Vec<String>,
1959    /// The values the change set, as it set them: what `persist` writes,
1960    /// whatever a pending change runs since (§2.13, text 0.2, F-111).
1961    values: BTreeMap<Key, Value>,
1962    sensitive: bool,
1963}
1964
1965impl Last {
1966    fn of(token: String, groups: Vec<String>, edits: &BTreeMap<Key, EditRec>) -> Self {
1967        Self {
1968            token,
1969            groups,
1970            values: edits
1971                .iter()
1972                .map(|(k, r)| (k.clone(), r.new.clone()))
1973                .collect(),
1974            sensitive: edits.values().any(|r| r.sensitive),
1975        }
1976    }
1977}
1978
1979#[derive(Debug, Clone)]
1980struct Held {
1981    key: String,
1982    group: String,
1983    request: SetRequest,
1984    answer: Result<Reply, Refusal>,
1985    at: Time,
1986}
1987
1988#[derive(Debug, Clone, Copy)]
1989enum UndoWhy {
1990    Deadline,
1991    Cancel(Answer),
1992    Failed,
1993}
1994
1995#[derive(Debug, Clone)]
1996enum Flight {
1997    Set {
1998        group: String,
1999        request: SetRequest,
2000        call: Call,
2001        values: BTreeMap<String, Value>,
2002        received: Time,
2003    },
2004    Apply(Wait),
2005    Undo {
2006        why: UndoWhy,
2007        plan: Vec<Key>,
2008    },
2009}
2010
2011/// One owner's configuration, as a pure state machine (§2.6 to §2.17).
2012///
2013/// Every method takes the instant it acts at. A call is answered by a
2014/// [`Step`]: [`Step::Done`] now, or [`Step::Act`], an act the runtime
2015/// performs on the device before it calls [`Owner::finish`] with the
2016/// result. While an act is in flight, every call is `busy` (§2.7). The
2017/// runtime calls [`Owner::due`] at [`Owner::next_due`], for the deadline's
2018/// undo and each reach apply.
2019#[derive(Debug, Clone)]
2020pub struct Owner {
2021    service: String,
2022    instance: String,
2023    schema: Schema,
2024    floor_s: u64,
2025    apply_after: Duration,
2026    persist: bool,
2027    file: BTreeMap<Key, (Value, Source)>,
2028    overlay: BTreeMap<Key, Value>,
2029    slots: BTreeMap<Key, Slot>,
2030    revision: u64,
2031    minted: u64,
2032    pending: Option<Change>,
2033    last: Option<Last>,
2034    keys: Vec<Held>,
2035    events: Vec<Time>,
2036    flight: Option<Flight>,
2037    desired: Option<DesiredReport>,
2038    whole_seconds: bool,
2039}
2040
2041fn key(g: &str, p: &str) -> Key {
2042    (g.to_owned(), p.to_owned())
2043}
2044
2045fn flat<T: Clone>(m: &BTreeMap<String, BTreeMap<String, T>>) -> BTreeMap<Key, T> {
2046    m.iter()
2047        .flat_map(|(g, ps)| ps.iter().map(move |(p, v)| (key(g, p), v.clone())))
2048        .collect()
2049}
2050
2051impl Owner {
2052    /// Starts an owner from its startup values and its persisted layer,
2053    /// never from a runtime change (§2.12): revision 0, nothing pending.
2054    ///
2055    /// # Errors
2056    ///
2057    /// A [`StartError`] for a floor of 0, an `apply_after` not below the
2058    /// floor, more than 16 groups, a name declared twice, bounds that cross,
2059    /// a startup source other than `file` or `default`, or a layer naming a
2060    /// parameter the schema does not declare, or a sensitive one in the
2061    /// persisted layer.
2062    pub fn start(s: Start) -> Result<Self, StartError> {
2063        let fail = |m: String| Err(StartError(m));
2064        if s.floor_s == 0 {
2065            return fail("the floor is at least 1 s".into());
2066        }
2067        if s.apply_after >= Duration::from_secs(s.floor_s) {
2068            return fail("apply_after must be below the floor, so that a reach change applies before its deadline".into());
2069        }
2070        if s.schema.groups.len() > MAX_GROUPS {
2071            return fail(format!(
2072                "{} groups, above the contract's {MAX_GROUPS}",
2073                s.schema.groups.len()
2074            ));
2075        }
2076        for (i, g) in s.schema.groups.iter().enumerate() {
2077            if g.name.is_empty() || s.schema.groups[..i].iter().any(|h| h.name == g.name) {
2078                return fail(format!("group {:?} is empty or declared twice", g.name));
2079            }
2080            for (j, p) in g.parameters.iter().enumerate() {
2081                if p.name.is_empty() || g.parameters[..j].iter().any(|q| q.name == p.name) {
2082                    return fail(format!(
2083                        "parameter {:?} of {:?} is empty or declared twice",
2084                        p.name, g.name
2085                    ));
2086                }
2087                if let Kind::Integer {
2088                    min: Some(a),
2089                    max: Some(b),
2090                    ..
2091                } = p.kind
2092                    && a > b
2093                {
2094                    return fail(format!("{}.{}: min above max", g.name, p.name));
2095                }
2096            }
2097        }
2098        let file = flat(&s.startup);
2099        let overlay = flat(&s.overlay);
2100        for ((g, p), (v, src)) in &file {
2101            let Some(d) = s.schema.group(g).and_then(|gd| gd.parameter(p)) else {
2102                return fail(format!(
2103                    "the startup layer names {g}.{p}, which the schema does not declare"
2104                ));
2105            };
2106            if !matches!(src, Source::File | Source::Default) {
2107                return fail(format!(
2108                    "{g}.{p}: a startup value comes from the file or a default"
2109                ));
2110            }
2111            if d.kind
2112                .check(&serde_json::to_value(v).unwrap_or(Json::Null))
2113                .is_err()
2114            {
2115                return fail(format!(
2116                    "{g}.{p}: its startup value is not of its kind or bounds"
2117                ));
2118            }
2119        }
2120        for ((g, p), v) in &overlay {
2121            match s.schema.group(g).and_then(|gd| gd.parameter(p)) {
2122                None => {
2123                    return fail(format!(
2124                        "the persisted layer names {g}.{p}, which the schema does not declare"
2125                    ));
2126                }
2127                Some(d) if d.sensitive => {
2128                    return fail(format!("{g}.{p} is sensitive, never persisted"));
2129                }
2130                Some(d)
2131                    if d.kind
2132                        .check(&serde_json::to_value(v).unwrap_or(Json::Null))
2133                        .is_err() =>
2134                {
2135                    return fail(format!(
2136                        "{g}.{p}: its persisted value is not of its kind or bounds"
2137                    ));
2138                }
2139                Some(_) => {}
2140            }
2141        }
2142        let mut slots = BTreeMap::new();
2143        for g in &s.schema.groups {
2144            for p in &g.parameters {
2145                let k = key(&g.name, &p.name);
2146                let slot = match (overlay.get(&k), file.get(&k)) {
2147                    (Some(v), _) => Slot {
2148                        value: Some(v.clone()),
2149                        source: Some(Source::Overlay),
2150                    },
2151                    (None, Some((v, src))) => Slot {
2152                        value: Some(v.clone()),
2153                        source: Some(*src),
2154                    },
2155                    (None, None) => Slot {
2156                        value: None,
2157                        source: None,
2158                    },
2159                };
2160                slots.insert(k, slot);
2161            }
2162        }
2163        Ok(Self {
2164            service: s.service,
2165            instance: s.instance,
2166            schema: s.schema,
2167            floor_s: s.floor_s,
2168            apply_after: s.apply_after,
2169            persist: s.persist,
2170            file,
2171            overlay,
2172            slots,
2173            revision: 0,
2174            minted: 0,
2175            pending: None,
2176            last: None,
2177            keys: Vec::new(),
2178            events: s.events,
2179            flight: None,
2180            desired: None,
2181            whole_seconds: false,
2182        })
2183    }
2184
2185    /// The owner with every deadline and `apply_at` it states rounded up
2186    /// to the next whole second, acted on at that instant: `config.v2`'s
2187    /// times (its §2.8), which [`v2::Owner`] runs this owner under.
2188    /// `config.v1` keeps milliseconds.
2189    #[must_use]
2190    pub fn whole_seconds(mut self) -> Self {
2191        self.whole_seconds = true;
2192        self
2193    }
2194
2195    /// An instant this owner states: rounded up under
2196    /// [`Owner::whole_seconds`].
2197    fn stated(&self, t: Time) -> Time {
2198        if self.whole_seconds {
2199            t.ceil_second()
2200        } else {
2201            t
2202        }
2203    }
2204
2205    /// The owner after a restart, as a new instance (§2.12): its startup
2206    /// values and persisted layer, revision 0, nothing pending, no last
2207    /// change, no key held. The persisted layer and the published events
2208    /// survive it.
2209    #[must_use]
2210    pub fn restart(&self, instance: impl Into<String>) -> Self {
2211        let unflat = |m: &BTreeMap<Key, (Value, Source)>| {
2212            let mut out: BTreeMap<String, BTreeMap<String, (Value, Source)>> = BTreeMap::new();
2213            for ((g, p), v) in m {
2214                out.entry(g.clone())
2215                    .or_default()
2216                    .insert(p.clone(), v.clone());
2217            }
2218            out
2219        };
2220        let mut overlay: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
2221        for ((g, p), v) in &self.overlay {
2222            overlay
2223                .entry(g.clone())
2224                .or_default()
2225                .insert(p.clone(), v.clone());
2226        }
2227        let mut next = Self::start(Start {
2228            service: self.service.clone(),
2229            instance: instance.into(),
2230            schema: self.schema.clone(),
2231            startup: unflat(&self.file),
2232            overlay,
2233            floor_s: self.floor_s,
2234            apply_after: self.apply_after,
2235            persist: self.persist,
2236            events: self.events.clone(),
2237        })
2238        .expect("a start that succeeded once succeeds again");
2239        next.whole_seconds = self.whole_seconds;
2240        next
2241    }
2242
2243    /// The schema.
2244    #[must_use]
2245    pub fn schema(&self) -> &Schema {
2246        &self.schema
2247    }
2248
2249    /// The instance id.
2250    #[must_use]
2251    pub fn instance(&self) -> &str {
2252        &self.instance
2253    }
2254
2255    /// The revision.
2256    #[must_use]
2257    pub fn revision(&self) -> u64 {
2258        self.revision
2259    }
2260
2261    /// Whether an act is in flight.
2262    #[must_use]
2263    pub fn in_flight(&self) -> bool {
2264        self.flight.is_some()
2265    }
2266
2267    /// The next instant [`Owner::due`] has something to do: the earliest
2268    /// reach `apply_at`, or the deadline.
2269    #[must_use]
2270    pub fn next_due(&self) -> Option<Time> {
2271        let ch = self.pending.as_ref()?;
2272        let apply = ch.waiting.iter().map(|w| w.apply_at).min();
2273        Some(apply.map_or(ch.deadline, |a| a.min(ch.deadline)))
2274    }
2275
2276    /// The pending change's deadline, if a change is pending.
2277    #[must_use]
2278    pub fn deadline(&self) -> Option<Time> {
2279        self.pending.as_ref().map(|c| c.deadline)
2280    }
2281
2282    /// The `apply_at` of the last reach group to join the pending change
2283    /// that has not applied yet, if one waits: `None` when the change is
2284    /// applied, or when none is pending (`config.v2` §2.9).
2285    #[must_use]
2286    pub fn apply_at(&self) -> Option<Time> {
2287        self.pending.as_ref()?.waiting.last().map(|w| w.apply_at)
2288    }
2289
2290    /// Sets the desired report the view and the status carry (§2.18).
2291    pub fn report_desired(&mut self, report: Option<DesiredReport>) {
2292        self.desired = report;
2293    }
2294
2295    /// The desired report the view and the status carry (§2.18).
2296    #[must_use]
2297    pub fn desired(&self) -> Option<&DesiredReport> {
2298        self.desired.as_ref()
2299    }
2300
2301    /// The instants of the change events published within the last hour
2302    /// at `now`, oldest first (§2.17): what the next instance starts from
2303    /// ([`Start::events`]), so that the event's rate, which a re-mint does
2304    /// not reset (core §2.7), holds across a restart.
2305    #[must_use]
2306    pub fn published(&self, now: Time) -> Vec<Time> {
2307        let mut out: Vec<Time> = self
2308            .events
2309            .iter()
2310            .copied()
2311            .filter(|e| now.within(*e, RATE_PERIOD))
2312            .collect();
2313        out.sort();
2314        out
2315    }
2316
2317    /// What converging `doc` asks next (§2.18): wait while a change is
2318    /// pending or an act is in flight; the document refused whole
2319    /// ([`check_desired`]); one `set` without a window on the first group,
2320    /// in the bytewise order of the group names, whose values differ from
2321    /// the running ones; or converged. Called again after each `set`, it
2322    /// moves to the next group, since the one applied no longer differs.
2323    #[must_use]
2324    pub fn converge(&self, doc: &DesiredConfig) -> Converge {
2325        if self.pending.is_some() || self.flight.is_some() {
2326            return Converge::Wait;
2327        }
2328        if let Err(refusal) = check_desired(&self.schema, doc) {
2329            return Converge::Refused(DesiredReport {
2330                observed_revision: doc.revision,
2331                outcome: DesiredOutcome::Refused,
2332                refusal: Some(refusal),
2333            });
2334        }
2335        for (g, params) in &doc.values {
2336            let Some(decl) = self.schema.group(g) else {
2337                continue;
2338            };
2339            let differ: BTreeMap<String, Json> = params
2340                .iter()
2341                .filter(|(p, v)| {
2342                    let wanted = decl.parameter(p).and_then(|d| d.kind.check(v).ok());
2343                    let running = self.slots.get(&key(g, p)).and_then(|s| s.value.as_ref());
2344                    wanted.as_ref() != running
2345                })
2346                .map(|(p, v)| (p.clone(), v.clone()))
2347                .collect();
2348            if !differ.is_empty() {
2349                return Converge::Set {
2350                    group: g.clone(),
2351                    request: SetRequest {
2352                        values: differ,
2353                        ..SetRequest::default()
2354                    },
2355                };
2356            }
2357        }
2358        Converge::Converged(DesiredReport {
2359            observed_revision: doc.revision,
2360            outcome: DesiredOutcome::Converged,
2361            refusal: None,
2362        })
2363    }
2364
2365    /// What the validators read of the owner's state at `now`.
2366    #[must_use]
2367    pub fn facts(&self, now: Time) -> Facts<'_> {
2368        Facts {
2369            revision: self.revision,
2370            pending: self.pending.as_ref().map(|c| PendingFacts {
2371                token: &c.token,
2372                applied: c.waiting.is_empty(),
2373                deadline_passed: now >= c.deadline,
2374            }),
2375            last_change: self.last.as_ref().map(|l| LastFacts {
2376                token: &l.token,
2377                set_sensitive: l.sensitive,
2378            }),
2379            persist: self.persist,
2380            in_flight: self.flight.is_some(),
2381        }
2382    }
2383
2384    fn startup_value(&self, k: &Key) -> Option<(Value, Source)> {
2385        self.overlay
2386            .get(k)
2387            .map(|v| (v.clone(), Source::Overlay))
2388            .or_else(|| self.file.get(k).cloned())
2389    }
2390
2391    /// A parameter's startup value and its source (§2.12): the persisted
2392    /// layer's, else the startup file's or the default. `None` for a
2393    /// parameter that starts unknown, or that the schema does not declare.
2394    #[must_use]
2395    pub fn startup(&self, group: &str, parameter: &str) -> Option<(Value, Source)> {
2396        self.startup_value(&key(group, parameter))
2397    }
2398
2399    /// The document a delete reverts the owner to, when `desired.v1` feeds
2400    /// it (`desired.v1` §2.16, text 0.3): each parameter of `named` (the
2401    /// ones the documents it acted on named) at its startup value, the
2402    /// persisted layer's, else the startup file's or the default; one that
2403    /// starts unknown is left out, and keeps its running value. Converged
2404    /// as any document is ([`Owner::converge`]): one `set` without a window
2405    /// per group whose running values differ, nothing for one that already
2406    /// runs its startup values.
2407    #[must_use]
2408    pub fn baseline_document<'n>(
2409        &self,
2410        named: impl IntoIterator<Item = (&'n str, &'n str)>,
2411    ) -> DesiredConfig {
2412        let mut values: BTreeMap<String, BTreeMap<String, Json>> = BTreeMap::new();
2413        for (g, p) in named {
2414            if let Some((v, _)) = self.startup(g, p) {
2415                values
2416                    .entry(g.to_owned())
2417                    .or_default()
2418                    .insert(p.to_owned(), serde_json::to_value(&v).unwrap_or(Json::Null));
2419            }
2420        }
2421        DesiredConfig {
2422            revision: 0,
2423            values,
2424        }
2425    }
2426
2427    /// What a re-mint returns the device to first (§2.12, "A re-mint is a
2428    /// restart"): each parameter whose running value is not its startup
2429    /// value, unknown included, at its startup value (the persisted
2430    /// layer's, else the startup file's or the default), in the schema's
2431    /// order. Empty when the device runs its startup values. `Err` names
2432    /// the first parameter that runs a value but starts unknown, which
2433    /// nothing returns it to. Read with nothing pending: a pending change
2434    /// is cancelled first.
2435    ///
2436    /// # Errors
2437    ///
2438    /// `(group, parameter)` of a parameter with a running value and no
2439    /// startup value.
2440    pub fn restart_plan(&self) -> Result<Vec<Restore>, (String, String)> {
2441        let mut plan = Vec::new();
2442        for g in &self.schema.groups {
2443            for p in &g.parameters {
2444                let k = key(&g.name, &p.name);
2445                let running = self.slots.get(&k).and_then(|s| s.value.as_ref());
2446                match (running, self.startup_value(&k)) {
2447                    (r, Some((v, _))) if r != Some(&v) => plan.push(Restore {
2448                        group: g.name.clone(),
2449                        parameter: p.name.clone(),
2450                        value: v,
2451                    }),
2452                    (Some(_), None) => return Err(k),
2453                    _ => {}
2454                }
2455            }
2456        }
2457        Ok(plan)
2458    }
2459
2460    fn render(&self, slots: &BTreeMap<Key, Slot>) -> ConfigView {
2461        let groups = self
2462            .schema
2463            .groups
2464            .iter()
2465            .map(|g| GroupView {
2466                name: g.name.clone(),
2467                class: g.class,
2468                description: g.description.clone(),
2469                writable: g.writable,
2470                parameters: g
2471                    .parameters
2472                    .iter()
2473                    .map(|d| {
2474                        let k = key(&g.name, &d.name);
2475                        let slot = slots.get(&k);
2476                        let value = slot.and_then(|s| s.value.clone());
2477                        let startup = self.startup_value(&k).map(|(v, _)| v);
2478                        Parameter {
2479                            name: d.name.clone(),
2480                            kind: d.kind.clone(),
2481                            description: d.description.clone(),
2482                            sensitive: d.sensitive,
2483                            value: if d.sensitive { None } else { value.clone() },
2484                            source: slot.and_then(|s| s.source),
2485                            startup: match (d.sensitive, value, startup) {
2486                                (false, Some(v), Some(s)) if v != s => Some(s),
2487                                _ => None,
2488                            },
2489                        }
2490                    })
2491                    .collect(),
2492            })
2493            .collect();
2494        ConfigView {
2495            service: self.service.clone(),
2496            instance: self.instance.clone(),
2497            revision: self.revision,
2498            confirm_floor_s: self.floor_s,
2499            pending: self.pending.as_ref().map(|c| Pending {
2500                token: c.token.clone(),
2501                groups: c.groups.clone(),
2502                deadline: c.deadline.rfc3339(),
2503                applied: c.waiting.is_empty(),
2504            }),
2505            last_change: self.last.as_ref().map(|l| LastChange {
2506                token: l.token.clone(),
2507                groups: l.groups.clone(),
2508            }),
2509            desired: self.desired.clone(),
2510            groups,
2511        }
2512    }
2513
2514    /// The read-back (§2.3).
2515    #[must_use]
2516    pub fn view(&self) -> ConfigView {
2517        self.render(&self.slots)
2518    }
2519
2520    /// The compact status, the view's projection (§2.19).
2521    #[must_use]
2522    pub fn status(&self) -> ConfigStatus {
2523        ConfigStatus::of(&self.view())
2524    }
2525
2526    fn control_reply(&self, answer: Answer) -> Reply {
2527        let view = self.view();
2528        Reply::Control(match answer {
2529            Answer::View => ControlReply::View(Box::new(view)),
2530            Answer::Status => ControlReply::Status(Box::new(ConfigStatus::of(&view))),
2531        })
2532    }
2533
2534    fn mint(&mut self) -> String {
2535        self.minted += 1;
2536        format!("{}-{}", self.instance, self.minted)
2537    }
2538
2539    fn rate_spent(&self, now: Time) -> bool {
2540        self.events
2541            .iter()
2542            .filter(|e| now.within(**e, RATE_PERIOD))
2543            .count()
2544            >= RATE
2545    }
2546
2547    fn edits(&self, groups: &[String], edits: &BTreeMap<Key, EditRec>) -> Vec<Edit> {
2548        groups
2549            .iter()
2550            .flat_map(|g| {
2551                edits
2552                    .iter()
2553                    .filter(move |((eg, _), _)| eg == g)
2554                    .map(|((eg, ep), r)| {
2555                        if r.sensitive {
2556                            Edit {
2557                                group: eg.clone(),
2558                                parameter: ep.clone(),
2559                                old: None,
2560                                new: None,
2561                                redacted: true,
2562                            }
2563                        } else {
2564                            Edit {
2565                                group: eg.clone(),
2566                                parameter: ep.clone(),
2567                                old: r.old.clone(),
2568                                new: Some(r.new.clone()),
2569                                redacted: false,
2570                            }
2571                        }
2572                    })
2573            })
2574            .collect()
2575    }
2576
2577    fn event(
2578        &mut self,
2579        now: Time,
2580        token: &str,
2581        outcome: Outcome,
2582        edits: Vec<Edit>,
2583        call: &Call,
2584    ) -> ConfigChangeEvent {
2585        self.events.retain(|e| now.within(*e, RATE_PERIOD));
2586        self.events.push(now);
2587        ConfigChangeEvent {
2588            service: self.service.clone(),
2589            instance: self.instance.clone(),
2590            revision: self.revision,
2591            token: token.to_owned(),
2592            outcome,
2593            edits,
2594            actor: call.actor.clone(),
2595            request_id: call.request_id.clone(),
2596            claimed_source: None,
2597        }
2598    }
2599
2600    fn is_sensitive(&self, k: &Key) -> bool {
2601        self.schema
2602            .group(&k.0)
2603            .is_some_and(|g| g.is_sensitive(&k.1))
2604    }
2605
2606    /// Records the values a change sets, keeping each parameter's value
2607    /// before the change from its first set.
2608    fn record(
2609        &self,
2610        edits: &mut BTreeMap<Key, EditRec>,
2611        group: &str,
2612        values: &BTreeMap<String, Value>,
2613        applied: bool,
2614    ) {
2615        for (p, v) in values {
2616            let k = key(group, p);
2617            let sensitive = self.is_sensitive(&k);
2618            match edits.get_mut(&k) {
2619                Some(r) => {
2620                    r.new = v.clone();
2621                    r.applied |= applied;
2622                }
2623                None => {
2624                    let slot = self.slots.get(&k);
2625                    edits.insert(
2626                        k,
2627                        EditRec {
2628                            old: slot.and_then(|s| s.value.clone()),
2629                            old_source: slot.and_then(|s| s.source),
2630                            new: v.clone(),
2631                            applied,
2632                            sensitive,
2633                        },
2634                    );
2635                }
2636            }
2637        }
2638    }
2639
2640    fn write(&mut self, group: &str, values: &BTreeMap<String, Value>) {
2641        for (p, v) in values {
2642            self.slots.insert(
2643                key(group, p),
2644                Slot {
2645                    value: Some(v.clone()),
2646                    source: Some(Source::Runtime),
2647                },
2648            );
2649        }
2650        self.revision += 1;
2651    }
2652
2653    fn forget_keys(&mut self, now: Time) {
2654        self.keys.retain(|h| now.within(h.at, KEY_HELD));
2655    }
2656
2657    fn hold(&mut self, now: Time, group: &str, req: &SetRequest, answer: &Result<Reply, Refusal>) {
2658        if let Some(k) = &req.idempotency_key
2659            && !self.keys.iter().any(|h| &h.key == k)
2660        {
2661            self.keys.push(Held {
2662                key: k.clone(),
2663                group: group.to_owned(),
2664                request: req.clone(),
2665                answer: answer.clone(),
2666                at: now,
2667            });
2668        }
2669    }
2670
2671    /// Whether a `set` of `group` with `req` would be answered now with the
2672    /// first answer its idempotency key holds (§2.14): what [`Owner::set`]
2673    /// replays, read without a change. A runtime that keeps the bytes it
2674    /// sent then sends them again, the first answer's as-of mark included
2675    /// (core §5.1, "An answer sent again").
2676    #[must_use]
2677    pub fn replays(&self, now: Time, group: &str, req: &SetRequest) -> bool {
2678        if check_set_shape(req).is_err() || self.flight.is_some() {
2679            return false;
2680        }
2681        req.idempotency_key.as_ref().is_some_and(|k| {
2682            self.held(now, k)
2683                .is_some_and(|h| h.group == group && h.request == *req)
2684        })
2685    }
2686
2687    /// Whether the owner holds a first answer for idempotency key `key` at
2688    /// `now` (§2.14): within 300 s of it.
2689    #[must_use]
2690    pub fn holds_key(&self, now: Time, key: &str) -> bool {
2691        self.held(now, key).is_some()
2692    }
2693
2694    fn held(&self, now: Time, key: &str) -> Option<&Held> {
2695        self.keys
2696            .iter()
2697            .find(|h| h.key == key && now.within(h.at, KEY_HELD))
2698    }
2699
2700    /// A `set` (§2.5, §2.9): answered now, or an [`Act::Apply`] for a hot
2701    /// group, whose reply comes with [`Owner::finish`].
2702    pub fn set(&mut self, now: Time, group: &str, req: &SetRequest, call: &Call) -> Step {
2703        let refuse = |r: Refusal| {
2704            Step::Done(Done {
2705                reply: Some(Err(r)),
2706                events: Vec::new(),
2707            })
2708        };
2709        if let Err(r) = check_set_shape(req) {
2710            return refuse(r);
2711        }
2712        if self.flight.is_some() {
2713            return refuse(in_flight());
2714        }
2715        self.forget_keys(now);
2716        if let Some(k) = &req.idempotency_key
2717            && let Some(h) = self.keys.iter().find(|h| &h.key == k)
2718        {
2719            return if h.group == group && h.request == *req {
2720                Step::Done(Done {
2721                    reply: Some(h.answer.clone()),
2722                    events: Vec::new(),
2723                })
2724            } else {
2725                refuse(Refusal::new(
2726                    Code::InvalidRequest,
2727                    Some(Field::member("idempotency_key")),
2728                    "this idempotency key was used for another request within 300 s",
2729                ))
2730            };
2731        }
2732        let step = self.admit(now, group, req, call);
2733        if let Step::Done(Done {
2734            reply: Some(answer),
2735            ..
2736        }) = &step
2737        {
2738            self.hold(now, group, req, answer);
2739        }
2740        step
2741    }
2742
2743    fn admit(&mut self, now: Time, group: &str, req: &SetRequest, call: &Call) -> Step {
2744        let refuse = |r: Refusal| {
2745            Step::Done(Done {
2746                reply: Some(Err(r)),
2747                events: Vec::new(),
2748            })
2749        };
2750        let facts = self.facts(now);
2751        let a = match check_rows(&self.schema, &facts, group, req) {
2752            Ok(a) => a,
2753            Err(r) => return refuse(r),
2754        };
2755        if a.dry_run {
2756            let mut slots = self.slots.clone();
2757            for (p, v) in &a.values {
2758                slots.insert(
2759                    key(group, p),
2760                    Slot {
2761                        value: Some(v.clone()),
2762                        source: Some(Source::Runtime),
2763                    },
2764                );
2765            }
2766            return Step::Done(Done {
2767                reply: Some(Ok(Reply::Set(SetReply::Applied(Box::new(
2768                    self.render(&slots),
2769                ))))),
2770                events: Vec::new(),
2771            });
2772        }
2773        if !a.joins && self.rate_spent(now) {
2774            return refuse(Refusal::busy(format!(
2775                "{RATE} change events within the last hour: the event's rate is spent; call again later"
2776            )));
2777        }
2778        match a.class {
2779            Class::Hot => {
2780                self.flight = Some(Flight::Set {
2781                    group: group.to_owned(),
2782                    request: req.clone(),
2783                    call: call.clone(),
2784                    values: a.values.clone(),
2785                    received: now,
2786                });
2787                Step::Act(Act::Apply {
2788                    group: group.to_owned(),
2789                    values: a.values,
2790                })
2791            }
2792            Class::Reach => {
2793                let apply_at = self.stated(now.plus(self.apply_after));
2794                if a.joins {
2795                    let deadline = self.pending.as_ref().map_or(now, |c| c.deadline);
2796                    if apply_at >= deadline {
2797                        return refuse(Refusal::busy(
2798                            "this group could not apply before the pending change's deadline; extend the change first",
2799                        ));
2800                    }
2801                    let mut ch = self.pending.take().expect("a join has a pending change");
2802                    self.record(&mut ch.edits, group, &a.values, false);
2803                    if !ch.groups.iter().any(|g| g == group) {
2804                        ch.groups.push(group.to_owned());
2805                    }
2806                    ch.waiting.push(Wait {
2807                        group: group.to_owned(),
2808                        values: a.values,
2809                        apply_at,
2810                    });
2811                    let reply = PendingReply {
2812                        token: ch.token.clone(),
2813                        apply_at: apply_at.rfc3339(),
2814                        deadline: ch.deadline.rfc3339(),
2815                    };
2816                    self.pending = Some(ch);
2817                    Step::Done(Done {
2818                        reply: Some(Ok(Reply::Set(SetReply::Pending(reply)))),
2819                        events: Vec::new(),
2820                    })
2821                } else {
2822                    let w = window(req.confirm_s.expect("row 10: a window"), self.floor_s);
2823                    let token = self.mint();
2824                    let deadline = self.stated(deadline(now, w));
2825                    let mut edits = BTreeMap::new();
2826                    self.record(&mut edits, group, &a.values, false);
2827                    self.pending = Some(Change {
2828                        token: token.clone(),
2829                        groups: vec![group.to_owned()],
2830                        deadline,
2831                        call: call.clone(),
2832                        edits,
2833                        waiting: vec![Wait {
2834                            group: group.to_owned(),
2835                            values: a.values,
2836                            apply_at,
2837                        }],
2838                    });
2839                    Step::Done(Done {
2840                        reply: Some(Ok(Reply::Set(SetReply::Pending(PendingReply {
2841                            token,
2842                            apply_at: apply_at.rfc3339(),
2843                            deadline: deadline.rfc3339(),
2844                        })))),
2845                        events: Vec::new(),
2846                    })
2847                }
2848            }
2849            Class::Contract => unreachable!("row 8 refuses a contract group"),
2850        }
2851    }
2852
2853    /// `confirm` (§2.10): always answered now.
2854    pub fn confirm(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
2855        if let Err(r) = validate_control(ControlOp::Confirm, &self.facts(now), req) {
2856            return Step::Done(Done {
2857                reply: Some(Err(r)),
2858                events: Vec::new(),
2859            });
2860        }
2861        let ch = self.pending.take().expect("validated: a change is pending");
2862        let edits = self.edits(&ch.groups, &ch.edits);
2863        let ev = self.event(now, &ch.token, Outcome::Confirmed, edits, &ch.call);
2864        self.last = Some(Last::of(ch.token.clone(), ch.groups.clone(), &ch.edits));
2865        Step::Done(Done {
2866            reply: Some(Ok(self.control_reply(req.answer.unwrap_or_default()))),
2867            events: vec![ev],
2868        })
2869    }
2870
2871    /// `extend` (§2.10): always answered now; the deadline moves to `now`
2872    /// plus the window, earlier or later.
2873    pub fn extend(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
2874        if let Err(r) = validate_control(ControlOp::Extend, &self.facts(now), req) {
2875            return Step::Done(Done {
2876                reply: Some(Err(r)),
2877                events: Vec::new(),
2878            });
2879        }
2880        let w = window(req.confirm_s.expect("validated: a window"), self.floor_s);
2881        let at = self.stated(deadline(now, w));
2882        if let Some(ch) = self.pending.as_mut() {
2883            ch.deadline = at;
2884        }
2885        Step::Done(Done {
2886            reply: Some(Ok(self.control_reply(req.answer.unwrap_or_default()))),
2887            events: Vec::new(),
2888        })
2889    }
2890
2891    /// `cancel` (§2.10): the undo now, an [`Act::Undo`] when something of
2892    /// the change is applied, else answered now.
2893    pub fn cancel(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
2894        if let Err(r) = validate_control(ControlOp::Cancel, &self.facts(now), req) {
2895            return Step::Done(Done {
2896                reply: Some(Err(r)),
2897                events: Vec::new(),
2898            });
2899        }
2900        self.end_by_undo(now, UndoWhy::Cancel(req.answer.unwrap_or_default()))
2901    }
2902
2903    /// Admits a `persist` (§2.13): the entries to write. Nothing changes
2904    /// until [`Owner::persisted`]; a write that fails is the runtime's
2905    /// `internal`.
2906    ///
2907    /// # Errors
2908    ///
2909    /// The [`Refusal`].
2910    pub fn persist_plan(&self, now: Time, req: &ControlRequest) -> Result<PersistPlan, Refusal> {
2911        validate_control(ControlOp::Persist, &self.facts(now), req)?;
2912        let last = self.last.as_ref().expect("validated: a last change");
2913        // The values the last change set, never the running ones: a pending
2914        // change may run another since (§2.13, text 0.2, F-111).
2915        let mut entries: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
2916        for ((g, p), v) in &last.values {
2917            entries
2918                .entry(g.clone())
2919                .or_default()
2920                .insert(p.clone(), v.clone());
2921        }
2922        Ok(PersistPlan {
2923            token: last.token.clone(),
2924            entries,
2925            answer: req.answer.unwrap_or_default(),
2926        })
2927    }
2928
2929    /// Commits a `persist` whose entries the runtime wrote (§2.13): a
2930    /// parameter that runs the value persisted reads `source: overlay`,
2931    /// unless an applied group of a pending change holds it, which keeps
2932    /// its value and source and shows the persisted value as `startup`;
2933    /// and a pending change's value before it, when it is the value
2934    /// persisted, restores at `source: overlay` (text 0.2, F-111). No
2935    /// revision, no event.
2936    pub fn persisted(&mut self, plan: PersistPlan) -> Done {
2937        for (g, ps) in &plan.entries {
2938            for (p, v) in ps {
2939                let k = key(g, p);
2940                self.overlay.insert(k.clone(), v.clone());
2941                let pending = self.pending.as_mut().and_then(|c| c.edits.get_mut(&k));
2942                let held = pending.as_ref().is_some_and(|r| r.applied);
2943                if let Some(r) = pending
2944                    && r.old.as_ref() == Some(v)
2945                {
2946                    r.old_source = Some(Source::Overlay);
2947                }
2948                if !held
2949                    && let Some(s) = self.slots.get_mut(&k)
2950                    && s.value.as_ref() == Some(v)
2951                {
2952                    s.source = Some(Source::Overlay);
2953                }
2954            }
2955        }
2956        Done {
2957            reply: Some(Ok(self.control_reply(plan.answer))),
2958            events: Vec::new(),
2959        }
2960    }
2961
2962    /// The act owed at `now`, if any (§2.9, §2.11): the deadline's undo,
2963    /// or else the earliest reach apply whose `apply_at` has come. A change
2964    /// with nothing applied ends at its deadline without an act. `None`
2965    /// while an act is in flight, or when nothing is owed.
2966    pub fn due(&mut self, now: Time) -> Option<Step> {
2967        if self.flight.is_some() {
2968            return None;
2969        }
2970        if now >= self.pending.as_ref()?.deadline {
2971            return Some(self.end_by_undo(now, UndoWhy::Deadline));
2972        }
2973        let ch = self.pending.as_mut()?;
2974        let i = ch
2975            .waiting
2976            .iter()
2977            .enumerate()
2978            .filter(|(_, w)| w.apply_at <= now)
2979            .min_by_key(|(i, w)| (w.apply_at, *i))
2980            .map(|(i, _)| i)?;
2981        let w = ch.waiting.remove(i);
2982        let act = Act::Apply {
2983            group: w.group.clone(),
2984            values: w.values.clone(),
2985        };
2986        self.flight = Some(Flight::Apply(w));
2987        Some(Step::Act(act))
2988    }
2989
2990    /// Ends the pending change by its undo: an act over its applied groups,
2991    /// or, with none applied, `rolled-back` at once (§2.11).
2992    fn end_by_undo(&mut self, now: Time, why: UndoWhy) -> Step {
2993        let Some(ch) = self.pending.as_mut() else {
2994            return Step::Done(Done::default());
2995        };
2996        ch.waiting.clear();
2997        let plan: Vec<Key> = ch
2998            .edits
2999            .iter()
3000            .filter(|(_, r)| r.applied)
3001            .map(|(k, _)| k.clone())
3002            .collect();
3003        if plan.is_empty() {
3004            let ch = self.pending.take().expect("checked above");
3005            let edits = self.edits(&ch.groups, &ch.edits);
3006            let ev = self.event(now, &ch.token, Outcome::RolledBack, edits, &ch.call);
3007            let reply = match why {
3008                UndoWhy::Cancel(answer) => Some(Ok(self.control_reply(answer))),
3009                _ => None,
3010            };
3011            return Step::Done(Done {
3012                reply,
3013                events: vec![ev],
3014            });
3015        }
3016        let ch = self.pending.as_ref().expect("checked above");
3017        let restore = plan
3018            .iter()
3019            .filter_map(|k| {
3020                let r = &ch.edits[k];
3021                let value = r
3022                    .old
3023                    .clone()
3024                    .or_else(|| self.startup_value(k).map(|(v, _)| v))?;
3025                Some(Restore {
3026                    group: k.0.clone(),
3027                    parameter: k.1.clone(),
3028                    value,
3029                })
3030            })
3031            .collect();
3032        self.flight = Some(Flight::Undo { why, plan });
3033        Step::Act(Act::Undo { restore })
3034    }
3035
3036    /// Reports the device's result for the act in flight, and answers what
3037    /// it owed: a `set`'s reply, a `cancel`'s, the events of a change it
3038    /// ended, or a next act (the undo after a reach apply that failed).
3039    pub fn finish(&mut self, now: Time, result: DeviceResult) -> Step {
3040        let Some(flight) = self.flight.take() else {
3041            return Step::Done(Done::default());
3042        };
3043        match flight {
3044            Flight::Set {
3045                group,
3046                request,
3047                call,
3048                values,
3049                received,
3050            } => {
3051                let done = match result {
3052                    DeviceResult::Ok => {
3053                        self.applied_hot(now, &group, &request, &call, &values, received)
3054                    }
3055                    DeviceResult::Refused(words) | DeviceResult::Failed { words, .. } => {
3056                        let detail = device_detail(&self.schema, &group, &request, Some(&words));
3057                        Done {
3058                            reply: Some(Err(Refusal::app(
3059                                ErrorCode::DeviceRefused,
3060                                detail,
3061                                format!("the device refused group {group:?}"),
3062                            ))),
3063                            events: Vec::new(),
3064                        }
3065                    }
3066                };
3067                if let Some(answer) = &done.reply {
3068                    self.hold(now, &group, &request, answer);
3069                }
3070                Step::Done(done)
3071            }
3072            Flight::Apply(w) => match result {
3073                DeviceResult::Ok => {
3074                    self.write(&w.group, &w.values);
3075                    if let Some(ch) = self.pending.as_mut() {
3076                        for p in w.values.keys() {
3077                            if let Some(r) = ch.edits.get_mut(&key(&w.group, p)) {
3078                                r.applied = true;
3079                            }
3080                        }
3081                    }
3082                    Step::Done(Done::default())
3083                }
3084                DeviceResult::Refused(_) | DeviceResult::Failed { .. } => {
3085                    self.end_by_undo(now, UndoWhy::Failed)
3086                }
3087            },
3088            Flight::Undo { why, plan } => {
3089                let ch = self
3090                    .pending
3091                    .take()
3092                    .expect("an undo ends the pending change");
3093                let outcome = match &result {
3094                    DeviceResult::Ok => {
3095                        for k in &plan {
3096                            let r = &ch.edits[k];
3097                            let (value, source) = match &r.old {
3098                                Some(v) => (Some(v.clone()), r.old_source),
3099                                None => match self.startup_value(k) {
3100                                    Some((v, s)) => (Some(v), Some(s)),
3101                                    None => (None, None),
3102                                },
3103                            };
3104                            self.slots.insert(k.clone(), Slot { value, source });
3105                        }
3106                        Outcome::RolledBack
3107                    }
3108                    DeviceResult::Refused(_) | DeviceResult::Failed { .. } => {
3109                        let empty = BTreeMap::new();
3110                        let readback = match &result {
3111                            DeviceResult::Failed { readback, .. } => readback,
3112                            _ => &empty,
3113                        };
3114                        for k in &plan {
3115                            let r = &ch.edits[k];
3116                            let read = readback.get(&k.0).and_then(|ps| ps.get(&k.1)).cloned();
3117                            let slot = match read {
3118                                Some(v) => {
3119                                    let source = if Some(&v) == r.old.as_ref() {
3120                                        r.old_source
3121                                    } else {
3122                                        Some(Source::Runtime)
3123                                    };
3124                                    Slot {
3125                                        value: Some(v),
3126                                        source,
3127                                    }
3128                                }
3129                                None => Slot {
3130                                    value: None,
3131                                    source: None,
3132                                },
3133                            };
3134                            self.slots.insert(k.clone(), slot);
3135                        }
3136                        Outcome::Partial
3137                    }
3138                };
3139                self.revision += 1;
3140                let edits = self.edits(&ch.groups, &ch.edits);
3141                let ev = self.event(now, &ch.token, outcome, edits, &ch.call);
3142                let reply = match why {
3143                    UndoWhy::Cancel(answer) => Some(Ok(self.control_reply(answer))),
3144                    UndoWhy::Deadline | UndoWhy::Failed => None,
3145                };
3146                Step::Done(Done {
3147                    reply,
3148                    events: vec![ev],
3149                })
3150            }
3151        }
3152    }
3153
3154    fn applied_hot(
3155        &mut self,
3156        now: Time,
3157        group: &str,
3158        request: &SetRequest,
3159        call: &Call,
3160        values: &BTreeMap<String, Value>,
3161        received: Time,
3162    ) -> Done {
3163        let mut events = Vec::new();
3164        if let Some(mut ch) = self.pending.take() {
3165            self.record(&mut ch.edits, group, values, true);
3166            if !ch.groups.iter().any(|g| g == group) {
3167                ch.groups.push(group.to_owned());
3168            }
3169            self.pending = Some(ch);
3170            self.write(group, values);
3171        } else {
3172            let mut edits = BTreeMap::new();
3173            self.record(&mut edits, group, values, true);
3174            self.write(group, values);
3175            let token = self.mint();
3176            let groups = vec![group.to_owned()];
3177            if let Some(cs) = request.confirm_s {
3178                self.pending = Some(Change {
3179                    token,
3180                    groups,
3181                    deadline: self.stated(deadline(received, window(cs, self.floor_s))),
3182                    call: call.clone(),
3183                    edits,
3184                    waiting: Vec::new(),
3185                });
3186            } else {
3187                let list = self.edits(&groups, &edits);
3188                events.push(self.event(now, &token, Outcome::Applied, list, call));
3189                self.last = Some(Last::of(token, groups, &edits));
3190            }
3191        }
3192        Done {
3193            reply: Some(Ok(Reply::Set(SetReply::Applied(Box::new(self.view()))))),
3194            events,
3195        }
3196    }
3197}
3198
3199#[cfg(test)]
3200mod tests {
3201    use super::*;
3202
3203    #[test]
3204    fn time_spells_and_reads_rfc3339() {
3205        assert_eq!(Time::from_millis(0).rfc3339(), "1970-01-01T00:00:00.000Z");
3206        assert_eq!(Time::from_millis(-1).rfc3339(), "1969-12-31T23:59:59.999Z");
3207        let t = Time::parse("2028-02-29T12:34:56.789Z").unwrap();
3208        assert_eq!(t.rfc3339(), "2028-02-29T12:34:56.789Z");
3209        assert_eq!(
3210            Time::parse("2026-10-18T14:00:00+02:00"),
3211            Time::parse("2026-10-18T12:00:00Z")
3212        );
3213        assert_eq!(
3214            Time::parse("2026-10-18t12:00:00.1234z").map(Time::millis),
3215            Time::parse("2026-10-18T12:00:00.123Z").map(Time::millis)
3216        );
3217        for bad in [
3218            "2027-02-29T00:00:00Z",
3219            "2026-13-01T00:00:00Z",
3220            "2026-10-18 12:00:00Z",
3221            "2026-10-18T12:00:00",
3222            "2026-10-18T12:00:00.Z",
3223            "2026-10-18T24:00:00Z",
3224            "",
3225        ] {
3226            assert_eq!(Time::parse(bad), None, "{bad:?}");
3227        }
3228    }
3229
3230    #[test]
3231    fn a_kind_reads_json_as_the_profile_does() {
3232        let int = Kind::Integer {
3233            min: Some(0),
3234            max: Some(10),
3235            unit: None,
3236        };
3237        assert_eq!(int.check(&serde_json::json!(10)), Ok(Value::Integer(10)));
3238        assert_eq!(int.check(&serde_json::json!(11)), Err(Misfit::Above(10)));
3239        assert_eq!(int.check(&serde_json::json!(2.0)), Err(Misfit::Kind));
3240        assert_eq!(int.check(&serde_json::json!(u64::MAX)), Err(Misfit::Range));
3241        assert_eq!(Kind::Bool.check(&serde_json::json!(1)), Err(Misfit::Kind));
3242        assert_eq!(Kind::Text.check(&Json::Null), Err(Misfit::Kind));
3243    }
3244
3245    #[test]
3246    fn the_wire_shapes_are_the_contracts() {
3247        let reply = SetReply::Pending(PendingReply {
3248            token: "i1-1".into(),
3249            apply_at: "1970-01-01T00:00:01.000Z".into(),
3250            deadline: "1970-01-01T00:02:00.000Z".into(),
3251        });
3252        assert_eq!(
3253            serde_json::to_value(&reply).unwrap(),
3254            serde_json::json!({"pending": {"token": "i1-1", "apply_at": "1970-01-01T00:00:01.000Z", "deadline": "1970-01-01T00:02:00.000Z"}})
3255        );
3256        let p = Parameter {
3257            name: "mtu".into(),
3258            kind: Kind::Integer {
3259                min: Some(68),
3260                max: None,
3261                unit: Some("By".into()),
3262            },
3263            description: String::new(),
3264            sensitive: false,
3265            value: Some(Value::Integer(1500)),
3266            source: Some(Source::File),
3267            startup: None,
3268        };
3269        let j = serde_json::to_value(&p).unwrap();
3270        assert_eq!(
3271            j,
3272            serde_json::json!({"name": "mtu", "kind": "integer", "min": 68, "unit": "By", "description": "", "value": 1500, "source": "file"})
3273        );
3274        assert_eq!(serde_json::from_value::<Parameter>(j).unwrap(), p);
3275        let decl: ParamDecl = serde_json::from_value(serde_json::json!({"name": "pin", "kind": "text", "description": "", "sensitive": true, "value": "x"})).unwrap();
3276        assert!(decl.sensitive);
3277        assert_eq!(decl.kind, Kind::Text);
3278    }
3279
3280    /// scenarios.md's `rf`, reduced: `duty` and `sim` hot, `radio` reach.
3281    fn rf() -> Owner {
3282        let int = |min, max| Kind::Integer {
3283            min: Some(min),
3284            max: Some(max),
3285            unit: None,
3286        };
3287        let group = |name: &str, class, p: ParamDecl| GroupDecl {
3288            name: name.into(),
3289            class,
3290            description: String::new(),
3291            writable: true,
3292            parameters: vec![p],
3293        };
3294        let param = |name: &str, kind, sensitive| ParamDecl {
3295            name: name.into(),
3296            kind,
3297            description: String::new(),
3298            sensitive,
3299        };
3300        let schema = Schema {
3301            groups: vec![
3302                group(
3303                    "duty",
3304                    Class::Hot,
3305                    param("fraction_ppm", int(0, 1_000_000), false),
3306                ),
3307                group(
3308                    "radio",
3309                    Class::Reach,
3310                    param("frequency_hz", int(0, 1_000_000_000), false),
3311                ),
3312                group("sim", Class::Hot, param("pin", Kind::Text, true)),
3313                group("tx", Class::Hot, param("power", int(0, 30), false)),
3314            ],
3315        };
3316        let startup = [
3317            ("duty", "fraction_ppm", Value::Integer(10_000)),
3318            ("radio", "frequency_hz", Value::Integer(868_100_000)),
3319            ("tx", "power", Value::Integer(14)),
3320        ]
3321        .into_iter()
3322        .map(|(g, p, v)| {
3323            (
3324                g.to_owned(),
3325                BTreeMap::from([(p.to_owned(), (v, Source::File))]),
3326            )
3327        })
3328        .collect();
3329        Owner::start(Start {
3330            service: "lab/rf0".into(),
3331            instance: "i1".into(),
3332            schema,
3333            startup,
3334            overlay: BTreeMap::new(),
3335            floor_s: 10,
3336            apply_after: Duration::from_secs(1),
3337            persist: true,
3338            events: vec![Time::from_millis(0)],
3339        })
3340        .unwrap()
3341    }
3342
3343    fn doc(revision: u64, values: Json) -> DesiredConfig {
3344        serde_json::from_value(serde_json::json!({"revision": revision, "values": values})).unwrap()
3345    }
3346
3347    /// §2.18 "Converging": one set per differing group, bytewise; a group
3348    /// already at its values is skipped; a pending change is waited out;
3349    /// a reach group refuses the document whole, applying nothing.
3350    #[test]
3351    fn converging_a_desired_document() {
3352        let mut o = rf();
3353        let t = Time::from_millis(10_000);
3354        let d = doc(
3355            1,
3356            serde_json::json!({"tx": {"power": 20}, "duty": {"fraction_ppm": 10000}}),
3357        );
3358        let Converge::Set { group, request } = o.converge(&d) else {
3359            panic!("a set")
3360        };
3361        assert_eq!(group, "tx", "duty already runs its value");
3362        assert_eq!(
3363            request.values,
3364            BTreeMap::from([("power".into(), 20.into())])
3365        );
3366        assert_eq!((request.confirm_s, request.token.as_ref()), (None, None));
3367        let Step::Act(_) = o.set(t, &group, &request, &Call::default()) else {
3368            panic!("a hot apply")
3369        };
3370        let Step::Done(done) = o.finish(t, DeviceResult::Ok) else {
3371            panic!("done")
3372        };
3373        assert_eq!(done.events[0].outcome, Outcome::Applied);
3374        let Converge::Converged(r) = o.converge(&d) else {
3375            panic!("converged")
3376        };
3377        assert_eq!(
3378            (r.observed_revision, r.outcome),
3379            (1, DesiredOutcome::Converged)
3380        );
3381
3382        // A pending change is waited out.
3383        let reach = SetRequest {
3384            values: BTreeMap::from([("frequency_hz".into(), 869_525_000.into())]),
3385            confirm_s: Some(60),
3386            ..SetRequest::default()
3387        };
3388        let _ = o.set(t, "radio", &reach, &Call::default());
3389        assert_eq!(
3390            o.converge(&doc(2, serde_json::json!({"tx": {"power": 1}}))),
3391            Converge::Wait
3392        );
3393
3394        // Refused whole: the reach group, though tx is legal on its own.
3395        let mut o = rf();
3396        let d = doc(
3397            3,
3398            serde_json::json!({"tx": {"power": 1}, "radio": {"frequency_hz": 1}}),
3399        );
3400        let Converge::Refused(r) = o.converge(&d) else {
3401            panic!("refused")
3402        };
3403        assert_eq!(r.outcome, DesiredOutcome::Refused);
3404        assert_eq!(
3405            r.refusal,
3406            Some(DesiredRefusal {
3407                code: DesiredCode::Reach,
3408                group: "radio".into(),
3409                parameter: None
3410            })
3411        );
3412        o.report_desired(Some(r.clone()));
3413        assert_eq!(o.desired(), Some(&r));
3414        assert_eq!(o.view().desired, Some(r));
3415    }
3416
3417    /// §2.18: a converging set refused is `failed`, with its code and group.
3418    #[test]
3419    fn a_converging_set_refused_is_failed() {
3420        let busy = Refusal::busy("the rate");
3421        let r = desired_failed(4, "tx", &busy);
3422        assert_eq!(
3423            (r.observed_revision, r.outcome),
3424            (4, DesiredOutcome::Failed)
3425        );
3426        assert_eq!(r.refusal.as_ref().map(|r| r.code), Some(DesiredCode::Busy));
3427        let refused = Refusal::app(ErrorCode::DeviceRefused, None, "no");
3428        let r = desired_failed(4, "tx", &refused);
3429        assert_eq!(
3430            r.refusal,
3431            Some(DesiredRefusal {
3432                code: DesiredCode::DeviceRefused,
3433                group: "tx".into(),
3434                parameter: None
3435            })
3436        );
3437    }
3438
3439    /// §2.17, core §2.7: the events of the last hour carry to the next
3440    /// instance, and the restart keeps them.
3441    #[test]
3442    fn the_published_events_carry_to_the_next_instance() {
3443        let mut o = rf();
3444        let t = Time::from_millis(3_000_000);
3445        let req = SetRequest {
3446            values: BTreeMap::from([("power".into(), 3.into())]),
3447            ..SetRequest::default()
3448        };
3449        let _ = o.set(t, "tx", &req, &Call::default());
3450        let _ = o.finish(t, DeviceResult::Ok);
3451        assert_eq!(o.published(t), vec![Time::from_millis(0), t]);
3452        let later = Time::from_millis(3_600_000);
3453        assert_eq!(o.published(later), vec![t], "an hour on, the first is out");
3454        assert_eq!(o.restart("i2").published(later), vec![t]);
3455    }
3456
3457    /// §2.12: a re-mint returns the device to its startup values first,
3458    /// each parameter whose running value is not one; a parameter set at
3459    /// runtime that starts unknown cannot be.
3460    #[test]
3461    fn a_restart_plan_returns_what_runs_off_its_startup_value() {
3462        let mut o = rf();
3463        let t = Time::from_millis(3_000_000);
3464        assert_eq!(o.restart_plan(), Ok(Vec::new()), "the startup values run");
3465        let set = |p: &str, v: Json| SetRequest {
3466            values: BTreeMap::from([(p.to_owned(), v)]),
3467            ..SetRequest::default()
3468        };
3469        let _ = o.set(t, "tx", &set("power", 3.into()), &Call::default());
3470        let _ = o.finish(t, DeviceResult::Ok);
3471        assert_eq!(
3472            o.restart_plan(),
3473            Ok(vec![Restore {
3474                group: "tx".into(),
3475                parameter: "power".into(),
3476                value: Value::Integer(14),
3477            }])
3478        );
3479        let _ = o.set(t, "sim", &set("pin", "1234".into()), &Call::default());
3480        let _ = o.finish(t, DeviceResult::Ok);
3481        assert_eq!(
3482            o.restart_plan(),
3483            Err(key("sim", "pin")),
3484            "pin starts unknown"
3485        );
3486        assert_eq!(o.restart("i2").restart_plan(), Ok(Vec::new()));
3487    }
3488
3489    /// §2.15: the device's words about an act that sets a sensitive value,
3490    /// or restores one, are not logged.
3491    #[test]
3492    fn device_words_leave_a_sensitive_act_out() {
3493        let o = rf();
3494        let apply = |g: &str, p: &str, v: Value| Act::Apply {
3495            group: g.into(),
3496            values: BTreeMap::from([(p.into(), v)]),
3497        };
3498        let schema = o.schema();
3499        assert_eq!(
3500            device_words(schema, &apply("tx", "power", Value::Integer(1)), "no"),
3501            Some("no")
3502        );
3503        assert_eq!(
3504            device_words(
3505                schema,
3506                &apply("sim", "pin", Value::Text("1234".into())),
3507                "1234?"
3508            ),
3509            None
3510        );
3511        assert_eq!(
3512            device_words(schema, &apply("nope", "x", Value::Bool(true)), "x"),
3513            None,
3514            "unknown: it cannot tell"
3515        );
3516        let undo = Act::Undo {
3517            restore: vec![Restore {
3518                group: "sim".into(),
3519                parameter: "pin".into(),
3520                value: Value::Text("0000".into()),
3521            }],
3522        };
3523        assert!(undo.carries_sensitive(schema));
3524        assert_eq!(device_words(schema, &undo, "0000"), None);
3525    }
3526}