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