1use 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
45pub const PROFILE: &str = "config.v1";
47
48pub const IFACE: &str = "config.v1";
50
51pub const VIEW: &str = "view";
53pub const STATUS: &str = "status";
55pub const SET: &str = "set/{group}";
57pub const CONFIRM: &str = "confirm";
59pub const CANCEL: &str = "cancel";
61pub const EXTEND: &str = "extend";
63pub const PERSIST: &str = "persist";
65pub const CHANGE: &str = "change";
67
68pub const TTL: Duration = Duration::from_secs(60);
70pub const REFRESH: Duration = Duration::from_secs(30);
73pub const MAX_GROUPS: usize = 16;
76pub const KEY_HELD: Duration = Duration::from_secs(300);
78pub const RATE: usize = 600;
80pub const RATE_PERIOD: Duration = Duration::from_secs(3600);
82pub const REDACTED: &str = "<redacted>";
84pub const MAX_TOKEN: usize = 64;
86pub const MAX_KEY: usize = 128;
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
93#[serde(rename_all = "lowercase")]
94pub enum Class {
95 Hot,
97 Reach,
100 Contract,
102}
103
104impl Class {
105 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
118#[serde(rename_all = "lowercase")]
119pub enum Source {
120 Default,
122 File,
124 Overlay,
126 Runtime,
128}
129
130impl Source {
131 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "kebab-case")]
146pub enum Outcome {
147 Applied,
149 Confirmed,
151 RolledBack,
153 Partial,
155}
156
157impl Outcome {
158 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
172#[serde(rename_all = "kebab-case")]
173pub enum ErrorCode {
174 RestartRequired,
176 DeviceRefused,
178}
179
180impl ErrorCode {
181 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
193#[serde(rename_all = "lowercase")]
194pub enum Answer {
195 #[default]
197 View,
198 Status,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "lowercase")]
205pub enum DesiredOutcome {
206 Converged,
208 Refused,
210 Failed,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
216pub enum DesiredCode {
217 #[serde(rename = "reach")]
219 Reach,
220 #[serde(rename = "contract")]
222 Contract,
223 #[serde(rename = "sensitive")]
225 Sensitive,
226 #[serde(rename = "not_found")]
228 NotFound,
229 #[serde(rename = "invalid_request")]
231 InvalidRequest,
232 #[serde(rename = "unavailable")]
234 Unavailable,
235 #[serde(rename = "busy")]
237 Busy,
238 #[serde(rename = "device-refused")]
240 DeviceRefused,
241}
242
243impl DesiredCode {
244 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(tag = "kind", rename_all = "lowercase")]
265pub enum Kind {
266 Bool,
268 Integer {
270 #[serde(default, skip_serializing_if = "Option::is_none")]
272 min: Option<i64>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
275 max: Option<i64>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 unit: Option<String>,
279 },
280 Text,
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum Misfit {
287 Kind,
289 Below(i64),
291 Above(i64),
293 Range,
295}
296
297impl Kind {
298 #[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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345pub struct ParamDecl {
346 pub name: String,
348 #[serde(flatten)]
350 pub kind: Kind,
351 pub description: String,
353 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
355 pub sensitive: bool,
356}
357
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
360pub struct GroupDecl {
361 pub name: String,
363 pub class: Class,
365 pub description: String,
367 pub writable: bool,
369 pub parameters: Vec<ParamDecl>,
371}
372
373impl GroupDecl {
374 #[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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
387#[serde(transparent)]
388pub struct Schema {
389 pub groups: Vec<GroupDecl>,
391}
392
393impl Schema {
394 #[must_use]
396 pub fn group(&self, name: &str) -> Option<&GroupDecl> {
397 self.groups.iter().find(|g| g.name == name)
398 }
399
400 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(untagged)]
434pub enum Value {
435 Bool(bool),
437 Integer(i64),
439 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
456pub struct Time(i64);
457
458impl Time {
459 #[must_use]
461 pub const fn from_millis(ms: i64) -> Self {
462 Self(ms)
463 }
464
465 #[must_use]
467 pub const fn millis(self) -> i64 {
468 self.0
469 }
470
471 #[must_use]
473 pub fn from_secs_f64(secs: f64) -> Self {
474 Self((secs * 1000.0).round() as i64)
475 }
476
477 #[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 #[must_use]
488 pub fn plus_secs(self, secs: u64) -> Self {
489 self.plus(Duration::from_secs(secs))
490 }
491
492 #[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 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 #[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 #[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
605fn 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
617fn 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#[must_use]
634pub fn window(confirm_s: u64, floor_s: u64) -> u64 {
635 confirm_s.max(floor_s)
636}
637
638#[must_use]
640pub fn deadline(received: Time, window_s: u64) -> Time {
641 received.plus_secs(window_s)
642}
643
644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
650pub struct Parameter {
651 pub name: String,
653 #[serde(flatten)]
655 pub kind: Kind,
656 pub description: String,
658 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
660 pub sensitive: bool,
661 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub value: Option<Value>,
664 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub source: Option<Source>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
670 pub startup: Option<Value>,
671}
672
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
675pub struct GroupView {
676 pub name: String,
678 pub class: Class,
680 pub description: String,
682 pub writable: bool,
684 pub parameters: Vec<Parameter>,
686}
687
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
690pub struct Pending {
691 pub token: String,
693 pub groups: Vec<String>,
695 pub deadline: String,
697 pub applied: bool,
699}
700
701#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703pub struct LastChange {
704 pub token: String,
706 pub groups: Vec<String>,
708}
709
710#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
712pub struct DesiredRefusal {
713 pub code: DesiredCode,
715 pub group: String,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub parameter: Option<String>,
720}
721
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
724pub struct DesiredReport {
725 pub observed_revision: u64,
727 pub outcome: DesiredOutcome,
729 #[serde(default, skip_serializing_if = "Option::is_none")]
731 pub refusal: Option<DesiredRefusal>,
732}
733
734#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
736pub struct ConfigView {
737 pub service: String,
739 pub instance: String,
741 pub revision: u64,
743 pub confirm_floor_s: u64,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
747 pub pending: Option<Pending>,
748 #[serde(default, skip_serializing_if = "Option::is_none")]
750 pub last_change: Option<LastChange>,
751 #[serde(default, skip_serializing_if = "Option::is_none")]
753 pub desired: Option<DesiredReport>,
754 pub groups: Vec<GroupView>,
756}
757
758#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
760pub struct ConfigStatus {
761 pub instance: String,
763 pub revision: u64,
765 pub confirm_floor_s: u64,
767 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub pending: Option<Pending>,
770 #[serde(default, skip_serializing_if = "Option::is_none")]
772 pub last_change: Option<LastChange>,
773 #[serde(default, skip_serializing_if = "Option::is_none")]
775 pub desired: Option<DesiredReport>,
776 pub values: BTreeMap<String, BTreeMap<String, Value>>,
779}
780
781impl ConfigStatus {
782 #[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
813pub struct SetRequest {
814 pub values: BTreeMap<String, Json>,
816 #[serde(default, skip_serializing_if = "Option::is_none")]
818 pub confirm_s: Option<u64>,
819 #[serde(default, skip_serializing_if = "Option::is_none")]
821 pub token: Option<String>,
822 #[serde(default, skip_serializing_if = "Option::is_none")]
824 pub expected_revision: Option<u64>,
825 #[serde(default, skip_serializing_if = "Option::is_none")]
827 pub idempotency_key: Option<String>,
828 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
830 pub dry_run: bool,
831}
832
833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
835pub struct PendingReply {
836 pub token: String,
838 pub apply_at: String,
840 pub deadline: String,
842}
843
844#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(rename_all = "lowercase")]
848pub enum SetReply {
849 Applied(Box<ConfigView>),
851 Pending(PendingReply),
853}
854
855#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
857pub struct ControlRequest {
858 pub token: String,
860 #[serde(default, skip_serializing_if = "Option::is_none")]
862 pub confirm_s: Option<u64>,
863 #[serde(default, skip_serializing_if = "Option::is_none")]
865 pub answer: Option<Answer>,
866}
867
868#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
871#[serde(rename_all = "lowercase")]
872pub enum ControlReply {
873 View(Box<ConfigView>),
875 Status(Box<ConfigStatus>),
877}
878
879#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
881pub struct Edit {
882 pub group: String,
884 pub parameter: String,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
888 pub old: Option<Value>,
889 #[serde(default, skip_serializing_if = "Option::is_none")]
891 pub new: Option<Value>,
892 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
894 pub redacted: bool,
895}
896
897#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
899pub struct ConfigChangeEvent {
900 pub service: String,
902 pub instance: String,
904 pub revision: u64,
906 pub token: String,
908 pub outcome: Outcome,
910 pub edits: Vec<Edit>,
912 #[serde(default, skip_serializing_if = "Option::is_none")]
914 pub actor: Option<String>,
915 #[serde(default, skip_serializing_if = "Option::is_none")]
917 pub request_id: Option<String>,
918 #[serde(default, skip_serializing_if = "Option::is_none")]
920 pub claimed_source: Option<String>,
921}
922
923#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
925pub struct ConfigError {
926 pub code: ErrorCode,
928 #[serde(default, skip_serializing_if = "Option::is_none")]
930 pub detail: Option<String>,
931}
932
933#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
936pub struct DesiredConfig {
937 pub revision: u64,
939 pub values: BTreeMap<String, BTreeMap<String, Json>>,
941}
942
943#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
948pub enum Code {
949 InvalidRequest,
951 NotFound,
953 Unavailable,
955 Forbidden,
957 Busy,
959 App,
961}
962
963impl Code {
964 #[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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
980pub enum Field {
981 Group,
983 Member(String),
985}
986
987impl Field {
988 #[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#[derive(Debug, Clone, PartialEq, Eq)]
1013pub struct Refusal {
1014 pub code: Code,
1016 pub app: Option<ConfigError>,
1018 pub field: Option<Field>,
1021 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 #[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#[derive(Debug, Clone, Copy, Default)]
1067pub struct Facts<'a> {
1068 pub revision: u64,
1070 pub pending: Option<PendingFacts<'a>>,
1072 pub last_change: Option<LastFacts<'a>>,
1074 pub persist: bool,
1076 pub in_flight: bool,
1078}
1079
1080#[derive(Debug, Clone, Copy)]
1082pub struct PendingFacts<'a> {
1083 pub token: &'a str,
1085 pub applied: bool,
1087 pub deadline_passed: bool,
1089}
1090
1091#[derive(Debug, Clone, Copy)]
1093pub struct LastFacts<'a> {
1094 pub token: &'a str,
1096 pub set_sensitive: bool,
1098}
1099
1100#[derive(Debug, Clone, PartialEq, Eq)]
1102pub struct Admitted {
1103 pub class: Class,
1105 pub values: BTreeMap<String, Value>,
1107 pub joins: bool,
1109 pub dry_run: bool,
1111}
1112
1113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1115pub enum ControlOp {
1116 Confirm,
1118 Cancel,
1120 Extend,
1122 Persist,
1124}
1125
1126impl ControlOp {
1127 #[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
1143fn 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
1160fn 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
1202fn 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
1223fn is_u64(v: &Json) -> bool {
1228 v.as_number().is_some_and(serde_json::Number::is_u64)
1229}
1230
1231fn 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
1266pub 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
1313pub 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
1349pub 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
1365pub 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
1406fn 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
1512pub 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
1534pub 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
1615pub 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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
1704pub struct Call {
1705 pub actor: Option<String>,
1707 pub request_id: Option<String>,
1709}
1710
1711#[derive(Debug, Clone)]
1714pub struct Start {
1715 pub service: String,
1717 pub instance: String,
1719 pub schema: Schema,
1721 pub startup: BTreeMap<String, BTreeMap<String, (Value, Source)>>,
1725 pub overlay: BTreeMap<String, BTreeMap<String, Value>>,
1727 pub floor_s: u64,
1729 pub apply_after: Duration,
1733 pub persist: bool,
1735 pub events: Vec<Time>,
1737}
1738
1739#[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#[derive(Debug, Clone, PartialEq, Eq)]
1754pub enum Act {
1755 Apply {
1757 group: String,
1759 values: BTreeMap<String, Value>,
1761 },
1762 Undo {
1765 restore: Vec<Restore>,
1767 },
1768}
1769
1770#[derive(Debug, Clone, PartialEq, Eq)]
1772pub struct Restore {
1773 pub group: String,
1775 pub parameter: String,
1777 pub value: Value,
1779}
1780
1781#[derive(Debug, Clone, PartialEq, Eq)]
1785pub enum DeviceResult {
1786 Ok,
1788 Refused(String),
1790 Failed {
1793 words: String,
1795 readback: BTreeMap<String, BTreeMap<String, Value>>,
1797 },
1798}
1799
1800impl Act {
1801 #[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#[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#[derive(Debug, Clone, PartialEq)]
1824pub enum Converge {
1825 Wait,
1827 Refused(DesiredReport),
1829 Set {
1833 group: String,
1835 request: SetRequest,
1837 },
1838 Converged(DesiredReport),
1840}
1841
1842#[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 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#[derive(Debug, Clone, PartialEq, Eq)]
1869pub enum Reply {
1870 Set(SetReply),
1872 Control(ControlReply),
1874}
1875
1876impl Reply {
1877 #[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
1891pub struct Done {
1892 pub reply: Option<Result<Reply, Refusal>>,
1895 pub events: Vec<ConfigChangeEvent>,
1897}
1898
1899#[derive(Debug, Clone, PartialEq, Eq)]
1903pub enum Step {
1904 Done(Done),
1906 Act(Act),
1908}
1909
1910#[derive(Debug, Clone, PartialEq, Eq)]
1913pub struct PersistPlan {
1914 pub token: String,
1916 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 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#[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 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 #[must_use]
2190 pub fn whole_seconds(mut self) -> Self {
2191 self.whole_seconds = true;
2192 self
2193 }
2194
2195 fn stated(&self, t: Time) -> Time {
2198 if self.whole_seconds {
2199 t.ceil_second()
2200 } else {
2201 t
2202 }
2203 }
2204
2205 #[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 #[must_use]
2245 pub fn schema(&self) -> &Schema {
2246 &self.schema
2247 }
2248
2249 #[must_use]
2251 pub fn instance(&self) -> &str {
2252 &self.instance
2253 }
2254
2255 #[must_use]
2257 pub fn revision(&self) -> u64 {
2258 self.revision
2259 }
2260
2261 #[must_use]
2263 pub fn in_flight(&self) -> bool {
2264 self.flight.is_some()
2265 }
2266
2267 #[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 #[must_use]
2278 pub fn deadline(&self) -> Option<Time> {
2279 self.pending.as_ref().map(|c| c.deadline)
2280 }
2281
2282 #[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 pub fn report_desired(&mut self, report: Option<DesiredReport>) {
2292 self.desired = report;
2293 }
2294
2295 #[must_use]
2297 pub fn desired(&self) -> Option<&DesiredReport> {
2298 self.desired.as_ref()
2299 }
2300
2301 #[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 #[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 #[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 #[must_use]
2395 pub fn startup(&self, group: &str, parameter: &str) -> Option<(Value, Source)> {
2396 self.startup_value(&key(group, parameter))
2397 }
2398
2399 #[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 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 #[must_use]
2516 pub fn view(&self) -> ConfigView {
2517 self.render(&self.slots)
2518 }
2519
2520 #[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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 #[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 #[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 #[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 #[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}