Files
faunosteo/crates/core/src/curation/draft/apply.rs
T

198 lines
7.1 KiB
Rust

//! Applies a changeset on a baseline document (`packages/anatomy/src/curation/apply.ts`),
//! deterministically and with a record per elementary edit. The references file replaces the
//! document registry first (it is the source of truth). Any op that cannot apply exactly as
//! written, and any integrity error left at the end, refuses: a curated document is never
//! produced from a partially applied changeset.
//!
//! Review rule: a level B or C change never leaves what it touched (findings, finding
//! categories, annotations: every item a set, add, cite, rename or move resolved to, whole
//! added subtrees and subtree scopes included) as inherited or reviewed. After its ops, the
//! applier sets `review_status = 'to_confirm'` on each one and records that edit under the
//! same change id. An explicit 'reviewed' in such a change refuses. Level A is untouched by
//! the rule.
use serde_json::Value;
use super::ops::{apply_op, assert_declared};
use super::records::{ChangeRecord, CurationResult, Recorder, strip_marks, touch_order};
use super::schema::{Change, ChangeSummary, Op, SetOp};
use super::targets::{
Path, Step, TargetKind, all_findings, at, fail, item_at_mut, list_at, top_collection_path,
};
use crate::curation::PipelineError;
use crate::domain::sheet::{
AnatomicalSheetDocument, Reference, SheetIssue, SheetIssueSeverity, validate_sheet_document,
};
/// A finding or an annotation a change touched: its touch order, its path, its target.
struct Touched {
order: u64,
path: Path,
target: String,
}
/// Findings and annotations of the document the change touched, in first-touch order.
fn touched_reviewable(doc: &Value) -> Result<Vec<Touched>, PipelineError> {
let mut candidates: Vec<(Path, String)> = all_findings(doc)?
.into_iter()
.map(|entry| (entry.path, entry.target))
.collect();
let annotations = top_collection_path(TargetKind::Annotation);
for (index, annotation) in list_at(doc, &annotations)?.iter().enumerate() {
let mut path = annotations.clone();
path.push(Step::Index(index));
let id = super::records::js_string(annotation.get("id"));
candidates.push((path, format!("annotation:{id}")));
}
let mut touched = Vec::new();
for (path, target) in candidates {
let Some(order) = at(doc, &path)?.as_object().and_then(touch_order) else {
continue;
};
touched.push(Touched {
order,
path,
target,
});
}
touched.sort_by_key(|item| item.order);
Ok(touched)
}
/// Marks every touched item still in the document 'to_confirm'.
fn mark_to_confirm(
doc: &mut Value,
change: &ChangeSummary,
records: &mut Vec<ChangeRecord>,
) -> Result<(), PipelineError> {
for touched in touched_reviewable(doc)? {
let item = item_at_mut(doc, &touched.path)?;
let status = item.get("review_status").cloned();
if status == Some(Value::from("to_confirm")) {
continue;
}
let before = match status {
None | Some(Value::Null) => Value::from("inherited"),
Some(value) => value,
};
item.insert("review_status".to_owned(), Value::from("to_confirm"));
let op = Op::Set(SetOp {
target: touched.target.clone(),
field: "review_status".to_owned(),
value: Value::from("to_confirm"),
scope: None,
});
records.push(ChangeRecord {
change: change.clone(),
op,
target: touched.target,
field: Some("review_status".to_owned()),
before,
after: Value::from("to_confirm"),
});
}
Ok(())
}
fn apply_change(
doc: &mut Value,
change: &Change,
records: &mut Vec<ChangeRecord>,
) -> Result<(), PipelineError> {
let summary = change.summary();
assert_declared(doc, &change.reference_ids)
.map_err(|error| fail(format!("{}: {error}", change.id)))?;
let mut next_touch = 0;
for (index, op) in change.ops.iter().enumerate() {
let mut recorder = Recorder::new(&summary, op, records, &mut next_touch);
apply_op(doc, &mut recorder)
.and_then(|()| assert_depth(doc))
.map_err(|error| fail(format!("{} op {index}: {error}", change.id)))?;
}
if change.level.needs_confirmation() {
mark_to_confirm(doc, &summary, records)?;
}
strip_marks(doc);
Ok(())
}
/// Nesting a valid sheet document never approaches (the equine document has 10 levels): a
/// resource bound checked after every op, so repeated adds, moves or deep values cannot grow
/// the document until a recursive walk overflows the stack.
pub const MAX_DOCUMENT_DEPTH: usize = 64;
/// The nesting of `value`, walked with an explicit stack (no recursion).
fn depth_of(value: &Value) -> usize {
let mut deepest = 0;
let mut pending = vec![(value, 1)];
while let Some((value, depth)) = pending.pop() {
let children: Box<dyn Iterator<Item = &Value>> = match value {
Value::Object(map) => Box::new(map.values()),
Value::Array(items) => Box::new(items.iter()),
_ => continue,
};
deepest = deepest.max(depth);
pending.extend(children.map(|child| (child, depth + 1)));
}
deepest
}
fn assert_depth(doc: &Value) -> Result<(), PipelineError> {
if depth_of(doc) > MAX_DOCUMENT_DEPTH {
return Err(fail(format!(
"the document nests more than {MAX_DOCUMENT_DEPTH} levels"
)));
}
Ok(())
}
fn describe(issues: &[SheetIssue]) -> String {
issues
.iter()
.map(|issue| format!("{}: {}", issue.path, issue.message))
.collect::<Vec<_>>()
.join("; ")
}
/// Shape (the strict R2 contract) then integrity check of a curated document. Refuses on any
/// shape issue or integrity error; returns the warnings, which are allowed.
pub fn curated_issues(doc: &Value) -> Result<Vec<SheetIssue>, PipelineError> {
let parsed: AnatomicalSheetDocument = serde_json::from_value(doc.clone())
.map_err(|error| fail(format!("curated document is not shape-valid: {error}")))?;
let issues = validate_sheet_document(&parsed);
let errors: Vec<SheetIssue> = issues
.iter()
.filter(|issue| issue.severity == SheetIssueSeverity::Error)
.cloned()
.collect();
if !errors.is_empty() {
return Err(fail(format!(
"curated document has integrity errors: {}",
describe(&errors)
)));
}
Ok(issues)
}
pub fn apply_changeset(
baseline: &Value,
references: &[Reference],
changes: &[Change],
) -> Result<CurationResult, PipelineError> {
let mut doc = baseline.clone();
let registry =
serde_json::to_value(references).map_err(|error| fail(format!("references: {error}")))?;
doc.as_object_mut()
.ok_or_else(|| fail("the baseline is not an object"))?
.insert("references".to_owned(), registry);
let mut records = Vec::new();
for change in changes {
apply_change(&mut doc, change, &mut records)?;
}
curated_issues(&doc)?;
Ok(CurationResult {
document: doc,
records,
})
}