use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde_json::{Map, Value, json};
use super::{
ActKind, Answer, Content, Finding, Invalid, Judged, Mutation, Reason, Reported, Seen, Source,
TargetReading, Via, machine,
};
use crate::authoring::{Kind, ParamType};
use crate::contract::{Body, Contract, Resource};
use crate::grammar::{self, Addr, IfaceId, Key, KindToken};
use crate::heartbeat::Digest;
use crate::packed::{self, Layout, ReadRefusal, Record, WriteRefusal};
use crate::schema::TypeId;
use crate::template::{Bindings, Template};
use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
use crate::words;
pub const PROFILE: &str = "desired.v2";
pub const REPORT_KEY: &str = "desired.report";
pub const POINTERS: &str = "desired.pointers";
pub const DETAILS: &str = "desired.details";
pub const VOCABULARY: &[&str] = &["target_param", "report", "pointers", "details"];
pub const SCHEMA_STEM: &str = "desired.v2";
pub const REPORT: &str = "Report";
pub const PUBLISHED: &[&str] =
&["sha256:1ac893a1cb14a102cc1b01ea526a317b19390a8ed6c40707f08754f4429532dd"];
pub const TAG: u8 = 12;
pub const MAX_REVISION: u64 = 4_294_967_295;
pub const REMEMBERED_RUNS: usize = super::REMEMBERED_IDS;
pub use crate::words::OUT_OF_RANGE;
pub const MAX_INDEX: u8 = 254;
#[must_use]
pub fn is_published(id: &str) -> bool {
PUBLISHED.contains(&id)
}
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
words::uses(c, PROFILE)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Major {
V1,
V2,
}
impl Major {
#[must_use]
pub fn of(c: &Contract) -> Option<Major> {
if uses_v2(c) {
Some(Major::V2)
} else if c.uses.iter().any(|u| u.to_string() == super::PROFILE) {
Some(Major::V1)
} else {
None
}
}
}
pub type Version = Stamp;
#[must_use]
pub fn version_text(v: Version) -> String {
format!("{}/{}", v.run, v.seq.get())
}
#[must_use]
pub fn parse_version(s: &str) -> Option<Version> {
let (run, seq) = s.split_once('/')?;
let digits = !seq.is_empty() && seq.len() <= 8 && seq.bytes().all(|b| b.is_ascii_digit());
if !digits || (seq.len() > 1 && seq.starts_with('0')) {
return None;
}
Some(Stamp {
run: Run::from_hex(run)?,
seq: Seq::new(seq.parse().ok()?)?,
})
}
#[must_use]
pub fn declaration(
kind: Kind,
template: &Template,
params: &BTreeMap<String, ParamType>,
annotations: &BTreeMap<String, Value>,
uses: impl Fn(&str) -> bool,
) -> super::Declaration {
let v1 = super::declaration(kind, template, params, annotations);
let horizon_v1 = kind == Kind::State
&& crate::freshness::horizon(kind, annotations).ttl().is_some()
&& !uses(crate::freshness::PROFILE_V2);
match v1 {
super::Declaration::NotThisProfiles => v1,
super::Declaration::Declared(_) if !horizon_v1 => v1,
super::Declaration::Declared(_) => super::Declaration::Invalid(vec![Invalid::HorizonV1]),
super::Declaration::Invalid(mut why) => {
if horizon_v1 {
why.push(Invalid::HorizonV1);
}
super::Declaration::Invalid(why)
}
}
}
#[must_use]
pub fn declaration_of(c: &Contract, r: &Resource) -> super::Declaration {
declaration(r.kind, &r.template, &r.params, &r.annotations, |p| {
c.uses.iter().any(|u| u.to_string() == p)
})
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Names {
Role(String),
Param(String),
}
impl Names {
#[must_use]
pub fn read(v: &Value) -> Option<Names> {
let s = v.as_str()?;
let name = |n: &str| !n.is_empty() && !n.contains(['{', '}']);
if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
return name(inner).then(|| Names::Param(inner.to_owned()));
}
name(s).then(|| Names::Role(s.to_owned()))
}
#[must_use]
pub fn names(&self, role: &str) -> bool {
match self {
Names::Role(r) => r == role,
Names::Param(_) => true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReportInvalid {
NotState,
Value,
NotARole,
NotAParam,
RestParam,
ParamNotRole,
NotReport,
Pointers,
Details,
TwoReports,
}
impl ReportInvalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotState => "not_state",
Self::Value => "value",
Self::NotARole => "not_a_role",
Self::NotAParam => "not_a_param",
Self::RestParam => "rest_param",
Self::ParamNotRole => "param_not_role",
Self::NotReport => "not_report",
Self::Pointers => "pointers",
Self::Details => "details",
Self::TwoReports => "two_reports",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotState => "a report is state of its target",
Self::Value => {
"desired.report is a role's name, or the resource's one parameter in braces"
}
Self::NotARole => "the name is no requirement of the contract",
Self::NotAParam => "the name in braces is no parameter of the template",
Self::RestParam => "a rest parameter cannot name a role",
Self::ParamNotRole => {
"a template parameter the value does not name: one report per role"
}
Self::NotReport => "a report resource's type is the profile's packed Report",
Self::Pointers => {
"desired.pointers is 1 to 255 JSON Pointers, the first \"\", none twice"
}
Self::Details => "desired.details is at most 255 lines of at least one character",
Self::TwoReports => "another report resource of the contract can report the same role",
}
}
}
impl std::fmt::Display for ReportInvalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.says())
}
}
pub use crate::words::{Index, Word};
#[must_use]
pub fn word(table: Option<&[String]>, index: Index) -> Word<'_> {
words::read(table, index)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tables {
pub pointers: Vec<String>,
pub details: Vec<String>,
}
impl Default for Tables {
fn default() -> Self {
Self {
pointers: vec![String::new()],
details: Vec::new(),
}
}
}
fn index_of(i: usize) -> Index {
Index::at(i, MAX_INDEX)
}
impl Tables {
#[must_use]
pub fn place(&self, pointer: &str) -> Index {
if let Some(i) = self.pointers.iter().position(|p| p == pointer) {
return index_of(i);
}
self.pointers
.iter()
.enumerate()
.filter(|(_, p)| {
!p.is_empty()
&& pointer
.strip_prefix(p.as_str())
.is_some_and(|rest| rest.starts_with('/'))
})
.max_by_key(|(_, p)| p.len())
.map_or(Index::OutOfRange, |(i, _)| index_of(i))
}
#[must_use]
pub fn line(&self, text: &str) -> Index {
words::write(&self.details, text, MAX_INDEX)
}
#[must_use]
pub fn pointer(&self, index: Index) -> Word<'_> {
word(Some(&self.pointers), index)
}
#[must_use]
pub fn detail(&self, index: Index) -> Word<'_> {
word(Some(&self.details), index)
}
}
fn is_json_pointer(s: &str) -> bool {
if !(s.is_empty() || s.starts_with('/')) {
return false;
}
let b = s.as_bytes();
(0..b.len()).all(|i| b[i] != b'~' || matches!(b.get(i + 1), Some(b'0' | b'1')))
}
fn read_pointers(v: &Value) -> Option<Vec<String>> {
words::list(v, usize::from(MAX_INDEX) + 1, is_json_pointer, true)
.filter(|out| out.first().is_some_and(String::is_empty))
}
fn read_details(v: &Value) -> Option<Vec<String>> {
words::list(v, usize::from(MAX_INDEX) + 1, |d| !d.is_empty(), false)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReportDeclaration {
NotThisProfiles,
Invalid(Vec<ReportInvalid>),
Declared { names: Names, tables: Tables },
}
impl ReportDeclaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotThisProfiles => "not_this_profiles",
Self::Invalid(_) => "invalid",
Self::Declared { .. } => "declared",
}
}
}
#[must_use]
pub fn is_report(ty: &TypeId) -> bool {
matches!(ty, TypeId::Packed { name, schema } if name == REPORT && is_published(schema))
}
#[derive(Debug, Clone, Copy)]
pub struct ReportResource<'a> {
pub kind: Kind,
pub token: KindToken,
pub template: &'a Template,
pub is_report: bool,
pub annotations: &'a BTreeMap<String, Value>,
}
impl<'a> ReportResource<'a> {
#[must_use]
pub fn of(r: &'a Resource) -> Self {
Self {
kind: r.kind,
token: r.token,
template: &r.template,
is_report: matches!(&r.body, Body::Data(d) if is_report(&d.type_)),
annotations: &r.annotations,
}
}
}
#[must_use]
pub fn report_declaration<'v>(
r: &ReportResource<'_>,
is_role: impl Fn(&str) -> bool,
others: impl IntoIterator<Item = &'v Value>,
) -> ReportDeclaration {
let Some(v) = r.annotations.get(REPORT_KEY) else {
return ReportDeclaration::NotThisProfiles;
};
let mut why = Vec::new();
if r.kind != Kind::State {
why.push(ReportInvalid::NotState);
}
let names = Names::read(v);
let params: Vec<(&str, bool)> = r.template.params().collect();
match &names {
None => why.push(ReportInvalid::Value),
Some(Names::Role(name)) => {
if !is_role(name) {
why.push(ReportInvalid::NotARole);
}
if !params.is_empty() {
why.push(ReportInvalid::ParamNotRole);
}
}
Some(Names::Param(name)) => match params.iter().find(|(p, _)| p == name) {
None => why.push(ReportInvalid::NotAParam),
Some((_, true)) => why.push(ReportInvalid::RestParam),
Some((_, false)) => {
if params.iter().any(|(p, _)| p != name) {
why.push(ReportInvalid::ParamNotRole);
}
}
},
}
if !r.is_report {
why.push(ReportInvalid::NotReport);
}
let pointers = match r.annotations.get(POINTERS) {
None => Some(Tables::default().pointers),
Some(v) => read_pointers(v),
};
if pointers.is_none() {
why.push(ReportInvalid::Pointers);
}
let details = match r.annotations.get(DETAILS) {
None => Some(Vec::new()),
Some(v) => read_details(v),
};
if details.is_none() {
why.push(ReportInvalid::Details);
}
if let Some(mine) = &names {
let clash = |other: &Names| match (mine, other) {
(Names::Role(a), Names::Role(b)) => a == b,
_ => true,
};
if others
.into_iter()
.filter_map(Names::read)
.any(|o| clash(&o))
{
why.push(ReportInvalid::TwoReports);
}
}
match (names, pointers, details) {
(Some(names), Some(pointers), Some(details)) if why.is_empty() => {
ReportDeclaration::Declared {
names,
tables: Tables { pointers, details },
}
}
_ => ReportDeclaration::Invalid(why),
}
}
#[must_use]
pub fn report_declaration_of(c: &Contract, r: &Resource) -> ReportDeclaration {
report_declaration(
&ReportResource::of(r),
|name| c.requires.contains_key(name),
c.resources
.iter()
.filter(|o| !(o.token == r.token && o.template.as_str() == r.template.as_str()))
.filter_map(|o| o.annotations.get(REPORT_KEY)),
)
}
pub use crate::words::Lint;
#[must_use]
pub fn lint_contract(c: &Contract) -> Vec<Lint> {
if !uses_v2(c) {
return Vec::new();
}
let mut out = Vec::new();
for r in &c.resources {
let finding = |token, says| Lint {
profile: PROFILE,
at: Lint::place(r),
key: None,
token,
says,
};
if let super::Declaration::Invalid(why) = declaration_of(c, r) {
out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
}
if let ReportDeclaration::Invalid(why) = report_declaration_of(c, r) {
out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
}
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Outcome {
NotActed,
Converged,
Refused,
Failed,
Reverted,
}
impl Outcome {
const ALL: [Outcome; 5] = [
Outcome::NotActed,
Outcome::Converged,
Outcome::Refused,
Outcome::Failed,
Outcome::Reverted,
];
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotActed => "not_acted",
Self::Converged => "converged",
Self::Refused => "refused",
Self::Failed => "failed",
Self::Reverted => "reverted",
}
}
fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|o| o.as_str() == s)
}
#[must_use]
pub fn acted(self) -> Option<super::Outcome> {
match self {
Self::NotActed => None,
Self::Converged => Some(super::Outcome::Converged),
Self::Refused => Some(super::Outcome::Refused),
Self::Failed => Some(super::Outcome::Failed),
Self::Reverted => Some(super::Outcome::Reverted),
}
}
}
impl From<Option<super::Outcome>> for Outcome {
fn from(o: Option<super::Outcome>) -> Self {
match o {
None => Self::NotActed,
Some(super::Outcome::Converged) => Self::Converged,
Some(super::Outcome::Refused) => Self::Refused,
Some(super::Outcome::Failed) => Self::Failed,
Some(super::Outcome::Reverted) => Self::Reverted,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Code {
Undecodable,
Reach,
Sensitive,
Invalid,
Apply,
Own,
}
impl Code {
const NAMED: [Code; 5] = [
Code::Undecodable,
Code::Reach,
Code::Sensitive,
Code::Invalid,
Code::Apply,
];
#[must_use]
pub fn as_str(self) -> Option<&'static str> {
match self {
Self::Undecodable => Some(super::UNDECODABLE),
Self::Reach => Some(super::REACH),
Self::Sensitive => Some(super::SENSITIVE),
Self::Invalid => Some(super::INVALID),
Self::Apply => Some(super::APPLY),
Self::Own => None,
}
}
#[must_use]
pub fn of(code: &str) -> Code {
Self::NAMED
.into_iter()
.find(|c| c.as_str() == Some(code))
.unwrap_or(Code::Own)
}
fn to_json(self) -> Value {
self.as_str().map_or(Value::Null, Value::from)
}
fn of_json(v: &Value) -> Result<Code, WriteRefusal> {
match v {
Value::Null => Ok(Code::Own),
Value::String(s) => Self::NAMED
.into_iter()
.find(|c| c.as_str() == Some(s.as_str()))
.ok_or(WriteRefusal::Value),
_ => Err(WriteRefusal::Value),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Refusal {
pub code: Code,
pub pointer: Option<Index>,
pub detail: Option<Index>,
}
impl Refusal {
#[must_use]
pub fn new(code: Code) -> Self {
Self {
code,
pointer: None,
detail: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Observed {
pub version: Version,
pub revision: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum InForce {
#[default]
None,
Observed,
Other,
}
impl InForce {
const ALL: [InForce; 3] = [InForce::None, InForce::Observed, InForce::Other];
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Observed => "observed",
Self::Other => "other",
}
}
}
fn schema() -> Value {
let int = |name: &str, maximum: u64| json!({"name": name, "type": "int", "minimum": 0, "maximum": maximum, "optional": true});
let index = |name: &str| {
json!({"name": name, "type": "int", "minimum": 0, "maximum": MAX_INDEX,
"reserved": [OUT_OF_RANGE], "optional": true})
};
json!({"types": {(REPORT): {"fields": [
{"name": "source", "type": "enum", "values": ["baseline", "desired", "call"], "escape": true},
{"name": "outcome", "type": "enum",
"values": ["not_acted", "converged", "refused", "failed", "reverted"], "escape": true},
{"name": "last_known", "type": "bool"},
{"name": "in_force", "type": "enum", "values": ["none", "observed", "other"]},
int("observed_run16", 65_535),
int("observed_run32", MAX_REVISION),
int("observed_seq", 16_777_215),
int("revision", MAX_REVISION),
int("in_force_run16", 65_535),
int("in_force_run32", MAX_REVISION),
int("in_force_seq", 16_777_215),
int("in_force_revision", MAX_REVISION),
{"name": "code", "type": "enum",
"values": ["undecodable", "reach", "sensitive", "invalid", "apply"],
"escape": true, "optional": true},
index("pointer"),
index("detail"),
packed::MARKER,
]}}})
}
#[must_use]
pub fn layout() -> &'static Layout {
static LAYOUT: OnceLock<Layout> = OnceLock::new();
LAYOUT.get_or_init(|| {
packed::layout_in(&schema(), REPORT).expect("the standard Report's declaration reads")
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Fields {
pub source: Option<Source>,
pub outcome: Option<Outcome>,
pub last_known: bool,
pub in_force: InForce,
pub observed_run16: Option<u16>,
pub observed_run32: Option<u32>,
pub observed_seq: Option<u32>,
pub revision: Option<u32>,
pub in_force_run16: Option<u16>,
pub in_force_run32: Option<u32>,
pub in_force_seq: Option<u32>,
pub in_force_revision: Option<u32>,
pub code: Option<Code>,
pub pointer: Option<Index>,
pub detail: Option<Index>,
}
fn stated(run16: Option<u16>, run32: Option<u32>, seq: Option<u32>) -> Option<Version> {
let run = match (run16, run32) {
(Some(r), None) => Run::U16(r),
(None, Some(r)) => Run::U32(r),
_ => return None,
};
Some(Stamp {
run,
seq: Seq::new(seq?)?,
})
}
impl Fields {
#[must_use]
pub fn observed(&self) -> Option<Version> {
stated(self.observed_run16, self.observed_run32, self.observed_seq)
}
#[must_use]
pub fn other_in_force(&self) -> Option<Version> {
stated(self.in_force_run16, self.in_force_run32, self.in_force_seq)
}
#[must_use]
pub fn to_json(&self) -> Value {
let mut m = Map::new();
let mut put = |k: &str, v: Option<Value>| {
if let Some(v) = v {
m.insert(k.to_owned(), v);
}
};
put(
"source",
Some(self.source.map_or(Value::Null, |s| json!(s.as_str()))),
);
put(
"outcome",
Some(self.outcome.map_or(Value::Null, |o| json!(o.as_str()))),
);
put("last_known", Some(json!(self.last_known)));
put("in_force", Some(json!(self.in_force.as_str())));
put("observed_run16", self.observed_run16.map(Value::from));
put("observed_run32", self.observed_run32.map(Value::from));
put("observed_seq", self.observed_seq.map(Value::from));
put("revision", self.revision.map(Value::from));
put("in_force_run16", self.in_force_run16.map(Value::from));
put("in_force_run32", self.in_force_run32.map(Value::from));
put("in_force_seq", self.in_force_seq.map(Value::from));
put("in_force_revision", self.in_force_revision.map(Value::from));
put("code", self.code.map(Code::to_json));
put("pointer", self.pointer.map(Index::to_json));
put("detail", self.detail.map(Index::to_json));
Value::Object(m)
}
pub fn of_json(v: &Value) -> Result<Fields, WriteRefusal> {
let Value::Object(o) = v else {
return Err(WriteRefusal::Value);
};
let number = |k: &str, max: u64| -> Result<Option<u64>, WriteRefusal> {
match o.get(k) {
None => Ok(None),
Some(Value::Number(n)) => match n.as_u64() {
Some(x) if x <= max => Ok(Some(x)),
_ => Err(WriteRefusal::Range),
},
Some(_) => Err(WriteRefusal::Value),
}
};
#[allow(clippy::cast_possible_truncation)]
let u16_of = |k: &str| number(k, u64::from(u16::MAX)).map(|x| x.map(|x| x as u16));
#[allow(clippy::cast_possible_truncation)]
let u32_of = |k: &str| number(k, u64::from(u32::MAX)).map(|x| x.map(|x| x as u32));
let named = |k: &str| match o.get(k) {
Some(Value::String(s)) => Ok(Some(s.as_str())),
Some(Value::Null) => Ok(None),
Some(_) => Err(WriteRefusal::Value),
None => Err(WriteRefusal::Missing),
};
let source = match named("source")? {
None => None,
Some(s) => Some(
[Source::Baseline, Source::Desired, Source::Call]
.into_iter()
.find(|x| x.as_str() == s)
.ok_or(WriteRefusal::Value)?,
),
};
let outcome = match named("outcome")? {
None => None,
Some(s) => Some(Outcome::parse(s).ok_or(WriteRefusal::Value)?),
};
let in_force = match o.get("in_force") {
Some(Value::String(s)) => InForce::ALL
.into_iter()
.find(|x| x.as_str() == s)
.ok_or(WriteRefusal::Value)?,
Some(_) => return Err(WriteRefusal::Value),
None => return Err(WriteRefusal::Missing),
};
let last_known = match o.get("last_known") {
Some(Value::Bool(b)) => *b,
Some(_) => return Err(WriteRefusal::Value),
None => return Err(WriteRefusal::Missing),
};
Ok(Fields {
source,
outcome,
last_known,
in_force,
observed_run16: u16_of("observed_run16")?,
observed_run32: u32_of("observed_run32")?,
observed_seq: u32_of("observed_seq")?,
revision: u32_of("revision")?,
in_force_run16: u16_of("in_force_run16")?,
in_force_run32: u32_of("in_force_run32")?,
in_force_seq: u32_of("in_force_seq")?,
in_force_revision: u32_of("in_force_revision")?,
code: o.get("code").map(Code::of_json).transpose()?,
pointer: o.get("pointer").map(Index::of_json).transpose()?,
detail: o.get("detail").map(Index::of_json).transpose()?,
})
}
pub fn record(&self) -> Result<Record, WriteRefusal> {
layout().write(&self.to_json(), None)
}
#[must_use]
pub fn check(&self) -> Vec<Finding> {
let (Some(source), Some(outcome)) = (self.source, self.outcome) else {
return vec![Finding::Escape];
};
let mut out = Vec::new();
let observed = self.observed();
let other = self.other_in_force();
let any_observed = self.observed_run16.is_some()
|| self.observed_run32.is_some()
|| self.observed_seq.is_some()
|| self.revision.is_some();
let any_other = self.in_force_run16.is_some()
|| self.in_force_run32.is_some()
|| self.in_force_seq.is_some()
|| self.in_force_revision.is_some();
if (any_observed && observed.is_none()) || (any_other && other.is_none()) {
out.push(Finding::RunFields);
}
let acted = matches!(
outcome,
Outcome::Converged | Outcome::Refused | Outcome::Failed
);
if (observed.is_some() && outcome == Outcome::NotActed) || (acted && observed.is_none()) {
out.push(Finding::ObservedOutcome);
}
let refusing = matches!(outcome, Outcome::Refused | Outcome::Failed);
let refusal = self.code.is_some() || self.pointer.is_some() || self.detail.is_some();
if (refusal && !refusing) || (refusing && self.code.is_none()) {
out.push(Finding::Refusal);
}
if (source == Source::Desired && observed.is_none())
|| (outcome == Outcome::Converged && source == Source::Baseline)
|| (outcome == Outcome::Reverted && source == Source::Desired)
{
out.push(Finding::Source);
}
let names = self.in_force != InForce::None;
let misplaced = names && (source != Source::Desired || outcome == Outcome::Failed);
let not_observed = outcome == Outcome::Converged
&& source == Source::Desired
&& self.in_force != InForce::Observed;
let no_observed = self.in_force == InForce::Observed && observed.is_none();
let no_other = self.in_force == InForce::Other && (other.is_none() || other == observed);
let stray = self.in_force != InForce::Other && any_other;
if misplaced || not_observed || no_observed || no_other || stray {
out.push(Finding::InForce);
}
if outcome == Outcome::Reverted && self.revision.is_some() {
out.push(Finding::RevisionOnRevert);
}
if self.last_known && observed.is_none() {
out.push(Finding::LastKnown);
}
out
}
#[must_use]
pub fn report(&self) -> Option<Report> {
if !self.check().is_empty() {
return None;
}
let observed = self.observed().map(|version| Observed {
version,
revision: self.revision.map(u64::from),
});
let in_force = match self.in_force {
InForce::None => None,
InForce::Observed => observed,
InForce::Other => self.other_in_force().map(|version| Observed {
version,
revision: self.in_force_revision.map(u64::from),
}),
};
Some(Report {
source: self.source?,
outcome: self.outcome?,
last_known: self.last_known,
observed,
in_force,
refusal: self.code.map(|code| Refusal {
code,
pointer: self.pointer,
detail: self.detail,
}),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Report {
pub source: Source,
pub outcome: Outcome,
pub last_known: bool,
pub observed: Option<Observed>,
pub in_force: Option<Observed>,
pub refusal: Option<Refusal>,
}
fn revision_field(r: Option<u64>) -> Result<Option<u32>, WriteRefusal> {
r.map(|r| u32::try_from(r).map_err(|_| WriteRefusal::Range))
.transpose()
}
fn observed_json(o: &Observed) -> Value {
let mut m = Map::new();
m.insert("version".into(), json!(version_text(o.version)));
if let Some(r) = o.revision {
m.insert("revision".into(), json!(r));
}
Value::Object(m)
}
fn observed_of(v: &Value) -> Result<Observed, WriteRefusal> {
let version = v
.get("version")
.and_then(Value::as_str)
.and_then(parse_version)
.ok_or(WriteRefusal::Value)?;
let revision = match v.get("revision") {
None => None,
Some(r) => Some(r.as_u64().ok_or(WriteRefusal::Value)?),
};
Ok(Observed { version, revision })
}
impl Report {
#[must_use]
pub fn baseline() -> Self {
Self {
source: Source::Baseline,
outcome: Outcome::NotActed,
last_known: false,
observed: None,
in_force: None,
refusal: None,
}
}
pub fn fields(&self) -> Result<Fields, WriteRefusal> {
let mut f = Fields {
source: Some(self.source),
outcome: Some(self.outcome),
last_known: self.last_known,
..Fields::default()
};
if let Some(o) = &self.observed {
match o.version.run {
Run::U16(r) => f.observed_run16 = Some(r),
Run::U32(r) => f.observed_run32 = Some(r),
}
f.observed_seq = Some(o.version.seq.get());
f.revision = revision_field(o.revision)?;
}
f.in_force = match (&self.in_force, &self.observed) {
(None, _) => InForce::None,
(Some(i), Some(o)) if i.version == o.version => {
revision_field(i.revision)?;
InForce::Observed
}
(Some(i), _) => {
match i.version.run {
Run::U16(r) => f.in_force_run16 = Some(r),
Run::U32(r) => f.in_force_run32 = Some(r),
}
f.in_force_seq = Some(i.version.seq.get());
f.in_force_revision = revision_field(i.revision)?;
InForce::Other
}
};
if let Some(r) = &self.refusal {
f.code = Some(r.code);
f.pointer = r.pointer;
f.detail = r.detail;
}
Ok(f)
}
pub fn write(&self) -> Result<Record, WriteRefusal> {
self.fields()?.record()
}
pub fn put(&self, stamp: Stamp) -> Result<Vec<u8>, WriteRefusal> {
let record = self.write()?;
let tag = Tag::new(TAG).expect("12 is a tag");
Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
}
#[must_use]
pub fn check(&self) -> Vec<Finding> {
self.fields().map(|f| f.check()).unwrap_or_default()
}
#[must_use]
pub fn reading(&self) -> Value {
let mut m = Map::new();
m.insert("source".into(), json!(self.source.as_str()));
m.insert("outcome".into(), json!(self.outcome.as_str()));
m.insert("last_known".into(), json!(self.last_known));
if let Some(o) = &self.observed {
m.insert("observed".into(), observed_json(o));
}
if let Some(i) = &self.in_force {
m.insert("in_force".into(), observed_json(i));
}
if let Some(r) = &self.refusal {
let mut x = Map::new();
x.insert("code".into(), r.code.to_json());
if let Some(p) = r.pointer {
x.insert("pointer".into(), p.to_json());
}
if let Some(d) = r.detail {
x.insert("detail".into(), d.to_json());
}
m.insert("refusal".into(), Value::Object(x));
}
Value::Object(m)
}
pub fn from_reading(v: &Value) -> Result<Report, WriteRefusal> {
let name = |k: &str| v.get(k).and_then(Value::as_str).ok_or(WriteRefusal::Value);
let source = name("source")?;
let source = [Source::Baseline, Source::Desired, Source::Call]
.into_iter()
.find(|s| s.as_str() == source)
.ok_or(WriteRefusal::Value)?;
let outcome = Outcome::parse(name("outcome")?).ok_or(WriteRefusal::Value)?;
let last_known = v
.get("last_known")
.and_then(Value::as_bool)
.ok_or(WriteRefusal::Value)?;
let refusal = match v.get("refusal") {
None => None,
Some(r) => Some(Refusal {
code: Code::of_json(r.get("code").ok_or(WriteRefusal::Value)?)?,
pointer: r.get("pointer").map(Index::of_json).transpose()?,
detail: r.get("detail").map(Index::of_json).transpose()?,
}),
};
Ok(Report {
source,
outcome,
last_known,
observed: v.get("observed").map(observed_of).transpose()?,
in_force: v.get("in_force").map(observed_of).transpose()?,
refusal,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Read {
pub fields: Fields,
pub findings: Vec<Finding>,
pub report: Option<Report>,
}
pub fn read(tag: u8, bytes: &[u8]) -> Result<Read, ReadRefusal> {
let value = layout().read(tag, bytes, None)?;
let fields = Fields::of_json(&value).map_err(|_| ReadRefusal::Code)?;
Ok(Read {
fields,
findings: fields.check(),
report: fields.report(),
})
}
impl Reported for Read {
fn facts(&self) -> Option<super::Facts> {
let r = self.report.as_ref()?;
Some(super::Facts {
source: r.source,
outcome: r.outcome.acted(),
last_known: r.last_known,
in_force: r.in_force.is_some(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cause {
Version(Version),
NoEntry {
run: Run,
asof: Seq,
},
}
impl machine::Mark for Cause {
type Epoch = Run;
type Tick = Seq;
fn epoch(&self) -> Run {
match self {
Cause::Version(v) => v.run,
Cause::NoEntry { run, .. } => *run,
}
}
fn tick(&self) -> Seq {
match self {
Cause::Version(v) => v.seq,
Cause::NoEntry { asof, .. } => *asof,
}
}
fn floor(&self) -> bool {
matches!(self, Cause::NoEntry { .. })
}
}
impl machine::Mark for Stamp {
type Epoch = Run;
type Tick = Seq;
fn epoch(&self) -> Run {
self.run
}
fn tick(&self) -> Seq {
self.seq
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sample {
pub via: Via,
pub mutation: Mutation,
pub version: Option<Version>,
pub revision: Option<u64>,
pub content: Option<Content>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Act {
pub kind: ActKind,
pub cause: Cause,
pub revision: Option<u64>,
pub via: Via,
pub content: Option<Content>,
}
impl Act {
#[must_use]
pub fn version(&self) -> Option<Version> {
match self.cause {
Cause::Version(v) => Some(v),
Cause::NoEntry { .. } => None,
}
}
#[must_use]
pub fn bound(&self) -> Option<Refusal> {
(self.kind == ActKind::Apply && self.revision.is_some_and(|r| r > MAX_REVISION))
.then(|| Refusal::new(Code::Invalid))
}
}
impl From<machine::Doing<Cause>> for Act {
fn from(d: machine::Doing<Cause>) -> Self {
Self {
kind: d.kind,
cause: d.mark,
revision: d.revision,
via: d.via,
content: d.content,
}
}
}
pub type Ended = super::Ended<Refusal>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Act(Act),
Adopted,
Held,
Unstamped,
SameVersion,
Older,
Confirmed,
Done,
NoVerdict,
}
impl Step {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Act(Act {
kind: ActKind::Apply,
..
}) => "act",
Self::Act(Act {
kind: ActKind::Revert,
..
}) => "revert",
Self::Adopted => "adopted",
Self::Held => "held",
Self::Unstamped => "unstamped",
Self::SameVersion => "same_version",
Self::Older => "older",
Self::Confirmed => "confirmed",
Self::Done => "done",
Self::NoVerdict => "no_verdict",
}
}
}
#[derive(Debug, Clone)]
pub struct Target {
core: machine::Core<Cause, Refusal>,
}
impl Default for Target {
fn default() -> Self {
Self::new()
}
}
impl Target {
#[must_use]
pub fn new() -> Self {
Self {
core: machine::Core::new(),
}
}
#[must_use]
pub fn report(&self) -> Report {
let seen = |(cause, revision): (Cause, Option<u64>)| match cause {
Cause::Version(version) => Some(Observed {
version,
revision: revision.filter(|r| *r <= MAX_REVISION),
}),
Cause::NoEntry { .. } => None,
};
let l = self.core.ledger();
Report {
source: l.source,
outcome: l.outcome.into(),
last_known: l.last_known,
observed: l.observed.and_then(seen),
in_force: l.in_force.and_then(seen),
refusal: l.refusal,
}
}
#[must_use]
pub fn running(&self) -> Option<Act> {
self.core.running().map(|d| Act::from(*d))
}
#[must_use]
pub fn remembered(&self, run: Run) -> Option<Seq> {
self.core.remembered(run)
}
#[must_use]
pub fn held(&self) -> Option<Version> {
self.holds().map(|(_, v)| v)
}
#[must_use]
pub fn holds(&self) -> Option<(Mutation, Version)> {
let d = self.core.latest()?;
match d.mark {
Cause::Version(v) => Some((
match d.kind {
ActKind::Apply => Mutation::Put,
ActKind::Revert => Mutation::Delete,
},
v,
)),
Cause::NoEntry { .. } => None,
}
}
pub fn observe(&mut self, s: Sample) -> Step {
let Some(version) = s.version else {
return Step::Unstamped;
};
let put = s.mutation == Mutation::Put;
match self.core.observe(machine::Doing {
kind: if put { ActKind::Apply } else { ActKind::Revert },
mark: Cause::Version(version),
revision: s.revision.filter(|_| put),
via: s.via,
content: s.content.filter(|_| put),
}) {
machine::Judged::Act(d) => Step::Act(d.into()),
machine::Judged::Adopted => Step::Adopted,
machine::Judged::Held => Step::Held,
machine::Judged::SameVersion => Step::SameVersion,
machine::Judged::Older => Step::Older,
machine::Judged::Confirmed => Step::Confirmed,
}
}
pub fn observe_no_entry(&mut self, run: Run, asof: Seq) -> Step {
match self.core.observe_floor(Cause::NoEntry { run, asof }) {
machine::Floored::NoVerdict => Step::NoVerdict,
machine::Floored::Older => Step::Older,
machine::Floored::Held => Step::Held,
machine::Floored::Act(d) => Step::Act(d.into()),
}
}
pub fn unchanged(&mut self, sent: Version) -> Step {
if self.core.unchanged(Cause::Version(sent)) {
Step::Confirmed
} else {
Step::SameVersion
}
}
pub fn finish(&mut self, ended: Ended) -> Step {
match self.core.finish(ended) {
machine::Finished::Done => Step::Done,
machine::Finished::Adopted => Step::Adopted,
machine::Finished::Act(d) => Step::Act(d.into()),
}
}
pub fn call(&mut self) {
self.core.call();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Section {
pub digest: Digest,
pub live: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Beat {
Revision,
Refused,
Read {
stamp: Stamp,
section: Option<Section>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
Revision,
Refused,
Older,
NoSection,
Unmoved,
Outstanding,
Read { held: Option<Version> },
}
impl Decision {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Revision => "revision",
Self::Refused => "refused",
Self::Older => "older",
Self::NoSection => "no_section",
Self::Unmoved => "unmoved",
Self::Outstanding => "outstanding",
Self::Read { .. } => "read",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answered {
Unchanged,
Whole,
NoAnswer,
}
impl Answered {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Unchanged => "unchanged",
Self::Whole => "whole",
Self::NoAnswer => "no_answer",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Heard {
Moved,
Kept,
}
impl Heard {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Moved => "moved",
Self::Kept => "kept",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Outstanding {
section: Section,
sent: Option<Version>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Watch {
key: String,
moves: bool,
sequence: crate::freshness::Sequence,
expects: Option<Section>,
outstanding: Option<Outstanding>,
}
impl Watch {
#[must_use]
pub fn new(key: impl Into<String>, moves: bool) -> Self {
Self {
key: key.into(),
moves,
sequence: crate::freshness::Sequence::default(),
expects: None,
outstanding: None,
}
}
#[must_use]
pub fn expects(&self) -> Option<Section> {
self.expects
}
#[must_use]
pub fn outstanding(&self) -> bool {
self.outstanding.is_some()
}
pub fn heartbeat(&mut self, beat: Beat, holds: Option<Version>) -> Decision {
let (stamp, section) = match beat {
Beat::Revision => {
self.expects = None;
return Decision::Revision;
}
Beat::Refused => {
self.expects = None;
return Decision::Refused;
}
Beat::Read { stamp, section } => (stamp, section),
};
let Some(read) = self.sequence.read(stamp) else {
return Decision::Older;
};
if read.gap || read.run {
self.expects = None;
}
let Some(section) = section else {
self.expects = None;
return Decision::NoSection;
};
if self.expects == Some(section) {
return Decision::Unmoved;
}
if self.outstanding.is_some() {
return Decision::Outstanding;
}
self.outstanding = Some(Outstanding {
section,
sent: holds,
});
Decision::Read { held: holds }
}
pub fn answer(&mut self, answer: Answered, holds: Option<Version>) -> Answered {
let Some(out) = self.outstanding.take() else {
return Answered::NoAnswer;
};
match answer {
Answered::Unchanged => {
self.expects = (out.sent.is_some() && out.sent == holds).then_some(out.section);
}
Answered::Whole => self.expects = None,
Answered::NoAnswer => {}
}
answer
}
pub fn heard(&mut self, old: Option<(Mutation, Version)>, new: (Mutation, Version)) -> Heard {
let (Some(section), Some(old), true) = (self.expects.as_mut(), old, self.moves) else {
return Heard::Kept;
};
if old.0 == Mutation::Put {
section.digest.toggle(&self.key, old.1);
section.live = section.live.saturating_sub(1);
}
if new.0 == Mutation::Put {
section.digest.toggle(&self.key, new.1);
section.live = section.live.saturating_add(1);
}
Heard::Moved
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReportAt {
None,
Two,
Invalid(Vec<ReportInvalid>),
At { key: Key, tables: Tables },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unreadable {
TwoReports,
Record(ReadRefusal),
}
impl Unreadable {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::TwoReports => "two_reports",
Self::Record(r) => r.token(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Found {
None(Vec<ReportInvalid>),
Unreadable(Unreadable),
One(Read),
}
impl Found {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::None(_) => "none",
Self::Unreadable(_) => "unreadable",
Self::One(_) => "one",
}
}
}
impl ReportAt {
#[must_use]
pub fn key(&self) -> Option<&Key> {
match self {
Self::At { key, .. } => Some(key),
_ => None,
}
}
#[must_use]
pub fn found(&self, reply: Option<(u8, &[u8])>) -> Found {
match self {
Self::None => Found::None(Vec::new()),
Self::Two => Found::Unreadable(Unreadable::TwoReports),
Self::Invalid(why) => Found::None(why.clone()),
Self::At { .. } => match reply {
None => Found::None(Vec::new()),
Some((tag, bytes)) => match read(tag, bytes) {
Ok(r) => Found::One(r),
Err(e) => Found::Unreadable(Unreadable::Record(e)),
},
},
}
}
}
#[must_use]
pub fn report_at(
target: &Addr,
iface: &IfaceId,
role: &str,
resources: &[ReportResource<'_>],
is_role: impl Fn(&str) -> bool,
) -> ReportAt {
let naming: Vec<usize> = resources
.iter()
.enumerate()
.filter(|(_, r)| {
r.annotations
.get(REPORT_KEY)
.and_then(Names::read)
.is_some_and(|n| n.names(role))
})
.map(|(i, _)| i)
.collect();
let at = match naming.as_slice() {
[] => return ReportAt::None,
[one] => *one,
_ => return ReportAt::Two,
};
let r = &resources[at];
let others = resources
.iter()
.enumerate()
.filter(|(i, _)| *i != at)
.filter_map(|(_, o)| o.annotations.get(REPORT_KEY));
let (names, tables) = match report_declaration(r, is_role, others) {
ReportDeclaration::Declared { names, tables } => (names, tables),
ReportDeclaration::Invalid(why) => return ReportAt::Invalid(why),
ReportDeclaration::NotThisProfiles => return ReportAt::None,
};
let mut values = Bindings::new();
if let Names::Param(p) = names {
values.insert(p, vec![role.to_owned()]);
}
let key = r.template.build(&values).ok().and_then(|chunks| {
let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
grammar::data_key(target, iface, r.token, &refs).ok()
});
match key {
Some(key) => ReportAt::At { key, tables },
None => ReportAt::None,
}
}
#[must_use]
pub fn report_at_of(target: &Addr, c: &Contract, role: &str) -> ReportAt {
let resources: Vec<ReportResource<'_>> = c.resources.iter().map(ReportResource::of).collect();
report_at(target, &c.iface, role, &resources, |name| {
c.requires.contains_key(name)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Current {
NotRead,
Incomplete,
Unstamped,
Silent,
Entry(Version),
Tombstone(Version),
NoEntry(Run),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthorReading {
pub presence: Seen,
pub current: Current,
}
#[must_use]
pub fn converged(t: &TargetReading<'_, Read>, a: &AuthorReading) -> Judged {
use Answer::{NotYet, Unobservable, Yes};
let judged = |answer, reason| Judged { answer, reason };
let report = match super::converging(t, a.presence) {
Ok((
Read {
report: Some(r), ..
},
_,
)) => *r,
Ok(_) => return judged(Unobservable, Reason::ReportInvalid),
Err(j) => return j,
};
let observed = report.observed.map(|o| o.version);
let current = match a.current {
Current::NotRead => return judged(Unobservable, Reason::AuthorNotRead),
Current::Incomplete | Current::Unstamped => {
return judged(Unobservable, Reason::AuthorReadIncomplete);
}
Current::Silent => return judged(Unobservable, Reason::AuthorSilent),
Current::NoEntry(run) => {
return match observed {
Some(o) if o.run == run && report.outcome == Outcome::Reverted => {
judged(Yes, Reason::Reverted)
}
Some(o) if o.run == run => judged(NotYet, Reason::Behind),
_ => judged(Unobservable, Reason::AuthorSilent),
};
}
Current::Entry(v) | Current::Tombstone(v) => v,
};
match (observed, report.outcome.acted()) {
(Some(o), Some(outcome)) => super::compared(&o, ¤t, outcome),
_ => judged(NotYet, Reason::NotActed),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn v(text: &str) -> Version {
parse_version(text).expect("a version")
}
fn put(text: &str, revision: u64) -> Sample {
Sample {
via: Via::Owner,
mutation: Mutation::Put,
version: Some(v(text)),
revision: Some(revision),
content: Some(Content::of_json(&json!({"revision": revision}))),
}
}
#[test]
fn a_version_is_written_as_its_run_and_its_seq() {
assert_eq!(version_text(v("0007/12")), "0007/12");
assert_eq!(version_text(v("00000007/12")), "00000007/12");
assert_ne!(v("0007/12"), v("00000007/12"), "two widths are two runs");
assert_eq!(v("ffff/16777215").seq, Seq::MAX);
for bad in [
"",
"7/12",
"007/12",
"00007/12",
"0007/",
"/12",
"0007/012",
"0007/+1",
"0007/1 ",
"000G/1",
"000A/1",
"0007/16777216",
"0007/1/2",
"0007",
"0007/-1",
"0007/000000001",
] {
assert_eq!(parse_version(bad), None, "{bad:?}");
}
assert_eq!(parse_version("0007/0"), Some(v("0007/0")));
}
#[test]
fn the_layout_is_the_texts() {
let l = layout();
assert_eq!(l.tag(), TAG);
assert_eq!(l.min_bits(), 20);
assert_eq!(Report::baseline().write().unwrap().bytes, [0, 0, 0]);
let longest = Report {
source: Source::Desired,
outcome: Outcome::Refused,
last_known: true,
observed: Some(Observed {
version: v("00a1b2c3/9"),
revision: Some(4),
}),
in_force: Some(Observed {
version: v("00a1b2c3/4"),
revision: Some(3),
}),
refusal: Some(Refusal {
code: Code::Reach,
pointer: Some(Index::At(3)),
detail: Some(Index::OutOfRange),
}),
};
let record = longest.write().unwrap();
assert_eq!((record.bits, record.bytes.len()), (215, 27));
assert_eq!(
read(TAG, &record.bytes).unwrap().report,
Some(longest),
"every report reads back"
);
}
#[test]
fn every_report_the_machine_makes_is_consistent() {
let mut t = Target::new();
let mut seen = vec![t.report()];
let mut note = |t: &Target| seen.push(t.report());
assert!(matches!(t.observe(put("0007/3", 1)), Step::Act(_)));
assert_eq!(t.observe(put("0007/4", 2)), Step::Held);
assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
note(&t);
t.finish(Ended::Refused(Refusal::new(Code::Reach)));
note(&t);
t.call();
note(&t);
let big = put("0007/5", MAX_REVISION + 1);
let Step::Act(act) = t.observe(big) else {
panic!("a new document is acted on");
};
let refusal = act.bound().expect("above the bound");
t.finish(Ended::Refused(refusal));
assert_eq!(t.report().observed.unwrap().revision, None);
note(&t);
let run = v("0007/0").run;
let asof = Seq::new(20).unwrap();
assert!(matches!(t.observe_no_entry(run, asof), Step::Act(_)));
t.finish(Ended::Failed(Refusal::new(Code::Apply)));
assert_eq!(t.report().outcome, Outcome::Failed);
assert_eq!(t.report().observed.map(|o| o.version), Some(v("0007/5")));
note(&t);
assert_eq!(t.observe(put("0007/20", 3)), Step::Older, "at the asof");
assert!(matches!(t.observe(put("0007/21", 3)), Step::Act(_)));
t.finish(Ended::Done);
note(&t);
assert!(matches!(
t.observe_no_entry(run, Seq::new(30).unwrap()),
Step::Act(_)
));
t.finish(Ended::Done);
assert_eq!(t.report().observed, None);
assert_eq!(t.held(), None, "after it the target holds no document");
note(&t);
for r in &seen {
assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
let record = r.write().expect("a record");
assert_eq!(read(TAG, &record.bytes).unwrap().report.as_ref(), Some(r));
}
}
#[test]
fn an_asof_at_the_held_seq_makes_that_version_older() {
let mut t = Target::new();
assert!(matches!(t.observe(put("0007/20", 1)), Step::Act(_)));
t.finish(Ended::Done);
assert_eq!(t.observe(put("0007/20", 1)), Step::SameVersion);
let run = v("0007/0").run;
assert!(matches!(
t.observe_no_entry(run, Seq::new(20).unwrap()),
Step::Act(_)
));
t.finish(Ended::Done);
assert_eq!(t.observe(put("0007/20", 1)), Step::Older);
assert_eq!(t.remembered(run), Seq::new(20));
}
#[test]
fn an_unchanged_answer_confirms_only_the_version_held() {
let archived = Sample {
via: Via::Archive,
..put("0007/3", 1)
};
let mut t = Target::new();
assert!(matches!(t.observe(archived), Step::Act(_)));
t.finish(Ended::Done);
assert!(t.report().last_known);
assert_eq!(t.unchanged(v("0007/2")), Step::SameVersion);
assert!(t.report().last_known, "another version's word");
assert_eq!(t.unchanged(v("0007/3")), Step::Confirmed);
assert!(!t.report().last_known);
assert_eq!(t.unchanged(v("0007/3")), Step::SameVersion);
assert_eq!(t.unchanged(v("0099/1")), Step::SameVersion);
assert_eq!(t.held(), Some(v("0007/3")));
}
#[test]
fn a_place_is_its_nearest_listed_ancestor() {
let t = Tables {
pointers: ["", "/a", "/a/b", "/a~1b"].map(str::to_owned).to_vec(),
details: vec!["x".into()],
};
assert_eq!(t.place(""), Index::At(0));
assert_eq!(t.place("/a/b/c/d"), Index::At(2));
assert_eq!(t.place("/a/c"), Index::At(1));
assert_eq!(t.place("/ab"), Index::OutOfRange);
assert_eq!(t.place("/z"), Index::OutOfRange, "never index 0");
assert_eq!(t.line("x"), Index::At(0));
assert_eq!(t.line("y"), Index::OutOfRange);
assert_eq!(t.pointer(Index::At(3)), Word::Entry("/a~1b"));
assert_eq!(t.pointer(Index::At(9)), Word::Number(9));
assert_eq!(word(None, Index::At(1)), Word::Number(1));
assert_eq!(t.detail(Index::OutOfRange), Word::OutOfRange);
}
#[test]
fn a_watch_makes_no_read_while_one_is_outstanding() {
let key = "zk2/lab/author/tasking.v2/state/tasks/lab/worker";
let held = v("0007/3");
let section = |seq: u32| Section {
digest: Digest::of([(key, v(&format!("0007/{seq}")))]),
live: 1,
};
let beat = |seq: u32, s: Section| Beat::Read {
stamp: v(&format!("0021/{seq}")),
section: Some(s),
};
let mut w = Watch::new(key, true);
assert_eq!(
w.heartbeat(beat(0, section(3)), Some(held)),
Decision::Read { held: Some(held) }
);
assert!(w.outstanding());
assert_eq!(
w.heartbeat(beat(1, section(3)), Some(held)),
Decision::Outstanding
);
assert_eq!(
w.answer(Answered::Unchanged, Some(held)),
Answered::Unchanged
);
assert_eq!(w.expects(), Some(section(3)));
assert_eq!(w.answer(Answered::Whole, Some(held)), Answered::NoAnswer);
assert_eq!(w.expects(), Some(section(3)));
let new = v("0007/9");
assert_eq!(
w.heard(Some((Mutation::Put, held)), (Mutation::Put, new)),
Heard::Moved
);
assert_eq!(
w.heartbeat(beat(2, section(9)), Some(new)),
Decision::Unmoved
);
assert_eq!(w.heard(None, (Mutation::Put, new)), Heard::Kept);
}
}