1use std::collections::BTreeMap;
38use std::sync::OnceLock;
39
40use serde_json::{Map, Value, json};
41
42use super::{
43 ActKind, Answer, Content, Finding, Invalid, Judged, Mutation, Reason, Reported, Seen, Source,
44 TargetReading, Via, machine,
45};
46use crate::authoring::{Kind, ParamType};
47use crate::contract::{Body, Contract, Resource};
48use crate::grammar::{self, Addr, IfaceId, Key, KindToken};
49use crate::heartbeat::Digest;
50use crate::packed::{self, Layout, ReadRefusal, Record, WriteRefusal};
51use crate::schema::TypeId;
52use crate::template::{Bindings, Template};
53use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
54use crate::words;
55
56pub const PROFILE: &str = "desired.v2";
58
59pub const REPORT_KEY: &str = "desired.report";
61pub const POINTERS: &str = "desired.pointers";
63pub const DETAILS: &str = "desired.details";
65
66pub const VOCABULARY: &[&str] = &["target_param", "report", "pointers", "details"];
69
70pub const SCHEMA_STEM: &str = "desired.v2";
72pub const REPORT: &str = "Report";
74
75pub const PUBLISHED: &[&str] =
78 &["sha256:1ac893a1cb14a102cc1b01ea526a317b19390a8ed6c40707f08754f4429532dd"];
79
80pub const TAG: u8 = 12;
83
84pub const MAX_REVISION: u64 = 4_294_967_295;
87
88pub const REMEMBERED_RUNS: usize = super::REMEMBERED_IDS;
90
91pub use crate::words::OUT_OF_RANGE;
93
94pub const MAX_INDEX: u8 = 254;
96
97#[must_use]
99pub fn is_published(id: &str) -> bool {
100 PUBLISHED.contains(&id)
101}
102
103#[must_use]
106pub fn uses_v2(c: &Contract) -> bool {
107 words::uses(c, PROFILE)
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum Major {
114 V1,
115 V2,
116}
117
118impl Major {
119 #[must_use]
121 pub fn of(c: &Contract) -> Option<Major> {
122 if uses_v2(c) {
123 Some(Major::V2)
124 } else if c.uses.iter().any(|u| u.to_string() == super::PROFILE) {
125 Some(Major::V1)
126 } else {
127 None
128 }
129 }
130}
131
132pub type Version = Stamp;
137
138#[must_use]
142pub fn version_text(v: Version) -> String {
143 format!("{}/{}", v.run, v.seq.get())
144}
145
146#[must_use]
150pub fn parse_version(s: &str) -> Option<Version> {
151 let (run, seq) = s.split_once('/')?;
152 let digits = !seq.is_empty() && seq.len() <= 8 && seq.bytes().all(|b| b.is_ascii_digit());
153 if !digits || (seq.len() > 1 && seq.starts_with('0')) {
154 return None;
155 }
156 Some(Stamp {
157 run: Run::from_hex(run)?,
158 seq: Seq::new(seq.parse().ok()?)?,
159 })
160}
161
162#[must_use]
171pub fn declaration(
172 kind: Kind,
173 template: &Template,
174 params: &BTreeMap<String, ParamType>,
175 annotations: &BTreeMap<String, Value>,
176 uses: impl Fn(&str) -> bool,
177) -> super::Declaration {
178 let v1 = super::declaration(kind, template, params, annotations);
179 let horizon_v1 = kind == Kind::State
181 && crate::freshness::horizon(kind, annotations).ttl().is_some()
182 && !uses(crate::freshness::PROFILE_V2);
183 match v1 {
184 super::Declaration::NotThisProfiles => v1,
185 super::Declaration::Declared(_) if !horizon_v1 => v1,
186 super::Declaration::Declared(_) => super::Declaration::Invalid(vec![Invalid::HorizonV1]),
187 super::Declaration::Invalid(mut why) => {
188 if horizon_v1 {
189 why.push(Invalid::HorizonV1);
190 }
191 super::Declaration::Invalid(why)
192 }
193 }
194}
195
196#[must_use]
198pub fn declaration_of(c: &Contract, r: &Resource) -> super::Declaration {
199 declaration(r.kind, &r.template, &r.params, &r.annotations, |p| {
200 c.uses.iter().any(|u| u.to_string() == p)
201 })
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
208pub enum Names {
209 Role(String),
211 Param(String),
214}
215
216impl Names {
217 #[must_use]
221 pub fn read(v: &Value) -> Option<Names> {
222 let s = v.as_str()?;
223 let name = |n: &str| !n.is_empty() && !n.contains(['{', '}']);
224 if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
225 return name(inner).then(|| Names::Param(inner.to_owned()));
226 }
227 name(s).then(|| Names::Role(s.to_owned()))
228 }
229
230 #[must_use]
233 pub fn names(&self, role: &str) -> bool {
234 match self {
235 Names::Role(r) => r == role,
236 Names::Param(_) => true,
237 }
238 }
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244pub enum ReportInvalid {
245 NotState,
247 Value,
250 NotARole,
252 NotAParam,
254 RestParam,
256 ParamNotRole,
258 NotReport,
260 Pointers,
262 Details,
264 TwoReports,
267}
268
269impl ReportInvalid {
270 #[must_use]
272 pub fn as_str(self) -> &'static str {
273 match self {
274 Self::NotState => "not_state",
275 Self::Value => "value",
276 Self::NotARole => "not_a_role",
277 Self::NotAParam => "not_a_param",
278 Self::RestParam => "rest_param",
279 Self::ParamNotRole => "param_not_role",
280 Self::NotReport => "not_report",
281 Self::Pointers => "pointers",
282 Self::Details => "details",
283 Self::TwoReports => "two_reports",
284 }
285 }
286
287 #[must_use]
289 pub fn says(self) -> &'static str {
290 match self {
291 Self::NotState => "a report is state of its target",
292 Self::Value => {
293 "desired.report is a role's name, or the resource's one parameter in braces"
294 }
295 Self::NotARole => "the name is no requirement of the contract",
296 Self::NotAParam => "the name in braces is no parameter of the template",
297 Self::RestParam => "a rest parameter cannot name a role",
298 Self::ParamNotRole => {
299 "a template parameter the value does not name: one report per role"
300 }
301 Self::NotReport => "a report resource's type is the profile's packed Report",
302 Self::Pointers => {
303 "desired.pointers is 1 to 255 JSON Pointers, the first \"\", none twice"
304 }
305 Self::Details => "desired.details is at most 255 lines of at least one character",
306 Self::TwoReports => "another report resource of the contract can report the same role",
307 }
308 }
309}
310
311impl std::fmt::Display for ReportInvalid {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 f.write_str(self.says())
314 }
315}
316
317pub use crate::words::{Index, Word};
325
326#[must_use]
329pub fn word(table: Option<&[String]>, index: Index) -> Word<'_> {
330 words::read(table, index)
331}
332
333#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct Tables {
336 pub pointers: Vec<String>,
338 pub details: Vec<String>,
340}
341
342impl Default for Tables {
343 fn default() -> Self {
344 Self {
345 pointers: vec![String::new()],
346 details: Vec::new(),
347 }
348 }
349}
350
351fn index_of(i: usize) -> Index {
352 Index::at(i, MAX_INDEX)
353}
354
355impl Tables {
356 #[must_use]
362 pub fn place(&self, pointer: &str) -> Index {
363 if let Some(i) = self.pointers.iter().position(|p| p == pointer) {
364 return index_of(i);
365 }
366 self.pointers
367 .iter()
368 .enumerate()
369 .filter(|(_, p)| {
370 !p.is_empty()
371 && pointer
372 .strip_prefix(p.as_str())
373 .is_some_and(|rest| rest.starts_with('/'))
374 })
375 .max_by_key(|(_, p)| p.len())
376 .map_or(Index::OutOfRange, |(i, _)| index_of(i))
377 }
378
379 #[must_use]
383 pub fn line(&self, text: &str) -> Index {
384 words::write(&self.details, text, MAX_INDEX)
385 }
386
387 #[must_use]
389 pub fn pointer(&self, index: Index) -> Word<'_> {
390 word(Some(&self.pointers), index)
391 }
392
393 #[must_use]
395 pub fn detail(&self, index: Index) -> Word<'_> {
396 word(Some(&self.details), index)
397 }
398}
399
400fn is_json_pointer(s: &str) -> bool {
403 if !(s.is_empty() || s.starts_with('/')) {
404 return false;
405 }
406 let b = s.as_bytes();
407 (0..b.len()).all(|i| b[i] != b'~' || matches!(b.get(i + 1), Some(b'0' | b'1')))
408}
409
410fn read_pointers(v: &Value) -> Option<Vec<String>> {
413 words::list(v, usize::from(MAX_INDEX) + 1, is_json_pointer, true)
414 .filter(|out| out.first().is_some_and(String::is_empty))
415}
416
417fn read_details(v: &Value) -> Option<Vec<String>> {
420 words::list(v, usize::from(MAX_INDEX) + 1, |d| !d.is_empty(), false)
421}
422
423#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum ReportDeclaration {
426 NotThisProfiles,
428 Invalid(Vec<ReportInvalid>),
430 Declared { names: Names, tables: Tables },
432}
433
434impl ReportDeclaration {
435 #[must_use]
437 pub fn as_str(&self) -> &'static str {
438 match self {
439 Self::NotThisProfiles => "not_this_profiles",
440 Self::Invalid(_) => "invalid",
441 Self::Declared { .. } => "declared",
442 }
443 }
444}
445
446#[must_use]
450pub fn is_report(ty: &TypeId) -> bool {
451 matches!(ty, TypeId::Packed { name, schema } if name == REPORT && is_published(schema))
452}
453
454#[derive(Debug, Clone, Copy)]
457pub struct ReportResource<'a> {
458 pub kind: Kind,
459 pub token: KindToken,
460 pub template: &'a Template,
461 pub is_report: bool,
463 pub annotations: &'a BTreeMap<String, Value>,
465}
466
467impl<'a> ReportResource<'a> {
468 #[must_use]
470 pub fn of(r: &'a Resource) -> Self {
471 Self {
472 kind: r.kind,
473 token: r.token,
474 template: &r.template,
475 is_report: matches!(&r.body, Body::Data(d) if is_report(&d.type_)),
476 annotations: &r.annotations,
477 }
478 }
479}
480
481#[must_use]
489pub fn report_declaration<'v>(
490 r: &ReportResource<'_>,
491 is_role: impl Fn(&str) -> bool,
492 others: impl IntoIterator<Item = &'v Value>,
493) -> ReportDeclaration {
494 let Some(v) = r.annotations.get(REPORT_KEY) else {
495 return ReportDeclaration::NotThisProfiles;
496 };
497 let mut why = Vec::new();
498 if r.kind != Kind::State {
499 why.push(ReportInvalid::NotState);
500 }
501 let names = Names::read(v);
502 let params: Vec<(&str, bool)> = r.template.params().collect();
503 match &names {
504 None => why.push(ReportInvalid::Value),
505 Some(Names::Role(name)) => {
506 if !is_role(name) {
507 why.push(ReportInvalid::NotARole);
508 }
509 if !params.is_empty() {
510 why.push(ReportInvalid::ParamNotRole);
511 }
512 }
513 Some(Names::Param(name)) => match params.iter().find(|(p, _)| p == name) {
514 None => why.push(ReportInvalid::NotAParam),
515 Some((_, true)) => why.push(ReportInvalid::RestParam),
516 Some((_, false)) => {
517 if params.iter().any(|(p, _)| p != name) {
518 why.push(ReportInvalid::ParamNotRole);
519 }
520 }
521 },
522 }
523 if !r.is_report {
524 why.push(ReportInvalid::NotReport);
525 }
526 let pointers = match r.annotations.get(POINTERS) {
527 None => Some(Tables::default().pointers),
528 Some(v) => read_pointers(v),
529 };
530 if pointers.is_none() {
531 why.push(ReportInvalid::Pointers);
532 }
533 let details = match r.annotations.get(DETAILS) {
534 None => Some(Vec::new()),
535 Some(v) => read_details(v),
536 };
537 if details.is_none() {
538 why.push(ReportInvalid::Details);
539 }
540 if let Some(mine) = &names {
541 let clash = |other: &Names| match (mine, other) {
542 (Names::Role(a), Names::Role(b)) => a == b,
543 _ => true,
544 };
545 if others
546 .into_iter()
547 .filter_map(Names::read)
548 .any(|o| clash(&o))
549 {
550 why.push(ReportInvalid::TwoReports);
551 }
552 }
553 match (names, pointers, details) {
554 (Some(names), Some(pointers), Some(details)) if why.is_empty() => {
555 ReportDeclaration::Declared {
556 names,
557 tables: Tables { pointers, details },
558 }
559 }
560 _ => ReportDeclaration::Invalid(why),
561 }
562}
563
564#[must_use]
567pub fn report_declaration_of(c: &Contract, r: &Resource) -> ReportDeclaration {
568 report_declaration(
569 &ReportResource::of(r),
570 |name| c.requires.contains_key(name),
571 c.resources
572 .iter()
573 .filter(|o| !(o.token == r.token && o.template.as_str() == r.template.as_str()))
574 .filter_map(|o| o.annotations.get(REPORT_KEY)),
575 )
576}
577
578pub use crate::words::Lint;
582
583#[must_use]
587pub fn lint_contract(c: &Contract) -> Vec<Lint> {
588 if !uses_v2(c) {
589 return Vec::new();
590 }
591 let mut out = Vec::new();
592 for r in &c.resources {
593 let finding = |token, says| Lint {
594 profile: PROFILE,
595 at: Lint::place(r),
596 key: None,
597 token,
598 says,
599 };
600 if let super::Declaration::Invalid(why) = declaration_of(c, r) {
601 out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
602 }
603 if let ReportDeclaration::Invalid(why) = report_declaration_of(c, r) {
604 out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
605 }
606 }
607 out
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
615pub enum Outcome {
616 NotActed,
617 Converged,
618 Refused,
619 Failed,
620 Reverted,
621}
622
623impl Outcome {
624 const ALL: [Outcome; 5] = [
625 Outcome::NotActed,
626 Outcome::Converged,
627 Outcome::Refused,
628 Outcome::Failed,
629 Outcome::Reverted,
630 ];
631
632 #[must_use]
634 pub fn as_str(self) -> &'static str {
635 match self {
636 Self::NotActed => "not_acted",
637 Self::Converged => "converged",
638 Self::Refused => "refused",
639 Self::Failed => "failed",
640 Self::Reverted => "reverted",
641 }
642 }
643
644 fn parse(s: &str) -> Option<Self> {
645 Self::ALL.into_iter().find(|o| o.as_str() == s)
646 }
647
648 #[must_use]
651 pub fn acted(self) -> Option<super::Outcome> {
652 match self {
653 Self::NotActed => None,
654 Self::Converged => Some(super::Outcome::Converged),
655 Self::Refused => Some(super::Outcome::Refused),
656 Self::Failed => Some(super::Outcome::Failed),
657 Self::Reverted => Some(super::Outcome::Reverted),
658 }
659 }
660}
661
662impl From<Option<super::Outcome>> for Outcome {
663 fn from(o: Option<super::Outcome>) -> Self {
664 match o {
665 None => Self::NotActed,
666 Some(super::Outcome::Converged) => Self::Converged,
667 Some(super::Outcome::Refused) => Self::Refused,
668 Some(super::Outcome::Failed) => Self::Failed,
669 Some(super::Outcome::Reverted) => Self::Reverted,
670 }
671 }
672}
673
674#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
677pub enum Code {
678 Undecodable,
679 Reach,
680 Sensitive,
681 Invalid,
682 Apply,
683 Own,
686}
687
688impl Code {
689 const NAMED: [Code; 5] = [
690 Code::Undecodable,
691 Code::Reach,
692 Code::Sensitive,
693 Code::Invalid,
694 Code::Apply,
695 ];
696
697 #[must_use]
699 pub fn as_str(self) -> Option<&'static str> {
700 match self {
701 Self::Undecodable => Some(super::UNDECODABLE),
702 Self::Reach => Some(super::REACH),
703 Self::Sensitive => Some(super::SENSITIVE),
704 Self::Invalid => Some(super::INVALID),
705 Self::Apply => Some(super::APPLY),
706 Self::Own => None,
707 }
708 }
709
710 #[must_use]
713 pub fn of(code: &str) -> Code {
714 Self::NAMED
715 .into_iter()
716 .find(|c| c.as_str() == Some(code))
717 .unwrap_or(Code::Own)
718 }
719
720 fn to_json(self) -> Value {
721 self.as_str().map_or(Value::Null, Value::from)
722 }
723
724 fn of_json(v: &Value) -> Result<Code, WriteRefusal> {
727 match v {
728 Value::Null => Ok(Code::Own),
729 Value::String(s) => Self::NAMED
730 .into_iter()
731 .find(|c| c.as_str() == Some(s.as_str()))
732 .ok_or(WriteRefusal::Value),
733 _ => Err(WriteRefusal::Value),
734 }
735 }
736}
737
738#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
742pub struct Refusal {
743 pub code: Code,
744 pub pointer: Option<Index>,
745 pub detail: Option<Index>,
746}
747
748impl Refusal {
749 #[must_use]
751 pub fn new(code: Code) -> Self {
752 Self {
753 code,
754 pointer: None,
755 detail: None,
756 }
757 }
758}
759
760#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
763pub struct Observed {
764 pub version: Version,
765 pub revision: Option<u64>,
768}
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
772pub enum InForce {
773 #[default]
775 None,
776 Observed,
778 Other,
780}
781
782impl InForce {
783 const ALL: [InForce; 3] = [InForce::None, InForce::Observed, InForce::Other];
784
785 #[must_use]
787 pub fn as_str(self) -> &'static str {
788 match self {
789 Self::None => "none",
790 Self::Observed => "observed",
791 Self::Other => "other",
792 }
793 }
794}
795
796fn schema() -> Value {
801 let int = |name: &str, maximum: u64| json!({"name": name, "type": "int", "minimum": 0, "maximum": maximum, "optional": true});
802 let index = |name: &str| {
803 json!({"name": name, "type": "int", "minimum": 0, "maximum": MAX_INDEX,
804 "reserved": [OUT_OF_RANGE], "optional": true})
805 };
806 json!({"types": {(REPORT): {"fields": [
807 {"name": "source", "type": "enum", "values": ["baseline", "desired", "call"], "escape": true},
808 {"name": "outcome", "type": "enum",
809 "values": ["not_acted", "converged", "refused", "failed", "reverted"], "escape": true},
810 {"name": "last_known", "type": "bool"},
811 {"name": "in_force", "type": "enum", "values": ["none", "observed", "other"]},
812 int("observed_run16", 65_535),
813 int("observed_run32", MAX_REVISION),
814 int("observed_seq", 16_777_215),
815 int("revision", MAX_REVISION),
816 int("in_force_run16", 65_535),
817 int("in_force_run32", MAX_REVISION),
818 int("in_force_seq", 16_777_215),
819 int("in_force_revision", MAX_REVISION),
820 {"name": "code", "type": "enum",
821 "values": ["undecodable", "reach", "sensitive", "invalid", "apply"],
822 "escape": true, "optional": true},
823 index("pointer"),
824 index("detail"),
825 packed::MARKER,
826 ]}}})
827}
828
829#[must_use]
832pub fn layout() -> &'static Layout {
833 static LAYOUT: OnceLock<Layout> = OnceLock::new();
834 LAYOUT.get_or_init(|| {
835 packed::layout_in(&schema(), REPORT).expect("the standard Report's declaration reads")
836 })
837}
838
839#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
844pub struct Fields {
845 pub source: Option<Source>,
847 pub outcome: Option<Outcome>,
849 pub last_known: bool,
850 pub in_force: InForce,
851 pub observed_run16: Option<u16>,
852 pub observed_run32: Option<u32>,
853 pub observed_seq: Option<u32>,
854 pub revision: Option<u32>,
855 pub in_force_run16: Option<u16>,
856 pub in_force_run32: Option<u32>,
857 pub in_force_seq: Option<u32>,
858 pub in_force_revision: Option<u32>,
859 pub code: Option<Code>,
860 pub pointer: Option<Index>,
861 pub detail: Option<Index>,
862}
863
864fn stated(run16: Option<u16>, run32: Option<u32>, seq: Option<u32>) -> Option<Version> {
867 let run = match (run16, run32) {
868 (Some(r), None) => Run::U16(r),
869 (None, Some(r)) => Run::U32(r),
870 _ => return None,
871 };
872 Some(Stamp {
873 run,
874 seq: Seq::new(seq?)?,
875 })
876}
877
878impl Fields {
879 #[must_use]
881 pub fn observed(&self) -> Option<Version> {
882 stated(self.observed_run16, self.observed_run32, self.observed_seq)
883 }
884
885 #[must_use]
888 pub fn other_in_force(&self) -> Option<Version> {
889 stated(self.in_force_run16, self.in_force_run32, self.in_force_seq)
890 }
891
892 #[must_use]
895 pub fn to_json(&self) -> Value {
896 let mut m = Map::new();
897 let mut put = |k: &str, v: Option<Value>| {
898 if let Some(v) = v {
899 m.insert(k.to_owned(), v);
900 }
901 };
902 put(
903 "source",
904 Some(self.source.map_or(Value::Null, |s| json!(s.as_str()))),
905 );
906 put(
907 "outcome",
908 Some(self.outcome.map_or(Value::Null, |o| json!(o.as_str()))),
909 );
910 put("last_known", Some(json!(self.last_known)));
911 put("in_force", Some(json!(self.in_force.as_str())));
912 put("observed_run16", self.observed_run16.map(Value::from));
913 put("observed_run32", self.observed_run32.map(Value::from));
914 put("observed_seq", self.observed_seq.map(Value::from));
915 put("revision", self.revision.map(Value::from));
916 put("in_force_run16", self.in_force_run16.map(Value::from));
917 put("in_force_run32", self.in_force_run32.map(Value::from));
918 put("in_force_seq", self.in_force_seq.map(Value::from));
919 put("in_force_revision", self.in_force_revision.map(Value::from));
920 put("code", self.code.map(Code::to_json));
921 put("pointer", self.pointer.map(Index::to_json));
922 put("detail", self.detail.map(Index::to_json));
923 Value::Object(m)
924 }
925
926 pub fn of_json(v: &Value) -> Result<Fields, WriteRefusal> {
934 let Value::Object(o) = v else {
935 return Err(WriteRefusal::Value);
936 };
937 let number = |k: &str, max: u64| -> Result<Option<u64>, WriteRefusal> {
938 match o.get(k) {
939 None => Ok(None),
940 Some(Value::Number(n)) => match n.as_u64() {
941 Some(x) if x <= max => Ok(Some(x)),
942 _ => Err(WriteRefusal::Range),
943 },
944 Some(_) => Err(WriteRefusal::Value),
945 }
946 };
947 #[allow(clippy::cast_possible_truncation)]
948 let u16_of = |k: &str| number(k, u64::from(u16::MAX)).map(|x| x.map(|x| x as u16));
949 #[allow(clippy::cast_possible_truncation)]
950 let u32_of = |k: &str| number(k, u64::from(u32::MAX)).map(|x| x.map(|x| x as u32));
951 let named = |k: &str| match o.get(k) {
952 Some(Value::String(s)) => Ok(Some(s.as_str())),
953 Some(Value::Null) => Ok(None),
954 Some(_) => Err(WriteRefusal::Value),
955 None => Err(WriteRefusal::Missing),
956 };
957 let source = match named("source")? {
958 None => None,
959 Some(s) => Some(
960 [Source::Baseline, Source::Desired, Source::Call]
961 .into_iter()
962 .find(|x| x.as_str() == s)
963 .ok_or(WriteRefusal::Value)?,
964 ),
965 };
966 let outcome = match named("outcome")? {
967 None => None,
968 Some(s) => Some(Outcome::parse(s).ok_or(WriteRefusal::Value)?),
969 };
970 let in_force = match o.get("in_force") {
971 Some(Value::String(s)) => InForce::ALL
972 .into_iter()
973 .find(|x| x.as_str() == s)
974 .ok_or(WriteRefusal::Value)?,
975 Some(_) => return Err(WriteRefusal::Value),
976 None => return Err(WriteRefusal::Missing),
977 };
978 let last_known = match o.get("last_known") {
979 Some(Value::Bool(b)) => *b,
980 Some(_) => return Err(WriteRefusal::Value),
981 None => return Err(WriteRefusal::Missing),
982 };
983 Ok(Fields {
984 source,
985 outcome,
986 last_known,
987 in_force,
988 observed_run16: u16_of("observed_run16")?,
989 observed_run32: u32_of("observed_run32")?,
990 observed_seq: u32_of("observed_seq")?,
991 revision: u32_of("revision")?,
992 in_force_run16: u16_of("in_force_run16")?,
993 in_force_run32: u32_of("in_force_run32")?,
994 in_force_seq: u32_of("in_force_seq")?,
995 in_force_revision: u32_of("in_force_revision")?,
996 code: o.get("code").map(Code::of_json).transpose()?,
997 pointer: o.get("pointer").map(Index::of_json).transpose()?,
998 detail: o.get("detail").map(Index::of_json).transpose()?,
999 })
1000 }
1001
1002 pub fn record(&self) -> Result<Record, WriteRefusal> {
1008 layout().write(&self.to_json(), None)
1009 }
1010
1011 #[must_use]
1015 pub fn check(&self) -> Vec<Finding> {
1016 let (Some(source), Some(outcome)) = (self.source, self.outcome) else {
1017 return vec![Finding::Escape];
1018 };
1019 let mut out = Vec::new();
1020 let observed = self.observed();
1021 let other = self.other_in_force();
1022 let any_observed = self.observed_run16.is_some()
1023 || self.observed_run32.is_some()
1024 || self.observed_seq.is_some()
1025 || self.revision.is_some();
1026 let any_other = self.in_force_run16.is_some()
1027 || self.in_force_run32.is_some()
1028 || self.in_force_seq.is_some()
1029 || self.in_force_revision.is_some();
1030 if (any_observed && observed.is_none()) || (any_other && other.is_none()) {
1031 out.push(Finding::RunFields);
1032 }
1033 let acted = matches!(
1034 outcome,
1035 Outcome::Converged | Outcome::Refused | Outcome::Failed
1036 );
1037 if (observed.is_some() && outcome == Outcome::NotActed) || (acted && observed.is_none()) {
1038 out.push(Finding::ObservedOutcome);
1039 }
1040 let refusing = matches!(outcome, Outcome::Refused | Outcome::Failed);
1041 let refusal = self.code.is_some() || self.pointer.is_some() || self.detail.is_some();
1042 if (refusal && !refusing) || (refusing && self.code.is_none()) {
1043 out.push(Finding::Refusal);
1044 }
1045 if (source == Source::Desired && observed.is_none())
1046 || (outcome == Outcome::Converged && source == Source::Baseline)
1047 || (outcome == Outcome::Reverted && source == Source::Desired)
1048 {
1049 out.push(Finding::Source);
1050 }
1051 let names = self.in_force != InForce::None;
1052 let misplaced = names && (source != Source::Desired || outcome == Outcome::Failed);
1053 let not_observed = outcome == Outcome::Converged
1054 && source == Source::Desired
1055 && self.in_force != InForce::Observed;
1056 let no_observed = self.in_force == InForce::Observed && observed.is_none();
1057 let no_other = self.in_force == InForce::Other && (other.is_none() || other == observed);
1058 let stray = self.in_force != InForce::Other && any_other;
1059 if misplaced || not_observed || no_observed || no_other || stray {
1060 out.push(Finding::InForce);
1061 }
1062 if outcome == Outcome::Reverted && self.revision.is_some() {
1063 out.push(Finding::RevisionOnRevert);
1064 }
1065 if self.last_known && observed.is_none() {
1066 out.push(Finding::LastKnown);
1067 }
1068 out
1069 }
1070
1071 #[must_use]
1073 pub fn report(&self) -> Option<Report> {
1074 if !self.check().is_empty() {
1075 return None;
1076 }
1077 let observed = self.observed().map(|version| Observed {
1078 version,
1079 revision: self.revision.map(u64::from),
1080 });
1081 let in_force = match self.in_force {
1082 InForce::None => None,
1083 InForce::Observed => observed,
1084 InForce::Other => self.other_in_force().map(|version| Observed {
1085 version,
1086 revision: self.in_force_revision.map(u64::from),
1087 }),
1088 };
1089 Some(Report {
1090 source: self.source?,
1091 outcome: self.outcome?,
1092 last_known: self.last_known,
1093 observed,
1094 in_force,
1095 refusal: self.code.map(|code| Refusal {
1096 code,
1097 pointer: self.pointer,
1098 detail: self.detail,
1099 }),
1100 })
1101 }
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1107pub struct Report {
1108 pub source: Source,
1110 pub outcome: Outcome,
1112 pub last_known: bool,
1114 pub observed: Option<Observed>,
1117 pub in_force: Option<Observed>,
1121 pub refusal: Option<Refusal>,
1122}
1123
1124fn revision_field(r: Option<u64>) -> Result<Option<u32>, WriteRefusal> {
1125 r.map(|r| u32::try_from(r).map_err(|_| WriteRefusal::Range))
1126 .transpose()
1127}
1128
1129fn observed_json(o: &Observed) -> Value {
1130 let mut m = Map::new();
1131 m.insert("version".into(), json!(version_text(o.version)));
1132 if let Some(r) = o.revision {
1133 m.insert("revision".into(), json!(r));
1134 }
1135 Value::Object(m)
1136}
1137
1138fn observed_of(v: &Value) -> Result<Observed, WriteRefusal> {
1139 let version = v
1140 .get("version")
1141 .and_then(Value::as_str)
1142 .and_then(parse_version)
1143 .ok_or(WriteRefusal::Value)?;
1144 let revision = match v.get("revision") {
1145 None => None,
1146 Some(r) => Some(r.as_u64().ok_or(WriteRefusal::Value)?),
1147 };
1148 Ok(Observed { version, revision })
1149}
1150
1151impl Report {
1152 #[must_use]
1156 pub fn baseline() -> Self {
1157 Self {
1158 source: Source::Baseline,
1159 outcome: Outcome::NotActed,
1160 last_known: false,
1161 observed: None,
1162 in_force: None,
1163 refusal: None,
1164 }
1165 }
1166
1167 pub fn fields(&self) -> Result<Fields, WriteRefusal> {
1173 let mut f = Fields {
1174 source: Some(self.source),
1175 outcome: Some(self.outcome),
1176 last_known: self.last_known,
1177 ..Fields::default()
1178 };
1179 if let Some(o) = &self.observed {
1180 match o.version.run {
1181 Run::U16(r) => f.observed_run16 = Some(r),
1182 Run::U32(r) => f.observed_run32 = Some(r),
1183 }
1184 f.observed_seq = Some(o.version.seq.get());
1185 f.revision = revision_field(o.revision)?;
1186 }
1187 f.in_force = match (&self.in_force, &self.observed) {
1188 (None, _) => InForce::None,
1189 (Some(i), Some(o)) if i.version == o.version => {
1190 revision_field(i.revision)?;
1193 InForce::Observed
1194 }
1195 (Some(i), _) => {
1196 match i.version.run {
1197 Run::U16(r) => f.in_force_run16 = Some(r),
1198 Run::U32(r) => f.in_force_run32 = Some(r),
1199 }
1200 f.in_force_seq = Some(i.version.seq.get());
1201 f.in_force_revision = revision_field(i.revision)?;
1202 InForce::Other
1203 }
1204 };
1205 if let Some(r) = &self.refusal {
1206 f.code = Some(r.code);
1207 f.pointer = r.pointer;
1208 f.detail = r.detail;
1209 }
1210 Ok(f)
1211 }
1212
1213 pub fn write(&self) -> Result<Record, WriteRefusal> {
1219 self.fields()?.record()
1220 }
1221
1222 pub fn put(&self, stamp: Stamp) -> Result<Vec<u8>, WriteRefusal> {
1229 let record = self.write()?;
1230 let tag = Tag::new(TAG).expect("12 is a tag");
1231 Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
1232 }
1233
1234 #[must_use]
1237 pub fn check(&self) -> Vec<Finding> {
1238 self.fields().map(|f| f.check()).unwrap_or_default()
1239 }
1240
1241 #[must_use]
1246 pub fn reading(&self) -> Value {
1247 let mut m = Map::new();
1248 m.insert("source".into(), json!(self.source.as_str()));
1249 m.insert("outcome".into(), json!(self.outcome.as_str()));
1250 m.insert("last_known".into(), json!(self.last_known));
1251 if let Some(o) = &self.observed {
1252 m.insert("observed".into(), observed_json(o));
1253 }
1254 if let Some(i) = &self.in_force {
1255 m.insert("in_force".into(), observed_json(i));
1256 }
1257 if let Some(r) = &self.refusal {
1258 let mut x = Map::new();
1259 x.insert("code".into(), r.code.to_json());
1260 if let Some(p) = r.pointer {
1261 x.insert("pointer".into(), p.to_json());
1262 }
1263 if let Some(d) = r.detail {
1264 x.insert("detail".into(), d.to_json());
1265 }
1266 m.insert("refusal".into(), Value::Object(x));
1267 }
1268 Value::Object(m)
1269 }
1270
1271 pub fn from_reading(v: &Value) -> Result<Report, WriteRefusal> {
1278 let name = |k: &str| v.get(k).and_then(Value::as_str).ok_or(WriteRefusal::Value);
1279 let source = name("source")?;
1280 let source = [Source::Baseline, Source::Desired, Source::Call]
1281 .into_iter()
1282 .find(|s| s.as_str() == source)
1283 .ok_or(WriteRefusal::Value)?;
1284 let outcome = Outcome::parse(name("outcome")?).ok_or(WriteRefusal::Value)?;
1285 let last_known = v
1286 .get("last_known")
1287 .and_then(Value::as_bool)
1288 .ok_or(WriteRefusal::Value)?;
1289 let refusal = match v.get("refusal") {
1290 None => None,
1291 Some(r) => Some(Refusal {
1292 code: Code::of_json(r.get("code").ok_or(WriteRefusal::Value)?)?,
1293 pointer: r.get("pointer").map(Index::of_json).transpose()?,
1294 detail: r.get("detail").map(Index::of_json).transpose()?,
1295 }),
1296 };
1297 Ok(Report {
1298 source,
1299 outcome,
1300 last_known,
1301 observed: v.get("observed").map(observed_of).transpose()?,
1302 in_force: v.get("in_force").map(observed_of).transpose()?,
1303 refusal,
1304 })
1305 }
1306}
1307
1308#[derive(Debug, Clone, PartialEq, Eq)]
1311pub struct Read {
1312 pub fields: Fields,
1313 pub findings: Vec<Finding>,
1316 pub report: Option<Report>,
1318}
1319
1320pub fn read(tag: u8, bytes: &[u8]) -> Result<Read, ReadRefusal> {
1328 let value = layout().read(tag, bytes, None)?;
1329 let fields = Fields::of_json(&value).map_err(|_| ReadRefusal::Code)?;
1331 Ok(Read {
1332 fields,
1333 findings: fields.check(),
1334 report: fields.report(),
1335 })
1336}
1337
1338impl Reported for Read {
1339 fn facts(&self) -> Option<super::Facts> {
1340 let r = self.report.as_ref()?;
1341 Some(super::Facts {
1342 source: r.source,
1343 outcome: r.outcome.acted(),
1344 last_known: r.last_known,
1345 in_force: r.in_force.is_some(),
1346 })
1347 }
1348}
1349
1350#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1355pub enum Cause {
1356 Version(Version),
1357 NoEntry {
1360 run: Run,
1361 asof: Seq,
1362 },
1363}
1364
1365impl machine::Mark for Cause {
1366 type Epoch = Run;
1367 type Tick = Seq;
1368 fn epoch(&self) -> Run {
1369 match self {
1370 Cause::Version(v) => v.run,
1371 Cause::NoEntry { run, .. } => *run,
1372 }
1373 }
1374 fn tick(&self) -> Seq {
1375 match self {
1376 Cause::Version(v) => v.seq,
1377 Cause::NoEntry { asof, .. } => *asof,
1378 }
1379 }
1380 fn floor(&self) -> bool {
1381 matches!(self, Cause::NoEntry { .. })
1382 }
1383}
1384
1385impl machine::Mark for Stamp {
1386 type Epoch = Run;
1387 type Tick = Seq;
1388 fn epoch(&self) -> Run {
1389 self.run
1390 }
1391 fn tick(&self) -> Seq {
1392 self.seq
1393 }
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1399pub struct Sample {
1400 pub via: Via,
1401 pub mutation: Mutation,
1402 pub version: Option<Version>,
1405 pub revision: Option<u64>,
1409 pub content: Option<Content>,
1412}
1413
1414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1417pub struct Act {
1418 pub kind: ActKind,
1419 pub cause: Cause,
1420 pub revision: Option<u64>,
1421 pub via: Via,
1422 pub content: Option<Content>,
1423}
1424
1425impl Act {
1426 #[must_use]
1428 pub fn version(&self) -> Option<Version> {
1429 match self.cause {
1430 Cause::Version(v) => Some(v),
1431 Cause::NoEntry { .. } => None,
1432 }
1433 }
1434
1435 #[must_use]
1439 pub fn bound(&self) -> Option<Refusal> {
1440 (self.kind == ActKind::Apply && self.revision.is_some_and(|r| r > MAX_REVISION))
1441 .then(|| Refusal::new(Code::Invalid))
1442 }
1443}
1444
1445impl From<machine::Doing<Cause>> for Act {
1446 fn from(d: machine::Doing<Cause>) -> Self {
1447 Self {
1448 kind: d.kind,
1449 cause: d.mark,
1450 revision: d.revision,
1451 via: d.via,
1452 content: d.content,
1453 }
1454 }
1455}
1456
1457pub type Ended = super::Ended<Refusal>;
1459
1460#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1462pub enum Step {
1463 Act(Act),
1465 Adopted,
1468 Held,
1470 Unstamped,
1472 SameVersion,
1475 Older,
1479 Confirmed,
1483 Done,
1485 NoVerdict,
1488}
1489
1490impl Step {
1491 #[must_use]
1493 pub fn as_str(&self) -> &'static str {
1494 match self {
1495 Self::Act(Act {
1496 kind: ActKind::Apply,
1497 ..
1498 }) => "act",
1499 Self::Act(Act {
1500 kind: ActKind::Revert,
1501 ..
1502 }) => "revert",
1503 Self::Adopted => "adopted",
1504 Self::Held => "held",
1505 Self::Unstamped => "unstamped",
1506 Self::SameVersion => "same_version",
1507 Self::Older => "older",
1508 Self::Confirmed => "confirmed",
1509 Self::Done => "done",
1510 Self::NoVerdict => "no_verdict",
1511 }
1512 }
1513}
1514
1515#[derive(Debug, Clone)]
1522pub struct Target {
1523 core: machine::Core<Cause, Refusal>,
1524}
1525
1526impl Default for Target {
1527 fn default() -> Self {
1528 Self::new()
1529 }
1530}
1531
1532impl Target {
1533 #[must_use]
1536 pub fn new() -> Self {
1537 Self {
1538 core: machine::Core::new(),
1539 }
1540 }
1541
1542 #[must_use]
1546 pub fn report(&self) -> Report {
1547 let seen = |(cause, revision): (Cause, Option<u64>)| match cause {
1548 Cause::Version(version) => Some(Observed {
1549 version,
1550 revision: revision.filter(|r| *r <= MAX_REVISION),
1551 }),
1552 Cause::NoEntry { .. } => None,
1553 };
1554 let l = self.core.ledger();
1555 Report {
1556 source: l.source,
1557 outcome: l.outcome.into(),
1558 last_known: l.last_known,
1559 observed: l.observed.and_then(seen),
1560 in_force: l.in_force.and_then(seen),
1561 refusal: l.refusal,
1562 }
1563 }
1564
1565 #[must_use]
1567 pub fn running(&self) -> Option<Act> {
1568 self.core.running().map(|d| Act::from(*d))
1569 }
1570
1571 #[must_use]
1575 pub fn remembered(&self, run: Run) -> Option<Seq> {
1576 self.core.remembered(run)
1577 }
1578
1579 #[must_use]
1585 pub fn held(&self) -> Option<Version> {
1586 self.holds().map(|(_, v)| v)
1587 }
1588
1589 #[must_use]
1592 pub fn holds(&self) -> Option<(Mutation, Version)> {
1593 let d = self.core.latest()?;
1594 match d.mark {
1595 Cause::Version(v) => Some((
1596 match d.kind {
1597 ActKind::Apply => Mutation::Put,
1598 ActKind::Revert => Mutation::Delete,
1599 },
1600 v,
1601 )),
1602 Cause::NoEntry { .. } => None,
1603 }
1604 }
1605
1606 pub fn observe(&mut self, s: Sample) -> Step {
1612 let Some(version) = s.version else {
1613 return Step::Unstamped;
1614 };
1615 let put = s.mutation == Mutation::Put;
1616 match self.core.observe(machine::Doing {
1617 kind: if put { ActKind::Apply } else { ActKind::Revert },
1618 mark: Cause::Version(version),
1619 revision: s.revision.filter(|_| put),
1620 via: s.via,
1621 content: s.content.filter(|_| put),
1622 }) {
1623 machine::Judged::Act(d) => Step::Act(d.into()),
1624 machine::Judged::Adopted => Step::Adopted,
1625 machine::Judged::Held => Step::Held,
1626 machine::Judged::SameVersion => Step::SameVersion,
1627 machine::Judged::Older => Step::Older,
1628 machine::Judged::Confirmed => Step::Confirmed,
1629 }
1630 }
1631
1632 pub fn observe_no_entry(&mut self, run: Run, asof: Seq) -> Step {
1640 match self.core.observe_floor(Cause::NoEntry { run, asof }) {
1641 machine::Floored::NoVerdict => Step::NoVerdict,
1642 machine::Floored::Older => Step::Older,
1643 machine::Floored::Held => Step::Held,
1644 machine::Floored::Act(d) => Step::Act(d.into()),
1645 }
1646 }
1647
1648 pub fn unchanged(&mut self, sent: Version) -> Step {
1654 if self.core.unchanged(Cause::Version(sent)) {
1655 Step::Confirmed
1656 } else {
1657 Step::SameVersion
1658 }
1659 }
1660
1661 pub fn finish(&mut self, ended: Ended) -> Step {
1665 match self.core.finish(ended) {
1666 machine::Finished::Done => Step::Done,
1667 machine::Finished::Adopted => Step::Adopted,
1668 machine::Finished::Act(d) => Step::Act(d.into()),
1669 }
1670 }
1671
1672 pub fn call(&mut self) {
1675 self.core.call();
1676 }
1677}
1678
1679#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1684pub struct Section {
1685 pub digest: Digest,
1686 pub live: u64,
1687}
1688
1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1694pub enum Beat {
1695 Revision,
1697 Refused,
1700 Read {
1704 stamp: Stamp,
1705 section: Option<Section>,
1706 },
1707}
1708
1709#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1712pub enum Decision {
1713 Revision,
1715 Refused,
1717 Older,
1719 NoSection,
1721 Unmoved,
1723 Outstanding,
1726 Read { held: Option<Version> },
1729}
1730
1731impl Decision {
1732 #[must_use]
1734 pub fn as_str(&self) -> &'static str {
1735 match self {
1736 Self::Revision => "revision",
1737 Self::Refused => "refused",
1738 Self::Older => "older",
1739 Self::NoSection => "no_section",
1740 Self::Unmoved => "unmoved",
1741 Self::Outstanding => "outstanding",
1742 Self::Read { .. } => "read",
1743 }
1744 }
1745}
1746
1747#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1749pub enum Answered {
1750 Unchanged,
1753 Whole,
1756 NoAnswer,
1759}
1760
1761impl Answered {
1762 #[must_use]
1764 pub fn as_str(self) -> &'static str {
1765 match self {
1766 Self::Unchanged => "unchanged",
1767 Self::Whole => "whole",
1768 Self::NoAnswer => "no_answer",
1769 }
1770 }
1771}
1772
1773#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1776pub enum Heard {
1777 Moved,
1779 Kept,
1782}
1783
1784impl Heard {
1785 #[must_use]
1787 pub fn as_str(self) -> &'static str {
1788 match self {
1789 Self::Moved => "moved",
1790 Self::Kept => "kept",
1791 }
1792 }
1793}
1794
1795#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1798struct Outstanding {
1799 section: Section,
1800 sent: Option<Version>,
1801}
1802
1803#[derive(Debug, Clone, PartialEq, Eq)]
1811pub struct Watch {
1812 key: String,
1813 moves: bool,
1814 sequence: crate::freshness::Sequence,
1815 expects: Option<Section>,
1816 outstanding: Option<Outstanding>,
1817}
1818
1819impl Watch {
1820 #[must_use]
1826 pub fn new(key: impl Into<String>, moves: bool) -> Self {
1827 Self {
1828 key: key.into(),
1829 moves,
1830 sequence: crate::freshness::Sequence::default(),
1831 expects: None,
1832 outstanding: None,
1833 }
1834 }
1835
1836 #[must_use]
1838 pub fn expects(&self) -> Option<Section> {
1839 self.expects
1840 }
1841
1842 #[must_use]
1844 pub fn outstanding(&self) -> bool {
1845 self.outstanding.is_some()
1846 }
1847
1848 pub fn heartbeat(&mut self, beat: Beat, holds: Option<Version>) -> Decision {
1852 let (stamp, section) = match beat {
1853 Beat::Revision => {
1854 self.expects = None;
1855 return Decision::Revision;
1856 }
1857 Beat::Refused => {
1858 self.expects = None;
1859 return Decision::Refused;
1860 }
1861 Beat::Read { stamp, section } => (stamp, section),
1862 };
1863 let Some(read) = self.sequence.read(stamp) else {
1864 return Decision::Older;
1865 };
1866 if read.gap || read.run {
1868 self.expects = None;
1869 }
1870 let Some(section) = section else {
1871 self.expects = None;
1872 return Decision::NoSection;
1873 };
1874 if self.expects == Some(section) {
1875 return Decision::Unmoved;
1876 }
1877 if self.outstanding.is_some() {
1878 return Decision::Outstanding;
1879 }
1880 self.outstanding = Some(Outstanding {
1881 section,
1882 sent: holds,
1883 });
1884 Decision::Read { held: holds }
1885 }
1886
1887 pub fn answer(&mut self, answer: Answered, holds: Option<Version>) -> Answered {
1894 let Some(out) = self.outstanding.take() else {
1895 return Answered::NoAnswer;
1896 };
1897 match answer {
1898 Answered::Unchanged => {
1899 self.expects = (out.sent.is_some() && out.sent == holds).then_some(out.section);
1900 }
1901 Answered::Whole => self.expects = None,
1902 Answered::NoAnswer => {}
1903 }
1904 answer
1905 }
1906
1907 pub fn heard(&mut self, old: Option<(Mutation, Version)>, new: (Mutation, Version)) -> Heard {
1915 let (Some(section), Some(old), true) = (self.expects.as_mut(), old, self.moves) else {
1916 return Heard::Kept;
1917 };
1918 if old.0 == Mutation::Put {
1919 section.digest.toggle(&self.key, old.1);
1920 section.live = section.live.saturating_sub(1);
1921 }
1922 if new.0 == Mutation::Put {
1923 section.digest.toggle(&self.key, new.1);
1924 section.live = section.live.saturating_add(1);
1925 }
1926 Heard::Moved
1927 }
1928}
1929
1930#[derive(Debug, Clone, PartialEq, Eq)]
1936pub enum ReportAt {
1937 None,
1939 Two,
1942 Invalid(Vec<ReportInvalid>),
1945 At { key: Key, tables: Tables },
1948}
1949
1950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1952pub enum Unreadable {
1953 TwoReports,
1955 Record(ReadRefusal),
1957}
1958
1959impl Unreadable {
1960 #[must_use]
1962 pub fn as_str(self) -> &'static str {
1963 match self {
1964 Self::TwoReports => "two_reports",
1965 Self::Record(r) => r.token(),
1966 }
1967 }
1968}
1969
1970#[derive(Debug, Clone, PartialEq, Eq)]
1972pub enum Found {
1973 None(Vec<ReportInvalid>),
1975 Unreadable(Unreadable),
1977 One(Read),
1979}
1980
1981impl Found {
1982 #[must_use]
1984 pub fn as_str(&self) -> &'static str {
1985 match self {
1986 Self::None(_) => "none",
1987 Self::Unreadable(_) => "unreadable",
1988 Self::One(_) => "one",
1989 }
1990 }
1991}
1992
1993impl ReportAt {
1994 #[must_use]
1997 pub fn key(&self) -> Option<&Key> {
1998 match self {
1999 Self::At { key, .. } => Some(key),
2000 _ => None,
2001 }
2002 }
2003
2004 #[must_use]
2008 pub fn found(&self, reply: Option<(u8, &[u8])>) -> Found {
2009 match self {
2010 Self::None => Found::None(Vec::new()),
2011 Self::Two => Found::Unreadable(Unreadable::TwoReports),
2012 Self::Invalid(why) => Found::None(why.clone()),
2013 Self::At { .. } => match reply {
2014 None => Found::None(Vec::new()),
2015 Some((tag, bytes)) => match read(tag, bytes) {
2016 Ok(r) => Found::One(r),
2017 Err(e) => Found::Unreadable(Unreadable::Record(e)),
2018 },
2019 },
2020 }
2021 }
2022}
2023
2024#[must_use]
2030pub fn report_at(
2031 target: &Addr,
2032 iface: &IfaceId,
2033 role: &str,
2034 resources: &[ReportResource<'_>],
2035 is_role: impl Fn(&str) -> bool,
2036) -> ReportAt {
2037 let naming: Vec<usize> = resources
2038 .iter()
2039 .enumerate()
2040 .filter(|(_, r)| {
2041 r.annotations
2042 .get(REPORT_KEY)
2043 .and_then(Names::read)
2044 .is_some_and(|n| n.names(role))
2045 })
2046 .map(|(i, _)| i)
2047 .collect();
2048 let at = match naming.as_slice() {
2049 [] => return ReportAt::None,
2050 [one] => *one,
2051 _ => return ReportAt::Two,
2052 };
2053 let r = &resources[at];
2054 let others = resources
2055 .iter()
2056 .enumerate()
2057 .filter(|(i, _)| *i != at)
2058 .filter_map(|(_, o)| o.annotations.get(REPORT_KEY));
2059 let (names, tables) = match report_declaration(r, is_role, others) {
2060 ReportDeclaration::Declared { names, tables } => (names, tables),
2061 ReportDeclaration::Invalid(why) => return ReportAt::Invalid(why),
2062 ReportDeclaration::NotThisProfiles => return ReportAt::None,
2063 };
2064 let mut values = Bindings::new();
2065 if let Names::Param(p) = names {
2066 values.insert(p, vec![role.to_owned()]);
2067 }
2068 let key = r.template.build(&values).ok().and_then(|chunks| {
2069 let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
2070 grammar::data_key(target, iface, r.token, &refs).ok()
2071 });
2072 match key {
2073 Some(key) => ReportAt::At { key, tables },
2074 None => ReportAt::None,
2076 }
2077}
2078
2079#[must_use]
2082pub fn report_at_of(target: &Addr, c: &Contract, role: &str) -> ReportAt {
2083 let resources: Vec<ReportResource<'_>> = c.resources.iter().map(ReportResource::of).collect();
2084 report_at(target, &c.iface, role, &resources, |name| {
2085 c.requires.contains_key(name)
2086 })
2087}
2088
2089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2094pub enum Current {
2095 NotRead,
2098 Incomplete,
2100 Unstamped,
2102 Silent,
2104 Entry(Version),
2106 Tombstone(Version),
2108 NoEntry(Run),
2110}
2111
2112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2114pub struct AuthorReading {
2115 pub presence: Seen,
2116 pub current: Current,
2117}
2118
2119#[must_use]
2127pub fn converged(t: &TargetReading<'_, Read>, a: &AuthorReading) -> Judged {
2128 use Answer::{NotYet, Unobservable, Yes};
2129 let judged = |answer, reason| Judged { answer, reason };
2130 let report = match super::converging(t, a.presence) {
2131 Ok((
2132 Read {
2133 report: Some(r), ..
2134 },
2135 _,
2136 )) => *r,
2137 Ok(_) => return judged(Unobservable, Reason::ReportInvalid),
2138 Err(j) => return j,
2139 };
2140 let observed = report.observed.map(|o| o.version);
2141 let current = match a.current {
2142 Current::NotRead => return judged(Unobservable, Reason::AuthorNotRead),
2143 Current::Incomplete | Current::Unstamped => {
2144 return judged(Unobservable, Reason::AuthorReadIncomplete);
2145 }
2146 Current::Silent => return judged(Unobservable, Reason::AuthorSilent),
2147 Current::NoEntry(run) => {
2148 return match observed {
2149 Some(o) if o.run == run && report.outcome == Outcome::Reverted => {
2150 judged(Yes, Reason::Reverted)
2151 }
2152 Some(o) if o.run == run => judged(NotYet, Reason::Behind),
2153 _ => judged(Unobservable, Reason::AuthorSilent),
2154 };
2155 }
2156 Current::Entry(v) | Current::Tombstone(v) => v,
2157 };
2158 match (observed, report.outcome.acted()) {
2159 (Some(o), Some(outcome)) => super::compared(&o, ¤t, outcome),
2160 _ => judged(NotYet, Reason::NotActed),
2161 }
2162}
2163
2164#[cfg(test)]
2165mod tests {
2166 use super::*;
2167
2168 fn v(text: &str) -> Version {
2169 parse_version(text).expect("a version")
2170 }
2171
2172 fn put(text: &str, revision: u64) -> Sample {
2173 Sample {
2174 via: Via::Owner,
2175 mutation: Mutation::Put,
2176 version: Some(v(text)),
2177 revision: Some(revision),
2178 content: Some(Content::of_json(&json!({"revision": revision}))),
2179 }
2180 }
2181
2182 #[test]
2183 fn a_version_is_written_as_its_run_and_its_seq() {
2184 assert_eq!(version_text(v("0007/12")), "0007/12");
2185 assert_eq!(version_text(v("00000007/12")), "00000007/12");
2186 assert_ne!(v("0007/12"), v("00000007/12"), "two widths are two runs");
2187 assert_eq!(v("ffff/16777215").seq, Seq::MAX);
2188 for bad in [
2189 "",
2190 "7/12",
2191 "007/12",
2192 "00007/12",
2193 "0007/",
2194 "/12",
2195 "0007/012",
2196 "0007/+1",
2197 "0007/1 ",
2198 "000G/1",
2199 "000A/1",
2200 "0007/16777216",
2201 "0007/1/2",
2202 "0007",
2203 "0007/-1",
2204 "0007/000000001",
2205 ] {
2206 assert_eq!(parse_version(bad), None, "{bad:?}");
2207 }
2208 assert_eq!(parse_version("0007/0"), Some(v("0007/0")));
2209 }
2210
2211 #[test]
2212 fn the_layout_is_the_texts() {
2213 let l = layout();
2214 assert_eq!(l.tag(), TAG);
2215 assert_eq!(l.min_bits(), 20);
2216 assert_eq!(Report::baseline().write().unwrap().bytes, [0, 0, 0]);
2217 let longest = Report {
2220 source: Source::Desired,
2221 outcome: Outcome::Refused,
2222 last_known: true,
2223 observed: Some(Observed {
2224 version: v("00a1b2c3/9"),
2225 revision: Some(4),
2226 }),
2227 in_force: Some(Observed {
2228 version: v("00a1b2c3/4"),
2229 revision: Some(3),
2230 }),
2231 refusal: Some(Refusal {
2232 code: Code::Reach,
2233 pointer: Some(Index::At(3)),
2234 detail: Some(Index::OutOfRange),
2235 }),
2236 };
2237 let record = longest.write().unwrap();
2238 assert_eq!((record.bits, record.bytes.len()), (215, 27));
2239 assert_eq!(
2240 read(TAG, &record.bytes).unwrap().report,
2241 Some(longest),
2242 "every report reads back"
2243 );
2244 }
2245
2246 #[test]
2247 fn every_report_the_machine_makes_is_consistent() {
2248 let mut t = Target::new();
2249 let mut seen = vec![t.report()];
2250 let mut note = |t: &Target| seen.push(t.report());
2251 assert!(matches!(t.observe(put("0007/3", 1)), Step::Act(_)));
2252 assert_eq!(t.observe(put("0007/4", 2)), Step::Held);
2253 assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
2254 note(&t);
2255 t.finish(Ended::Refused(Refusal::new(Code::Reach)));
2256 note(&t);
2257 t.call();
2258 note(&t);
2259 let big = put("0007/5", MAX_REVISION + 1);
2261 let Step::Act(act) = t.observe(big) else {
2262 panic!("a new document is acted on");
2263 };
2264 let refusal = act.bound().expect("above the bound");
2265 t.finish(Ended::Refused(refusal));
2266 assert_eq!(t.report().observed.unwrap().revision, None);
2267 note(&t);
2268 let run = v("0007/0").run;
2271 let asof = Seq::new(20).unwrap();
2272 assert!(matches!(t.observe_no_entry(run, asof), Step::Act(_)));
2273 t.finish(Ended::Failed(Refusal::new(Code::Apply)));
2274 assert_eq!(t.report().outcome, Outcome::Failed);
2275 assert_eq!(t.report().observed.map(|o| o.version), Some(v("0007/5")));
2276 note(&t);
2277 assert_eq!(t.observe(put("0007/20", 3)), Step::Older, "at the asof");
2278 assert!(matches!(t.observe(put("0007/21", 3)), Step::Act(_)));
2279 t.finish(Ended::Done);
2280 note(&t);
2281 assert!(matches!(
2282 t.observe_no_entry(run, Seq::new(30).unwrap()),
2283 Step::Act(_)
2284 ));
2285 t.finish(Ended::Done);
2286 assert_eq!(t.report().observed, None);
2287 assert_eq!(t.held(), None, "after it the target holds no document");
2288 note(&t);
2289 for r in &seen {
2290 assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
2291 let record = r.write().expect("a record");
2292 assert_eq!(read(TAG, &record.bytes).unwrap().report.as_ref(), Some(r));
2293 }
2294 }
2295
2296 #[test]
2297 fn an_asof_at_the_held_seq_makes_that_version_older() {
2298 let mut t = Target::new();
2299 assert!(matches!(t.observe(put("0007/20", 1)), Step::Act(_)));
2300 t.finish(Ended::Done);
2301 assert_eq!(t.observe(put("0007/20", 1)), Step::SameVersion);
2302 let run = v("0007/0").run;
2303 assert!(matches!(
2304 t.observe_no_entry(run, Seq::new(20).unwrap()),
2305 Step::Act(_)
2306 ));
2307 t.finish(Ended::Done);
2308 assert_eq!(t.observe(put("0007/20", 1)), Step::Older);
2310 assert_eq!(t.remembered(run), Seq::new(20));
2311 }
2312
2313 #[test]
2314 fn an_unchanged_answer_confirms_only_the_version_held() {
2315 let archived = Sample {
2316 via: Via::Archive,
2317 ..put("0007/3", 1)
2318 };
2319 let mut t = Target::new();
2320 assert!(matches!(t.observe(archived), Step::Act(_)));
2321 t.finish(Ended::Done);
2322 assert!(t.report().last_known);
2323 assert_eq!(t.unchanged(v("0007/2")), Step::SameVersion);
2324 assert!(t.report().last_known, "another version's word");
2325 assert_eq!(t.unchanged(v("0007/3")), Step::Confirmed);
2326 assert!(!t.report().last_known);
2327 assert_eq!(t.unchanged(v("0007/3")), Step::SameVersion);
2328 assert_eq!(t.unchanged(v("0099/1")), Step::SameVersion);
2330 assert_eq!(t.held(), Some(v("0007/3")));
2331 }
2332
2333 #[test]
2334 fn a_place_is_its_nearest_listed_ancestor() {
2335 let t = Tables {
2336 pointers: ["", "/a", "/a/b", "/a~1b"].map(str::to_owned).to_vec(),
2337 details: vec!["x".into()],
2338 };
2339 assert_eq!(t.place(""), Index::At(0));
2340 assert_eq!(t.place("/a/b/c/d"), Index::At(2));
2341 assert_eq!(t.place("/a/c"), Index::At(1));
2342 assert_eq!(t.place("/ab"), Index::OutOfRange);
2343 assert_eq!(t.place("/z"), Index::OutOfRange, "never index 0");
2344 assert_eq!(t.line("x"), Index::At(0));
2345 assert_eq!(t.line("y"), Index::OutOfRange);
2346 assert_eq!(t.pointer(Index::At(3)), Word::Entry("/a~1b"));
2347 assert_eq!(t.pointer(Index::At(9)), Word::Number(9));
2348 assert_eq!(word(None, Index::At(1)), Word::Number(1));
2349 assert_eq!(t.detail(Index::OutOfRange), Word::OutOfRange);
2350 }
2351
2352 #[test]
2353 fn a_watch_makes_no_read_while_one_is_outstanding() {
2354 let key = "zk2/lab/author/tasking.v2/state/tasks/lab/worker";
2355 let held = v("0007/3");
2356 let section = |seq: u32| Section {
2357 digest: Digest::of([(key, v(&format!("0007/{seq}")))]),
2358 live: 1,
2359 };
2360 let beat = |seq: u32, s: Section| Beat::Read {
2361 stamp: v(&format!("0021/{seq}")),
2362 section: Some(s),
2363 };
2364 let mut w = Watch::new(key, true);
2365 assert_eq!(
2366 w.heartbeat(beat(0, section(3)), Some(held)),
2367 Decision::Read { held: Some(held) }
2368 );
2369 assert!(w.outstanding());
2370 assert_eq!(
2371 w.heartbeat(beat(1, section(3)), Some(held)),
2372 Decision::Outstanding
2373 );
2374 assert_eq!(
2375 w.answer(Answered::Unchanged, Some(held)),
2376 Answered::Unchanged
2377 );
2378 assert_eq!(w.expects(), Some(section(3)));
2379 assert_eq!(w.answer(Answered::Whole, Some(held)), Answered::NoAnswer);
2381 assert_eq!(w.expects(), Some(section(3)));
2382 let new = v("0007/9");
2384 assert_eq!(
2385 w.heard(Some((Mutation::Put, held)), (Mutation::Put, new)),
2386 Heard::Moved
2387 );
2388 assert_eq!(
2389 w.heartbeat(beat(2, section(9)), Some(new)),
2390 Decision::Unmoved
2391 );
2392 assert_eq!(w.heard(None, (Mutation::Put, new)), Heard::Kept);
2394 }
2395}