From 64a43840ce23cf37a84b4a8cd80aaed22f53ac45 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 29 Oct 2026 13:14:21 +0100 Subject: [PATCH] feat(domain): V1-2.2 document measure, review groups, verdict, preview, edits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core's authoring surface of contract §16.3: the server's document measure, review groups with digests and removal groups, the change list, the pure server verdict in the shape M5 reads, PreviewSheet with draft and published modes, and the editor's commands with the §6.6 markings. --- .../core/src/domain/archive/snapshot_rules.rs | 4 +- crates/core/src/domain/sheet/caps.rs | 167 +++ crates/core/src/domain/sheet/edit.rs | 1021 +++++++++++++++++ crates/core/src/domain/sheet/index_data.rs | 11 +- crates/core/src/domain/sheet/keys.rs | 155 +++ crates/core/src/domain/sheet/loaded.rs | 2 +- crates/core/src/domain/sheet/mod.rs | 8 + crates/core/src/domain/sheet/preview.rs | 327 ++++++ crates/core/src/domain/sheet/report.rs | 81 ++ crates/core/src/domain/sheet/review.rs | 432 +++++++ crates/core/src/domain/sheet/size.rs | 133 +++ crates/core/src/domain/sheet/verdict.rs | 363 ++++++ crates/core/src/facade.rs | 47 + crates/core/src/ops.rs | 119 +- crates/core/tests/oracles/v1-2-2/size.json | 99 ++ crates/core/tests/oracles/v1-2-2/size.mjs | 92 ++ crates/core/tests/sheet_edit.rs | 797 +++++++++++++ crates/core/tests/sheet_preview.rs | 350 ++++++ crates/core/tests/sheet_review.rs | 351 ++++++ crates/core/tests/sheet_size.rs | 120 ++ crates/core/tests/sheet_verdict.rs | 542 +++++++++ 21 files changed, 5204 insertions(+), 17 deletions(-) create mode 100644 crates/core/src/domain/sheet/caps.rs create mode 100644 crates/core/src/domain/sheet/edit.rs create mode 100644 crates/core/src/domain/sheet/keys.rs create mode 100644 crates/core/src/domain/sheet/preview.rs create mode 100644 crates/core/src/domain/sheet/report.rs create mode 100644 crates/core/src/domain/sheet/review.rs create mode 100644 crates/core/src/domain/sheet/size.rs create mode 100644 crates/core/src/domain/sheet/verdict.rs create mode 100644 crates/core/tests/oracles/v1-2-2/size.json create mode 100644 crates/core/tests/oracles/v1-2-2/size.mjs create mode 100644 crates/core/tests/sheet_edit.rs create mode 100644 crates/core/tests/sheet_preview.rs create mode 100644 crates/core/tests/sheet_review.rs create mode 100644 crates/core/tests/sheet_size.rs create mode 100644 crates/core/tests/sheet_verdict.rs diff --git a/crates/core/src/domain/archive/snapshot_rules.rs b/crates/core/src/domain/archive/snapshot_rules.rs index ebdcb00a..cf7a0bc5 100644 --- a/crates/core/src/domain/archive/snapshot_rules.rs +++ b/crates/core/src/domain/archive/snapshot_rules.rs @@ -257,7 +257,7 @@ fn assert_finding_depth(input: &Value) -> Result<(), SnapshotRejection> { Ok(()) } -fn count_finding_nodes(document: &AnatomicalSheetDocument) -> usize { +pub(crate) fn count_finding_nodes(document: &AnatomicalSheetDocument) -> usize { fn nodes(list: &[FindingNode]) -> usize { list.iter().map(|n| 1 + nodes(&n.children)).sum() } @@ -270,7 +270,7 @@ fn count_finding_nodes(document: &AnatomicalSheetDocument) -> usize { } /// Longest `name` label (`fr` or `en`, UTF-16 units) anywhere in the document. -fn longest_name(document: &AnatomicalSheetDocument) -> usize { +pub(crate) fn longest_name(document: &AnatomicalSheetDocument) -> usize { fn node_names(list: &[FindingNode], longest: &mut usize) { for node in list { *longest = (*longest).max(label_len(&node.name)); diff --git a/crates/core/src/domain/sheet/caps.rs b/crates/core/src/domain/sheet/caps.rs new file mode 100644 index 00000000..241f92ec --- /dev/null +++ b/crates/core/src/domain/sheet/caps.rs @@ -0,0 +1,167 @@ +//! The caps every exportable sheet must keep (contract §1 « Archive caps », §6.7): a PDF +//! snapshot carries every view and every reachable drawing, so the snapshot's limits bound +//! the sheet itself, plus the server's cap on the document text (§12.2). The verdict refuses +//! a version over any of them; the editor shows them as they stand. + +use serde::Serialize; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::schema::{AnatomicalSheetDocument, FindingNode}; +use super::size::MAX_DOCUMENT_BYTES; +use crate::domain::archive::SnapshotCaps; +use crate::domain::archive::snapshot_rules::{count_finding_nodes, longest_name}; + +/// One cap, by name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum CapName { + Views, + Annotations, + FindingNodes, + FindingDepth, + LabelLength, + Drawings, + DrawingBytes, + DrawingsTotalBytes, + DocumentBytes, +} + +impl CapName { + /// The serde spelling. + pub fn as_str(self) -> &'static str { + match self { + Self::Views => "views", + Self::Annotations => "annotations", + Self::FindingNodes => "finding_nodes", + Self::FindingDepth => "finding_depth", + Self::LabelLength => "label_length", + Self::Drawings => "drawings", + Self::DrawingBytes => "drawing_bytes", + Self::DrawingsTotalBytes => "drawings_total_bytes", + Self::DocumentBytes => "document_bytes", + } + } +} + +/// What the sheet holds against each cap, and the caps it passes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct CapsReport { + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub views: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub annotations: u64, + /// Finding categories and nodes, categories counted. + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub finding_nodes: u64, + /// Deepest finding level, a category at 1. + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub finding_depth: u64, + /// Longest `name` label, `fr` or `en`, in UTF-16 units. + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub longest_label: u64, + /// Distinct drawings the views reference. + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub drawings: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub largest_drawing_bytes: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub drawings_total_bytes: u64, + /// The server's measure of the document (`octet_length(content::text)`). + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub document_bytes: u64, + pub exceeded: Vec, +} + +/// The report of `document`, measured at `document_bytes`, with the byte sizes of the +/// distinct drawings its views reference. +pub fn caps_report( + document: &AnatomicalSheetDocument, + document_bytes: u64, + drawing_sizes: &[u64], +) -> CapsReport { + let mut report = CapsReport { + views: count(document.views.len()), + annotations: count(document.annotations.len()), + finding_nodes: count(count_finding_nodes(document)), + finding_depth: count(finding_depth(document)), + longest_label: count(longest_name(document)), + drawings: count(drawing_sizes.len()), + largest_drawing_bytes: drawing_sizes.iter().copied().max().unwrap_or(0), + drawings_total_bytes: drawing_sizes.iter().sum(), + document_bytes, + exceeded: Vec::new(), + }; + report.exceeded = exceeded(&report); + report +} + +fn count(value: usize) -> u64 { + u64::try_from(value).unwrap_or(u64::MAX) +} + +fn exceeded(report: &CapsReport) -> Vec { + let limits = [ + (CapName::Views, report.views, SnapshotCaps::VIEWS), + ( + CapName::Annotations, + report.annotations, + SnapshotCaps::ANNOTATIONS, + ), + ( + CapName::FindingNodes, + report.finding_nodes, + SnapshotCaps::FINDING_NODES, + ), + ( + CapName::FindingDepth, + report.finding_depth, + SnapshotCaps::FINDING_DEPTH, + ), + ( + CapName::LabelLength, + report.longest_label, + SnapshotCaps::LABEL_CHARS, + ), + (CapName::Drawings, report.drawings, SnapshotCaps::ASSETS), + ( + CapName::DrawingBytes, + report.largest_drawing_bytes, + SnapshotCaps::ASSET_BYTES, + ), + ( + CapName::DrawingsTotalBytes, + report.drawings_total_bytes, + SnapshotCaps::ASSETS_TOTAL_BYTES, + ), + ]; + let mut over: Vec = limits + .into_iter() + .filter(|&(_, value, limit)| value > count(limit)) + .map(|(name, _, _)| name) + .collect(); + if report.document_bytes > MAX_DOCUMENT_BYTES { + over.push(CapName::DocumentBytes); + } + over +} + +/// Deepest level of the finding trees, a category at 1, a zone without categories at 0. +pub fn finding_depth(document: &AnatomicalSheetDocument) -> usize { + fn below(nodes: &[FindingNode]) -> usize { + nodes + .iter() + .map(|n| 1 + below(&n.children)) + .max() + .unwrap_or(0) + } + document + .finding_zones + .iter() + .flat_map(|zone| &zone.categories) + .map(|category| 1 + below(&category.children)) + .max() + .unwrap_or(0) +} diff --git a/crates/core/src/domain/sheet/edit.rs b/crates/core/src/domain/sheet/edit.rs new file mode 100644 index 00000000..c1b329b9 --- /dev/null +++ b/crates/core/src/domain/sheet/edit.rs @@ -0,0 +1,1021 @@ +//! The editor's commands (contract §6.6, §8.1): generic primitives over element keys, each +//! taking a strictly parsed document and giving the next one, with the marking rules applied +//! for the editor (the server trusts none of them: the verdict and the SQL check re-read the +//! statuses). +//! +//! - insert: the new element and everything under it start `to_confirm`; +//! - update: the element's own fields are replaced (its children, categories and marking +//! stay); any change of content turns its marking `to_confirm`; an id or code never changes; +//! - remove: the element goes with its descendants (a zone with its categories and nodes, a +//! node with its children); references to it are left to the validation panel, which +//! `dependents` lists beforehand; +//! - move: reorder among siblings, marking unchanged; +//! - set_status: one element to `to_confirm` or `reviewed`, never `inherited`; +//! - mark_reviewed: « Marquer comme relu » on one category (and its nodes) or one zone; +//! - after any command, the annotations of every view whose drawing or crop changed (its own +//! or an ancestor's drawing, its `view_box`) turn `to_confirm`. +//! +//! Refused: what would leave an element unaddressable (an id already used among its +//! siblings, a key that names nothing), a finding deeper than the 8 levels the editor offers, +//! a position past the end. Referential gaps stay possible: the integrity rules list them. +//! Of elements sharing a key (an integrity error), the first is the one addressed. + +use std::collections::HashMap; + +use serde::de::{DeserializeOwned, Error as _}; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::keys::ElementKey; +use super::schema::{ + AnatomicalSheetDocument, Annotation, AnnotationCategory, Attribution, FindingCategory, + FindingNode, FindingZone, LocalizedOptionalText, LocalizedText, Reference, ReviewStatus, + SheetView, VertebralRegion, ViewBox, +}; +use crate::anatomy::compose::asset_id_of_view; +use crate::domain::archive::SnapshotCaps; + +/// The sheet's own texts, set as one element. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(deny_unknown_fields)] +pub struct SheetTexts { + pub name: LocalizedText, + pub description: LocalizedOptionalText, + pub scope_disclaimer: LocalizedOptionalText, + pub attribution: Attribution, +} + +/// An element as the editor writes it, by kind. +#[derive(Debug, Clone, PartialEq)] +#[cfg_attr( + feature = "ts", + derive(TS), + ts(export, tag = "kind", content = "value", rename_all = "snake_case") +)] +pub enum NewElement { + Sheet(SheetTexts), + Reference(Reference), + Region(VertebralRegion), + Category(AnnotationCategory), + View(SheetView), + Annotation(Annotation), + Zone(FindingZone), + FindingCategory(FindingCategory), + FindingNode(FindingNode), +} + +/// The two markings an editor sets by hand. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum Marking { + ToConfirm, + Reviewed, +} + +impl From for ReviewStatus { + fn from(marking: Marking) -> Self { + match marking { + Marking::ToConfirm => Self::ToConfirm, + Marking::Reviewed => Self::Reviewed, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +#[cfg_attr( + feature = "ts", + derive(TS), + ts(export, tag = "op", rename_all = "snake_case") +)] +pub enum EditCommand { + /// `parent`: the zone a finding category goes into, the finding a node goes under; + /// absent for every other kind. `position` among the siblings, the end by default. + Insert { + element: NewElement, + #[cfg_attr(feature = "ts", ts(optional))] + parent: Option, + #[cfg_attr(feature = "ts", ts(optional))] + position: Option, + }, + Update { + key: ElementKey, + element: NewElement, + }, + Remove { + key: ElementKey, + }, + /// The element's new position among its siblings. + Move { + key: ElementKey, + position: usize, + }, + SetStatus { + key: ElementKey, + status: Marking, + }, + MarkReviewed { + key: ElementKey, + }, +} + +// The wire forms above are serde's tagged ones (`{"op": …, …}`, `{"kind": …, "value": …}`), +// read through `serde_json::Value`: serde's own tagged readers buffer through a private +// content type, which compiles every document type's reader a second time into the browser +// module (about 100 KB of gzip, measured at V1-2.2); the `Value` path reuses the readers the +// sheet load already has. Unknown fields are refused, as `deny_unknown_fields` would. + +impl<'de> Deserialize<'de> for NewElement { + fn deserialize>(deserializer: D) -> Result { + new_element(&Value::deserialize(deserializer)?).map_err(D::Error::custom) + } +} + +impl<'de> Deserialize<'de> for EditCommand { + fn deserialize>(deserializer: D) -> Result { + edit_command(&Value::deserialize(deserializer)?).map_err(D::Error::custom) + } +} + +type Read = Result; + +fn new_element(value: &Value) -> Read { + only_fields(value, &["kind", "value"])?; + let inner = required(value, "value")?; + Ok(match tag(value, "kind")? { + "sheet" => NewElement::Sheet(SheetTexts::deserialize(inner)?), + "reference" => NewElement::Reference(Reference::deserialize(inner)?), + "region" => NewElement::Region(VertebralRegion::deserialize(inner)?), + "category" => NewElement::Category(AnnotationCategory::deserialize(inner)?), + "view" => NewElement::View(SheetView::deserialize(inner)?), + "annotation" => NewElement::Annotation(Annotation::deserialize(inner)?), + "zone" => NewElement::Zone(FindingZone::deserialize(inner)?), + "finding_category" => NewElement::FindingCategory(FindingCategory::deserialize(inner)?), + "finding_node" => NewElement::FindingNode(FindingNode::deserialize(inner)?), + other => return Err(unknown("kind", other)), + }) +} + +fn edit_command(value: &Value) -> Read { + let op = tag(value, "op")?; + let fields: &[&str] = match op { + "insert" => &["op", "element", "parent", "position"], + "update" => &["op", "key", "element"], + "move" => &["op", "key", "position"], + "set_status" => &["op", "key", "status"], + _ => &["op", "key"], + }; + only_fields(value, fields)?; + let key = || field::(value, "key"); + Ok(match op { + "insert" => EditCommand::Insert { + element: new_element(required(value, "element")?)?, + parent: optional(value, "parent")?, + position: optional(value, "position")?, + }, + "update" => EditCommand::Update { + key: key()?, + element: new_element(required(value, "element")?)?, + }, + "remove" => EditCommand::Remove { key: key()? }, + "move" => EditCommand::Move { + key: key()?, + position: field(value, "position")?, + }, + "set_status" => EditCommand::SetStatus { + key: key()?, + status: field(value, "status")?, + }, + "mark_reviewed" => EditCommand::MarkReviewed { key: key()? }, + other => return Err(unknown("op", other)), + }) +} + +/// An object holding no field outside `allowed`. +fn only_fields(value: &Value, allowed: &[&str]) -> Read<()> { + let object = value + .as_object() + .ok_or_else(|| serde_json::Error::custom("expected an object"))?; + match object.keys().find(|key| !allowed.contains(&key.as_str())) { + Some(key) => Err(serde_json::Error::custom(format!("unknown field `{key}`"))), + None => Ok(()), + } +} + +fn tag<'a>(value: &'a Value, name: &str) -> Read<&'a str> { + required(value, name)? + .as_str() + .ok_or_else(|| serde_json::Error::custom(format!("`{name}` is not a string"))) +} + +fn required<'a>(value: &'a Value, name: &str) -> Read<&'a Value> { + value + .get(name) + .ok_or_else(|| serde_json::Error::custom(format!("missing field `{name}`"))) +} + +fn field(value: &Value, name: &str) -> Read { + T::deserialize(required(value, name)?) +} + +/// Absent or `null` is `None`, as `#[serde(default)]` on an `Option` reads it. +fn optional(value: &Value, name: &str) -> Read> { + value.get(name).map_or(Ok(None), Option::::deserialize) +} + +fn unknown(name: &str, found: &str) -> serde_json::Error { + serde_json::Error::custom(format!("unknown {name} `{found}`")) +} + +/// Why a command is refused; the document is left as it was. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EditError { + UnknownKey, + DuplicateKey, + /// The command does not apply to that element, or that parent. + InvalidTarget, + /// An update would change the element's id or code. + IdChanged, + InvalidPosition, + TooDeep, +} + +impl EditError { + pub fn kind(self) -> &'static str { + match self { + Self::UnknownKey => "unknown_key", + Self::DuplicateKey => "duplicate_key", + Self::InvalidTarget => "invalid_target", + Self::IdChanged => "id_changed", + Self::InvalidPosition => "invalid_position", + Self::TooDeep => "too_deep", + } + } +} + +type Edit = Result<(), EditError>; + +/// The document after `command`. +pub fn apply_edit( + document: &AnatomicalSheetDocument, + command: EditCommand, +) -> Result { + let mut next = document.clone(); + let drawn_before = view_drawings(&next); + match command { + EditCommand::Insert { + element, + parent, + position, + } => insert(&mut next, element, parent.as_ref(), position)?, + EditCommand::Update { key, element } => update(&mut next, &key, element)?, + EditCommand::Remove { key } => remove(&mut next, &key)?, + EditCommand::Move { key, position } => move_to(&mut next, &key, position)?, + EditCommand::SetStatus { key, status } => set_status(&mut next, &key, status.into())?, + EditCommand::MarkReviewed { key } => mark_reviewed(&mut next, &key)?, + } + reconfirm_redrawn_views(&mut next, &drawn_before); + Ok(next) +} + +// --------------------------------------------------------------------------- +// Lists + +/// Inserts at `position` (the end when absent). +fn insert_at(list: &mut Vec, item: T, position: Option) -> Edit { + let at = position.unwrap_or(list.len()); + if at > list.len() { + return Err(EditError::InvalidPosition); + } + list.insert(at, item); + Ok(()) +} + +/// Adds `item` unless an element of the list already has its id. +fn insert_new( + list: &mut Vec, + item: T, + id: impl Fn(&T) -> &str, + position: Option, +) -> Edit { + if list.iter().any(|existing| id(existing) == id(&item)) { + return Err(EditError::DuplicateKey); + } + insert_at(list, item, position) +} + +fn position_of(list: &[T], matches: impl Fn(&T) -> bool) -> Result { + list.iter().position(matches).ok_or(EditError::UnknownKey) +} + +fn reorder(list: &mut Vec, from: usize, to: usize) -> Edit { + if to >= list.len() { + return Err(EditError::InvalidPosition); + } + let item = list.remove(from); + list.insert(to, item); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Insert + +fn insert( + doc: &mut AnatomicalSheetDocument, + element: NewElement, + parent: Option<&ElementKey>, + position: Option, +) -> Edit { + match (element, parent) { + (NewElement::FindingCategory(category), Some(ElementKey::Zone { id })) => { + insert_category(doc, id, category, position) + } + (NewElement::FindingNode(node), Some(ElementKey::Finding { zone_id, path })) => { + insert_node(doc, zone_id, path, node, position) + } + (element, None) => insert_top(doc, element, position), + _ => Err(EditError::InvalidTarget), + } +} + +fn insert_top( + doc: &mut AnatomicalSheetDocument, + element: NewElement, + position: Option, +) -> Edit { + match element { + NewElement::Reference(r) => insert_new(&mut doc.references, r, |r| &r.id, position), + NewElement::Region(r) => { + insert_new(&mut doc.vertebral_config.regions, r, |r| &r.code, position) + } + NewElement::Category(c) => insert_new(&mut doc.categories, c, |c| &c.id, position), + NewElement::View(v) => insert_new(&mut doc.views, v, SheetView::id, position), + NewElement::Annotation(mut a) => { + set_annotation_status(&mut a, ReviewStatus::ToConfirm); + insert_new(&mut doc.annotations, a, Annotation::id, position) + } + NewElement::Zone(mut zone) => { + check_new_categories(&zone.categories)?; + zone.categories + .iter_mut() + .for_each(|c| mark_category(c, ReviewStatus::ToConfirm)); + insert_new(&mut doc.finding_zones, zone, |z| &z.id, position) + } + NewElement::Sheet(_) | NewElement::FindingCategory(_) | NewElement::FindingNode(_) => { + Err(EditError::InvalidTarget) + } + } +} + +fn insert_category( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + mut category: FindingCategory, + position: Option, +) -> Edit { + check_new_categories(std::slice::from_ref(&category))?; + mark_category(&mut category, ReviewStatus::ToConfirm); + let zone = zone_mut(doc, zone_id)?; + insert_new(&mut zone.categories, category, |c| &c.id, position) +} + +fn insert_node( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], + mut node: FindingNode, + position: Option, +) -> Edit { + if path.len() + depth_of(std::slice::from_ref(&node)) > SnapshotCaps::FINDING_DEPTH { + return Err(EditError::TooDeep); + } + check_unique_siblings(&node.children)?; + mark_node(&mut node, ReviewStatus::ToConfirm); + let children = children_mut(doc, zone_id, path)?; + insert_new(children, node, |n| &n.id, position) +} + +/// A new subtree: within the depth the editor offers, every sibling level without repeats. +fn check_new_categories(categories: &[FindingCategory]) -> Edit { + let deepest = categories + .iter() + .map(|c| 1 + depth_of(&c.children)) + .max() + .unwrap_or(0); + if deepest > SnapshotCaps::FINDING_DEPTH { + return Err(EditError::TooDeep); + } + unique(categories.iter().map(|c| c.id.as_str()))?; + categories + .iter() + .try_for_each(|c| check_unique_siblings(&c.children)) +} + +fn check_unique_siblings(nodes: &[FindingNode]) -> Edit { + unique(nodes.iter().map(|n| n.id.as_str()))?; + nodes + .iter() + .try_for_each(|n| check_unique_siblings(&n.children)) +} + +fn unique<'a>(ids: impl Iterator) -> Edit { + let mut seen = std::collections::HashSet::new(); + if ids.into_iter().all(|id| seen.insert(id)) { + Ok(()) + } else { + Err(EditError::DuplicateKey) + } +} + +/// Levels of a node list, the list itself counted (an empty list is 0). +fn depth_of(nodes: &[FindingNode]) -> usize { + nodes + .iter() + .map(|n| 1 + depth_of(&n.children)) + .max() + .unwrap_or(0) +} + +// --------------------------------------------------------------------------- +// Update + +fn update(doc: &mut AnatomicalSheetDocument, key: &ElementKey, element: NewElement) -> Edit { + match (key, element) { + (ElementKey::Sheet, NewElement::Sheet(texts)) => { + doc.name = texts.name; + doc.description = texts.description; + doc.scope_disclaimer = texts.scope_disclaimer; + doc.attribution = texts.attribution; + Ok(()) + } + (ElementKey::Reference { id }, NewElement::Reference(r)) => { + replace_same(&mut doc.references, id, r, |r| &r.id) + } + (ElementKey::Region { code }, NewElement::Region(r)) => { + replace_same(&mut doc.vertebral_config.regions, code, r, |r| &r.code) + } + (ElementKey::Category { id }, NewElement::Category(c)) => { + replace_same(&mut doc.categories, id, c, |c| &c.id) + } + (ElementKey::View { id }, NewElement::View(v)) => { + replace_same(&mut doc.views, id, v, SheetView::id) + } + (ElementKey::Annotation { id }, NewElement::Annotation(a)) => update_annotation(doc, id, a), + (ElementKey::Zone { id }, NewElement::Zone(zone)) => update_zone(doc, id, zone), + (ElementKey::Finding { zone_id, path }, NewElement::FindingCategory(c)) + if path.len() == 1 => + { + update_category(doc, zone_id, &path[0], c) + } + (ElementKey::Finding { zone_id, path }, NewElement::FindingNode(n)) if path.len() > 1 => { + update_node(doc, zone_id, path, n) + } + _ => Err(EditError::InvalidTarget), + } +} + +/// Replaces the first element of that id with `item`, which keeps the id. +fn replace_same(list: &mut [T], id: &str, item: T, id_of: impl Fn(&T) -> &str) -> Edit { + if id_of(&item) != id { + return Err(EditError::IdChanged); + } + let at = position_of(list, |existing| id_of(existing) == id)?; + list[at] = item; + Ok(()) +} + +fn update_annotation(doc: &mut AnatomicalSheetDocument, id: &str, mut next: Annotation) -> Edit { + if next.id() != id { + return Err(EditError::IdChanged); + } + let at = position_of(&doc.annotations, |a| a.id() == id)?; + let current = &doc.annotations[at]; + let status = super::keys::annotation_status(current); + set_annotation_status(&mut next, status); + let changed = &next != current; + if changed { + set_annotation_status(&mut next, ReviewStatus::ToConfirm); + } + doc.annotations[at] = next; + Ok(()) +} + +fn update_zone(doc: &mut AnatomicalSheetDocument, id: &str, next: FindingZone) -> Edit { + if next.id != id { + return Err(EditError::IdChanged); + } + zone_mut(doc, id)?.name = next.name; + Ok(()) +} + +fn update_category( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + id: &str, + next: FindingCategory, +) -> Edit { + if next.id != id { + return Err(EditError::IdChanged); + } + let category = category_mut(zone_mut(doc, zone_id)?, id)?; + let changed = category.kind != next.kind + || category.name != next.name + || category.description != next.description + || category.reference_ids != next.reference_ids; + category.kind = next.kind; + category.name = next.name; + category.description = next.description; + category.reference_ids = next.reference_ids; + if changed { + category.review_status = ReviewStatus::ToConfirm; + } + Ok(()) +} + +fn update_node( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], + next: FindingNode, +) -> Edit { + if path.last().is_none_or(|last| *last != next.id) { + return Err(EditError::IdChanged); + } + let node = node_mut(doc, zone_id, path)?; + let changed = node.name != next.name + || node.description != next.description + || node.requires_vet_referral != next.requires_vet_referral + || node.reference_ids != next.reference_ids; + node.name = next.name; + node.description = next.description; + node.requires_vet_referral = next.requires_vet_referral; + node.reference_ids = next.reference_ids; + if changed { + node.review_status = ReviewStatus::ToConfirm; + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Remove and move + +fn remove(doc: &mut AnatomicalSheetDocument, key: &ElementKey) -> Edit { + let at = locate(doc, key)?; + match key { + ElementKey::Sheet => return Err(EditError::InvalidTarget), + ElementKey::Reference { .. } => { + doc.references.remove(at); + } + ElementKey::Region { .. } => { + doc.vertebral_config.regions.remove(at); + } + ElementKey::Category { .. } => { + doc.categories.remove(at); + } + ElementKey::View { .. } => { + doc.views.remove(at); + } + ElementKey::Annotation { .. } => { + doc.annotations.remove(at); + } + ElementKey::Zone { .. } => { + doc.finding_zones.remove(at); + } + ElementKey::Finding { zone_id, path } => remove_finding(doc, zone_id, path, at)?, + } + Ok(()) +} + +fn remove_finding( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], + at: usize, +) -> Edit { + if path.len() == 1 { + zone_mut(doc, zone_id)?.categories.remove(at); + } else { + children_mut(doc, zone_id, &path[..path.len() - 1])?.remove(at); + } + Ok(()) +} + +fn move_to(doc: &mut AnatomicalSheetDocument, key: &ElementKey, to: usize) -> Edit { + let from = locate(doc, key)?; + match key { + ElementKey::Sheet => Err(EditError::InvalidTarget), + ElementKey::Reference { .. } => reorder(&mut doc.references, from, to), + ElementKey::Region { .. } => reorder(&mut doc.vertebral_config.regions, from, to), + ElementKey::Category { .. } => reorder(&mut doc.categories, from, to), + ElementKey::View { .. } => reorder(&mut doc.views, from, to), + ElementKey::Annotation { .. } => reorder(&mut doc.annotations, from, to), + ElementKey::Zone { .. } => reorder(&mut doc.finding_zones, from, to), + ElementKey::Finding { zone_id, path } if path.len() == 1 => { + reorder(&mut zone_mut(doc, zone_id)?.categories, from, to) + } + ElementKey::Finding { zone_id, path } => reorder( + children_mut(doc, zone_id, &path[..path.len() - 1])?, + from, + to, + ), + } +} + +/// The element's position among its siblings. +fn locate(doc: &mut AnatomicalSheetDocument, key: &ElementKey) -> Result { + match key { + ElementKey::Sheet => Err(EditError::InvalidTarget), + ElementKey::Reference { id } => position_of(&doc.references, |r| &r.id == id), + ElementKey::Region { code } => { + position_of(&doc.vertebral_config.regions, |r| &r.code == code) + } + ElementKey::Category { id } => position_of(&doc.categories, |c| &c.id == id), + ElementKey::View { id } => position_of(&doc.views, |v| v.id() == id), + ElementKey::Annotation { id } => position_of(&doc.annotations, |a| a.id() == id), + ElementKey::Zone { id } => position_of(&doc.finding_zones, |z| &z.id == id), + ElementKey::Finding { zone_id, path } => locate_finding(doc, zone_id, path), + } +} + +fn locate_finding( + doc: &mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], +) -> Result { + let Some((last, parent)) = path.split_last() else { + return Err(EditError::UnknownKey); + }; + if parent.is_empty() { + return position_of(&zone_mut(doc, zone_id)?.categories, |c| &c.id == last); + } + position_of(children_mut(doc, zone_id, parent)?, |n| &n.id == last) +} + +// --------------------------------------------------------------------------- +// Markings + +fn set_status(doc: &mut AnatomicalSheetDocument, key: &ElementKey, status: ReviewStatus) -> Edit { + match key { + ElementKey::Annotation { id } => { + let at = position_of(&doc.annotations, |a| a.id() == id)?; + set_annotation_status(&mut doc.annotations[at], status); + Ok(()) + } + ElementKey::Finding { zone_id, path } if path.len() == 1 => { + category_mut(zone_mut(doc, zone_id)?, &path[0])?.review_status = status; + Ok(()) + } + ElementKey::Finding { zone_id, path } if path.len() > 1 => { + node_mut(doc, zone_id, path)?.review_status = status; + Ok(()) + } + _ => Err(EditError::InvalidTarget), + } +} + +/// « Marquer comme relu »: one category with its nodes, or one zone. +fn mark_reviewed(doc: &mut AnatomicalSheetDocument, key: &ElementKey) -> Edit { + match key { + ElementKey::Zone { id } => { + let zone = zone_mut(doc, id)?; + zone.categories + .iter_mut() + .for_each(|c| mark_category(c, ReviewStatus::Reviewed)); + Ok(()) + } + ElementKey::Finding { zone_id, path } if path.len() == 1 => { + mark_category( + category_mut(zone_mut(doc, zone_id)?, &path[0])?, + ReviewStatus::Reviewed, + ); + Ok(()) + } + _ => Err(EditError::InvalidTarget), + } +} + +fn set_annotation_status(annotation: &mut Annotation, status: ReviewStatus) { + match annotation { + Annotation::Observable(a) => a.review_status = status, + Annotation::DetailTrigger(a) => a.review_status = status, + } +} + +fn mark_category(category: &mut FindingCategory, status: ReviewStatus) { + category.review_status = status; + category + .children + .iter_mut() + .for_each(|n| mark_node(n, status)); +} + +fn mark_node(node: &mut FindingNode, status: ReviewStatus) { + node.review_status = status; + node.children.iter_mut().for_each(|n| mark_node(n, status)); +} + +// --------------------------------------------------------------------------- +// Finding tree access + +fn zone_mut<'a>( + doc: &'a mut AnatomicalSheetDocument, + id: &str, +) -> Result<&'a mut FindingZone, EditError> { + doc.finding_zones + .iter_mut() + .find(|z| z.id == id) + .ok_or(EditError::UnknownKey) +} + +fn category_mut<'a>( + zone: &'a mut FindingZone, + id: &str, +) -> Result<&'a mut FindingCategory, EditError> { + zone.categories + .iter_mut() + .find(|c| c.id == id) + .ok_or(EditError::UnknownKey) +} + +/// The node at `path` (a category id, then node ids). +fn node_mut<'a>( + doc: &'a mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], +) -> Result<&'a mut FindingNode, EditError> { + let Some((last, parent)) = path.split_last() else { + return Err(EditError::UnknownKey); + }; + children_mut(doc, zone_id, parent)? + .iter_mut() + .find(|n| &n.id == last) + .ok_or(EditError::UnknownKey) +} + +/// The children of the category or node at `path` (at least the category id). +fn children_mut<'a>( + doc: &'a mut AnatomicalSheetDocument, + zone_id: &str, + path: &[String], +) -> Result<&'a mut Vec, EditError> { + let Some((category_id, below)) = path.split_first() else { + return Err(EditError::InvalidTarget); + }; + let mut children = &mut category_mut(zone_mut(doc, zone_id)?, category_id)?.children; + for segment in below { + children = &mut children + .iter_mut() + .find(|n| &n.id == segment) + .ok_or(EditError::UnknownKey)? + .children; + } + Ok(children) +} + +// --------------------------------------------------------------------------- +// Views redrawn + +/// Per view id (first occurrence): the drawing it shows and its crop. +fn view_drawings( + doc: &AnatomicalSheetDocument, +) -> HashMap, Option)> { + let mut out = HashMap::new(); + for view in &doc.views { + out.entry(view.id().to_owned()).or_insert_with(|| { + let asset = asset_id_of_view(doc, view.id()).map(str::to_owned); + (asset, view.view_box().cloned()) + }); + } + out +} + +/// Annotations of a view whose drawing or crop changed turn `to_confirm` (§6.6). +fn reconfirm_redrawn_views( + doc: &mut AnatomicalSheetDocument, + before: &HashMap, Option)>, +) { + let after = view_drawings(doc); + let redrawn: Vec<&String> = after + .iter() + .filter(|(id, drawn)| before.get(*id).is_some_and(|old| old != *drawn)) + .map(|(id, _)| id) + .collect(); + for annotation in &mut doc.annotations { + if redrawn.iter().any(|id| id.as_str() == annotation.view_id()) { + set_annotation_status(annotation, ReviewStatus::ToConfirm); + } + } +} + +// --------------------------------------------------------------------------- +// Dependents + +/// How a dependent relates to the element about to be removed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum Relation { + /// An annotation drawn in the view. + DrawnIn, + /// A detail view of the view. + ChildView, + /// A detail view link that opens the view. + Opens, + /// An annotation of the annotation category. + UsesCategory, + /// An annotation linked to the finding zone. + LinksZone, + /// A finding category or node that cites the reference. + Cites, + /// An annotation of the vertebral region. + UsesRegion, + /// A category or node removed with it. + Descendant, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct Dependent { + pub element: ElementKey, + pub relation: Relation, +} + +/// What names `key` or goes with it, for the delete confirmation (document order). +pub fn dependents(doc: &AnatomicalSheetDocument, key: &ElementKey) -> Vec { + let annotation = |a: &Annotation, relation| Dependent { + element: ElementKey::Annotation { + id: a.id().to_owned(), + }, + relation, + }; + match key { + ElementKey::View { id } => view_dependents(doc, id), + ElementKey::Category { id } => doc + .annotations + .iter() + .filter(|a| a.category_id() == id) + .map(|a| annotation(a, Relation::UsesCategory)) + .collect(), + ElementKey::Region { code } => doc + .annotations + .iter() + .filter(|a| { + a.observable() + .and_then(|o| o.vertebral_region_code.as_deref()) + == Some(code) + }) + .map(|a| annotation(a, Relation::UsesRegion)) + .collect(), + ElementKey::Zone { id } => zone_dependents(doc, id), + ElementKey::Finding { zone_id, path } => finding_descendants(doc, zone_id, path), + ElementKey::Reference { id } => citing(doc, id), + ElementKey::Sheet | ElementKey::Annotation { .. } => Vec::new(), + } +} + +fn view_dependents(doc: &AnatomicalSheetDocument, id: &str) -> Vec { + let mut out: Vec = doc + .views + .iter() + .filter(|v| v.parent_view_id() == Some(id)) + .map(|v| Dependent { + element: ElementKey::View { + id: v.id().to_owned(), + }, + relation: Relation::ChildView, + }) + .collect(); + for a in &doc.annotations { + let element = ElementKey::Annotation { + id: a.id().to_owned(), + }; + if a.view_id() == id { + out.push(Dependent { + element, + relation: Relation::DrawnIn, + }); + } else if a.trigger().is_some_and(|t| t.opens_view_id == id) { + out.push(Dependent { + element, + relation: Relation::Opens, + }); + } + } + out +} + +fn zone_dependents(doc: &AnatomicalSheetDocument, id: &str) -> Vec { + let mut out: Vec = doc + .annotations + .iter() + .filter(|a| a.observable().and_then(|o| o.finding_zone_id.as_deref()) == Some(id)) + .map(|a| Dependent { + element: ElementKey::Annotation { + id: a.id().to_owned(), + }, + relation: Relation::LinksZone, + }) + .collect(); + if let Some(zone) = doc.finding_zones.iter().find(|z| z.id == id) { + for category in &zone.categories { + let path = vec![category.id.clone()]; + out.push(descendant(id, path.clone())); + push_descendants(id, &category.children, path, &mut out); + } + } + out +} + +fn finding_descendants( + doc: &AnatomicalSheetDocument, + zone_id: &str, + path: &[String], +) -> Vec { + let Some(zone) = doc.finding_zones.iter().find(|z| z.id == zone_id) else { + return Vec::new(); + }; + let Some((first, rest)) = path.split_first() else { + return Vec::new(); + }; + let Some(category) = zone.categories.iter().find(|c| &c.id == first) else { + return Vec::new(); + }; + let mut children = &category.children; + for segment in rest { + match children.iter().find(|n| &n.id == segment) { + Some(node) => children = &node.children, + None => return Vec::new(), + } + } + let mut out = Vec::new(); + push_descendants(zone_id, children, path.to_vec(), &mut out); + out +} + +fn push_descendants( + zone_id: &str, + nodes: &[FindingNode], + path: Vec, + out: &mut Vec, +) { + for node in nodes { + let mut here = path.clone(); + here.push(node.id.clone()); + out.push(descendant(zone_id, here.clone())); + push_descendants(zone_id, &node.children, here, out); + } +} + +fn descendant(zone_id: &str, path: Vec) -> Dependent { + Dependent { + element: ElementKey::Finding { + zone_id: zone_id.to_owned(), + path, + }, + relation: Relation::Descendant, + } +} + +fn citing(doc: &AnatomicalSheetDocument, reference_id: &str) -> Vec { + let mut out = Vec::new(); + for zone in &doc.finding_zones { + for category in &zone.categories { + let path = vec![category.id.clone()]; + if category.reference_ids.iter().any(|r| r == reference_id) { + out.push(cite(&zone.id, path.clone())); + } + push_citing(&zone.id, &category.children, path, reference_id, &mut out); + } + } + out +} + +fn push_citing( + zone_id: &str, + nodes: &[FindingNode], + path: Vec, + reference_id: &str, + out: &mut Vec, +) { + for node in nodes { + let mut here = path.clone(); + here.push(node.id.clone()); + if node.reference_ids.iter().any(|r| r == reference_id) { + out.push(cite(zone_id, here.clone())); + } + push_citing(zone_id, &node.children, here, reference_id, out); + } +} + +fn cite(zone_id: &str, path: Vec) -> Dependent { + Dependent { + element: ElementKey::Finding { + zone_id: zone_id.to_owned(), + path, + }, + relation: Relation::Cites, + } +} diff --git a/crates/core/src/domain/sheet/index_data.rs b/crates/core/src/domain/sheet/index_data.rs index 3f934339..d8cfcfeb 100644 --- a/crates/core/src/domain/sheet/index_data.rs +++ b/crates/core/src/domain/sheet/index_data.rs @@ -44,11 +44,11 @@ pub struct SheetIndexData { pub node_keys: Vec, } -fn sorted(positions: &HashMap) -> BTreeMap { +pub(crate) fn sorted(positions: &HashMap) -> BTreeMap { positions.iter().map(|(id, &p)| (id.clone(), p)).collect() } -fn names( +pub(crate) fn names( indexed: IndexedDocument<'_>, by_id: &HashMap, ) -> BTreeMap { @@ -61,7 +61,7 @@ fn names( .collect() } -fn spine_ids(indexed: IndexedDocument<'_>) -> Vec { +pub(crate) fn spine_ids(indexed: IndexedDocument<'_>) -> Vec { let mut seen = HashSet::new(); indexed .document @@ -90,7 +90,10 @@ fn walk<'a, T: FindingLevelItem>(nodes: &'a [T], prefix: &mut Vec<&'a str>, out: } } -fn node_keys(indexed: IndexedDocument<'_>, by_id: &HashMap) -> Vec { +pub(crate) fn node_keys( + indexed: IndexedDocument<'_>, + by_id: &HashMap, +) -> Vec { let mut out = Vec::new(); for (position, zone) in indexed.document.finding_zones.iter().enumerate() { if by_id.get(&zone.id) != Some(&position) { diff --git a/crates/core/src/domain/sheet/keys.rs b/crates/core/src/domain/sheet/keys.rs new file mode 100644 index 00000000..2edb8d63 --- /dev/null +++ b/crates/core/src/domain/sheet/keys.rs @@ -0,0 +1,155 @@ +//! Element keys (contract §6.6): how one element of a sheet document is named by the edit +//! commands, the change list and the review screen, across versions. Ids are generated by the +//! page, never derived from labels, never edited; a finding category or node is named by its +//! path (`//…`), so it keeps its key under label changes and +//! sibling reordering and gets a new one when it moves. + +use serde::{Deserialize, Serialize}; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::schema::{ + AnatomicalSheetDocument, Annotation, FindingCategory, FindingNode, FindingZone, ReviewStatus, +}; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum ElementKey { + /// The sheet's own texts: names, description, scope disclaimer, attribution. + Sheet, + Reference { + id: String, + }, + /// A vertebral region, by code. + Region { + code: String, + }, + /// An annotation category. + Category { + id: String, + }, + View { + id: String, + }, + Annotation { + id: String, + }, + /// A finding zone. + Zone { + id: String, + }, + /// A finding category (one segment) or node (more), from its zone down. + Finding { + zone_id: String, + path: Vec, + }, +} + +impl ElementKey { + /// The review group the element belongs to in `document` (§6.3); an annotation follows + /// the view it is drawn in. + pub fn group_of(&self, document: &AnatomicalSheetDocument) -> Option { + match self { + Self::Sheet | Self::Reference { .. } | Self::Region { .. } | Self::Category { .. } => { + Some(GENERAL_GROUP.to_owned()) + } + Self::View { id } => Some(view_group(id)), + Self::Annotation { id } => document + .annotations + .iter() + .find(|a| a.id() == id) + .map(|a| view_group(a.view_id())), + Self::Zone { id } | Self::Finding { zone_id: id, .. } => Some(zone_group(id)), + } + } +} + +pub const GENERAL_GROUP: &str = "general"; + +pub fn view_group(view_id: &str) -> String { + format!("view:{view_id}") +} + +pub fn zone_group(zone_id: &str) -> String { + format!("zone:{zone_id}") +} + +/// One element that carries a review marking: an annotation, a finding category or node. +pub struct Marked { + pub key: ElementKey, + pub status: ReviewStatus, + pub group: String, + /// Finding categories and nodes only: the node flags a vet referral; categories never do. + pub vet_referral: bool, + /// Finding categories and nodes only: no reference cited. + pub uncited: bool, +} + +/// Every marked element of `document`, in document order: annotations, then each zone's +/// categories and nodes depth first. Duplicate keys are listed as they appear. +pub fn marked_elements(document: &AnatomicalSheetDocument) -> Vec { + let mut out: Vec = document + .annotations + .iter() + .map(|annotation| Marked { + key: ElementKey::Annotation { + id: annotation.id().to_owned(), + }, + status: annotation_status(annotation), + group: view_group(annotation.view_id()), + vet_referral: false, + uncited: false, + }) + .collect(); + for zone in &document.finding_zones { + push_zone(zone, &mut out); + } + out +} + +pub fn annotation_status(annotation: &Annotation) -> ReviewStatus { + match annotation { + Annotation::Observable(a) => a.review_status, + Annotation::DetailTrigger(a) => a.review_status, + } +} + +fn push_zone(zone: &FindingZone, out: &mut Vec) { + for category in &zone.categories { + push_category(zone, category, out); + } +} + +fn push_category(zone: &FindingZone, category: &FindingCategory, out: &mut Vec) { + let mut path = vec![category.id.clone()]; + out.push(Marked { + key: ElementKey::Finding { + zone_id: zone.id.clone(), + path: path.clone(), + }, + status: category.review_status, + group: zone_group(&zone.id), + vet_referral: false, + uncited: category.reference_ids.is_empty(), + }); + push_nodes(&zone.id, &category.children, &mut path, out); +} + +fn push_nodes(zone_id: &str, nodes: &[FindingNode], path: &mut Vec, out: &mut Vec) { + for node in nodes { + path.push(node.id.clone()); + out.push(Marked { + key: ElementKey::Finding { + zone_id: zone_id.to_owned(), + path: path.clone(), + }, + status: node.review_status, + group: zone_group(zone_id), + vet_referral: node.requires_vet_referral, + uncited: node.reference_ids.is_empty(), + }); + push_nodes(zone_id, &node.children, path, out); + path.pop(); + } +} diff --git a/crates/core/src/domain/sheet/loaded.rs b/crates/core/src/domain/sheet/loaded.rs index afc7f33a..426af74e 100644 --- a/crates/core/src/domain/sheet/loaded.rs +++ b/crates/core/src/domain/sheet/loaded.rs @@ -85,7 +85,7 @@ pub struct LoadedSheet { /// drawing (refused, never repaired: LRN-055). pub type Drawing = Result; -fn read_drawing(text: &str) -> Drawing { +pub(crate) fn read_drawing(text: &str) -> Drawing { match read_svg(text) { Ok(read) if read.removed.is_empty() => Ok(read.root), Ok(read) => Err(format!("removed {}", read.removed.join(", "))), diff --git a/crates/core/src/domain/sheet/mod.rs b/crates/core/src/domain/sheet/mod.rs index 225c7c00..2ff9d7af 100644 --- a/crates/core/src/domain/sheet/mod.rs +++ b/crates/core/src/domain/sheet/mod.rs @@ -1,14 +1,22 @@ //! The anatomical sheet: document contract, integrity rules, index, the loaded sheet of a //! session and what React reads of it. +pub mod caps; pub mod check; pub mod create; +pub mod edit; pub mod fingerprint; pub mod index; pub mod index_data; +pub mod keys; pub mod loaded; +pub mod preview; +pub mod report; +pub mod review; pub mod schema; +pub mod size; pub mod validate; +pub mod verdict; pub use check::{SheetCheck, check_sheet_document}; pub use create::{MAIN_VIEW_ID, create_empty_sheet_document}; diff --git a/crates/core/src/domain/sheet/preview.rs b/crates/core/src/domain/sheet/preview.rs new file mode 100644 index 00000000..e6bd1ad9 --- /dev/null +++ b/crates/core/src/domain/sheet/preview.rs @@ -0,0 +1,327 @@ +//! `PreviewSheet` (contract §8.1, §10): a stored sheet version loaded into the core for the +//! catalogue, the admin preview and the editor, with no report migration map, so it can never +//! open a report session (the report editor keeps `LoadedSheet`). +//! +//! At load: the document read strictly; each drawing's bytes hashed against the sha256 of +//! its row, then read once per sha256 through `read_svg` (a rejection or a removal affects +//! the views on that drawing only, as with `LoadedSheet`); for a published or deprecated +//! version, the fingerprint recomputed against the stored one, the caps, and every +//! referenced drawing present. A draft loads with its integrity errors, its caps excess and +//! its missing drawings, all reported (owner decision 2026-10-29); its document can then be +//! replaced after each edit without reading the drawings again. + +use std::collections::{BTreeMap, HashMap}; + +use serde::{Deserialize, Serialize}; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::caps::{CapName, caps_report}; +use super::fingerprint::document_fingerprint; +use super::index::SheetIndex; +use super::index_data::{names, node_keys, sorted, spine_ids}; +use super::loaded::{Drawing, read_drawing}; +use super::report::{SheetReport, referenced_asset_ids, sheet_report}; +use super::review::DigestError; +use super::schema::{AnatomicalSheetDocument, LocalizedText}; +use super::verdict::{read_document, sha256_hex}; +use crate::domain::js; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum PreviewStatus { + Draft, + Published, + Deprecated, +} + +impl PreviewStatus { + fn is_draft(self) -> bool { + self == Self::Draft + } +} + +/// The version as `get_sheet_version` gives it: status, document text, stored fingerprint +/// (published and deprecated versions). +#[derive(Debug, Clone, Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(deny_unknown_fields)] +pub struct PreviewInput { + pub status: PreviewStatus, + pub document: String, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional))] + pub fingerprint: Option, +} + +/// One downloaded drawing: its asset id, the sha256 of its row, the object's bytes. +#[derive(Debug, Clone)] +pub struct PreviewDrawing { + pub asset_id: String, + pub sha256: String, + pub bytes: Vec, +} + +/// Why a version cannot be previewed (contract §10; the page adds `not_found_or_denied`, +/// `core_unavailable` and `unavailable`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PreviewFailure { + InvalidDocument(String), + /// A referenced drawing of a published or deprecated version was not given. + DrawingMissing(String), + /// The bytes of a drawing do not hash to its row's sha256 (or the row's value is not one). + DrawingHashMismatch(String), + /// The recomputed fingerprint is not the stored one, or the version has none. + FingerprintMismatch, + /// A published or deprecated version over a cap. + Caps(Vec), + /// A published or deprecated version is never edited. + ReadOnly, +} + +impl PreviewFailure { + pub fn kind(&self) -> &'static str { + match self { + Self::InvalidDocument(_) => "invalid_document", + Self::DrawingMissing(_) => "drawing_missing", + Self::DrawingHashMismatch(_) => "drawing_hash_mismatch", + Self::FingerprintMismatch => "fingerprint_mismatch", + Self::Caps(_) => "caps", + Self::ReadOnly => "read_only", + } + } + + pub fn detail(&self) -> String { + match self { + Self::InvalidDocument(detail) + | Self::DrawingMissing(detail) + | Self::DrawingHashMismatch(detail) => detail.clone(), + Self::Caps(names) => names + .iter() + .map(|name| name.as_str()) + .collect::>() + .join(", "), + Self::FingerprintMismatch | Self::ReadOnly => String::new(), + } + } +} + +struct Asset { + sha256: String, + bytes: u64, +} + +/// A stored version, loaded. +pub struct PreviewSheet { + status: PreviewStatus, + document: AnatomicalSheetDocument, + document_bytes: u64, + /// Recomputed at load and at each replacement; `None` with an integrity error. + fingerprint: Option, + assets: HashMap, + /// Each drawing read once, by sha256. + drawings: HashMap, + reads: usize, +} + +impl PreviewSheet { + pub fn load(input: PreviewInput, given: Vec) -> Result { + let read = read_document(&input.document) + .ok_or_else(|| PreviewFailure::InvalidDocument("the document is refused".to_owned()))?; + let mut sheet = Self { + status: input.status, + fingerprint: document_fingerprint(&read.typed).ok(), + document: read.typed, + document_bytes: read.bytes, + assets: HashMap::new(), + drawings: HashMap::new(), + reads: 0, + }; + for drawing in given { + sheet.take_drawing(drawing)?; + } + if !sheet.status.is_draft() { + sheet.check_published(input.fingerprint.as_deref())?; + } + Ok(sheet) + } + + /// Published and deprecated versions: every referenced drawing given, the stored + /// fingerprint recomputed, every cap kept. + fn check_published(&self, stored: Option<&str>) -> Result<(), PreviewFailure> { + if let Some(missing) = referenced_asset_ids(&self.document) + .into_iter() + .find(|id| !self.assets.contains_key(*id)) + { + return Err(PreviewFailure::DrawingMissing(missing.to_owned())); + } + if stored.is_none() || stored != self.fingerprint.as_deref() { + return Err(PreviewFailure::FingerprintMismatch); + } + let caps = caps_report(&self.document, self.document_bytes, &self.drawing_sizes()); + if !caps.exceeded.is_empty() { + return Err(PreviewFailure::Caps(caps.exceeded)); + } + Ok(()) + } + + /// Hashes the bytes against the row, reads a new sha256 once, keeps the asset. + fn take_drawing(&mut self, drawing: PreviewDrawing) -> Result<(), PreviewFailure> { + if !js::is_sha256_hex(&drawing.sha256) || sha256_hex(&drawing.bytes) != drawing.sha256 { + return Err(PreviewFailure::DrawingHashMismatch(drawing.asset_id)); + } + if !self.drawings.contains_key(&drawing.sha256) { + self.reads += 1; + let read = std::str::from_utf8(&drawing.bytes) + .map_or_else(|_| Err("malformed".to_owned()), read_drawing); + self.drawings.insert(drawing.sha256.clone(), read); + } + let asset = Asset { + sha256: drawing.sha256, + bytes: drawing.bytes.len() as u64, + }; + self.assets.insert(drawing.asset_id, asset); + Ok(()) + } + + /// A draft's document after an edit; the drawings are kept as read. On a refusal the + /// previous document stays. + pub fn replace_document(&mut self, text: &str) -> Result<(), PreviewFailure> { + if !self.status.is_draft() { + return Err(PreviewFailure::ReadOnly); + } + let read = read_document(text) + .ok_or_else(|| PreviewFailure::InvalidDocument("the document is refused".to_owned()))?; + self.fingerprint = document_fingerprint(&read.typed).ok(); + self.document = read.typed; + self.document_bytes = read.bytes; + Ok(()) + } + + /// A drawing uploaded while the draft is open. + pub fn add_drawing(&mut self, drawing: PreviewDrawing) -> Result<(), PreviewFailure> { + if !self.status.is_draft() { + return Err(PreviewFailure::ReadOnly); + } + self.take_drawing(drawing) + } + + pub fn document(&self) -> &AnatomicalSheetDocument { + &self.document + } + + /// The drawing of an asset; `None` when it was not given. + pub fn drawing(&self, asset_id: &str) -> Option<&Drawing> { + let asset = self.assets.get(asset_id)?; + self.drawings.get(&asset.sha256) + } + + /// How many times a drawing was read (each sha256 once). + pub fn drawing_reads(&self) -> usize { + self.reads + } + + fn drawing_sizes(&self) -> Vec { + referenced_asset_ids(&self.document) + .into_iter() + .filter_map(|id| self.assets.get(id).map(|a| a.bytes)) + .collect() + } + + pub fn state(&self) -> Result { + let report = sheet_report( + &self.document, + self.document_bytes, + &self.drawing_sizes(), + None, + )?; + Ok(PreviewState { + status: self.status, + fingerprint: self.fingerprint.clone(), + drawings: self.drawing_states(), + index: preview_index(&self.document), + report, + document: self.document.clone(), + }) + } + + fn drawing_states(&self) -> Vec { + referenced_asset_ids(&self.document) + .into_iter() + .map(|id| { + let (state, detail) = match self.drawing(id) { + None => (PreviewDrawingStatus::Missing, None), + Some(Ok(_)) => (PreviewDrawingStatus::Ok, None), + Some(Err(reason)) => (PreviewDrawingStatus::Rejected, Some(reason.clone())), + }; + PreviewDrawingState { + asset_id: id.to_owned(), + state, + detail, + } + }) + .collect() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum PreviewDrawingStatus { + Ok, + /// Not given (not uploaded, or not downloaded). + Missing, + /// Refused by the reader, or needing a removal (`detail`: the reason or `removed …`). + Rejected, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct PreviewDrawingState { + pub asset_id: String, + pub state: PreviewDrawingStatus, + pub detail: Option, +} + +/// The lookups the canvas and the catalogue read (the `SheetIndexData` tables), present when +/// the document has a main view. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct PreviewIndex { + pub main_view_id: String, + pub view_by_id: BTreeMap, + pub annotation_by_id: BTreeMap, + pub finding_zone_by_id: BTreeMap, + pub names: BTreeMap, + pub spine_ids: Vec, + pub node_keys: Vec, +} + +fn preview_index(document: &AnatomicalSheetDocument) -> Option { + let index = SheetIndex::build(document).ok()?; + let indexed = index.over(document); + Some(PreviewIndex { + main_view_id: indexed.main_view().id().to_owned(), + view_by_id: sorted(index.view_positions()), + annotation_by_id: sorted(index.annotation_positions()), + finding_zone_by_id: sorted(index.zone_positions()), + names: names(indexed, index.annotation_positions()), + spine_ids: spine_ids(indexed), + node_keys: node_keys(indexed, index.zone_positions()), + }) +} + +/// What a page reads of a loaded version, after load and after each replacement. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct PreviewState { + pub status: PreviewStatus, + /// Recomputed; absent when the document has an integrity error. + pub fingerprint: Option, + pub report: SheetReport, + pub drawings: Vec, + pub index: Option, + /// The document as read (defaults filled in). + pub document: AnatomicalSheetDocument, +} diff --git a/crates/core/src/domain/sheet/report.rs b/crates/core/src/domain/sheet/report.rs new file mode 100644 index 00000000..9ac1c26b --- /dev/null +++ b/crates/core/src/domain/sheet/report.rs @@ -0,0 +1,81 @@ +//! What the core says of a sheet version as it stands, shared by the server verdict and the +//! editor's validation panel (contract §6.4, §8.1): the server measure of the document, the +//! issues (the integrity rules, then the submission rule that every annotation is drawn), the +//! caps, the completeness counts and the review groups. In a page it is advisory; only the +//! verdict decides. + +use serde::Serialize; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::caps::{CapsReport, caps_report}; +use super::review::{Completeness, DigestError, ReviewGroup, completeness, review_groups}; +use super::schema::{AnatomicalSheetDocument, Annotation}; +use super::validate::{SheetIssue, SheetIssueSeverity, validate_sheet_document}; + +/// The submission rule of §6.7 the integrity tier does not hold: a draft may keep an +/// annotation without geometry, a submitted revision may not. +pub const GEOMETRY_MISSING: &str = "annotation.geometry.missing"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct SheetReport { + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub document_bytes: u64, + pub issues: Vec, + pub caps: CapsReport, + pub completeness: Completeness, + pub groups: Vec, +} + +/// The report of `document` measured at `document_bytes`, with the byte sizes of the +/// drawings its views reference and the removal groups against `base`. +pub fn sheet_report( + document: &AnatomicalSheetDocument, + document_bytes: u64, + drawing_sizes: &[u64], + base: Option<&AnatomicalSheetDocument>, +) -> Result { + let mut issues = validate_sheet_document(document); + issues.extend(geometry_issues(document)); + Ok(SheetReport { + document_bytes, + issues, + caps: caps_report(document, document_bytes, drawing_sizes), + completeness: completeness(document), + groups: review_groups(document, base)?, + }) +} + +fn geometry_issues(document: &AnatomicalSheetDocument) -> Vec { + document + .annotations + .iter() + .enumerate() + .filter(|(_, annotation)| geometry_of(annotation).is_none()) + .map(|(index, annotation)| SheetIssue { + code: GEOMETRY_MISSING.to_owned(), + severity: SheetIssueSeverity::Error, + path: format!("annotations[{index}].geometry"), + message: format!("Annotation \"{}\" has no geometry", annotation.id()), + }) + .collect() +} + +fn geometry_of(annotation: &Annotation) -> Option<&super::schema::Geometry> { + match annotation { + Annotation::Observable(a) => a.geometry.as_ref(), + Annotation::DetailTrigger(a) => a.geometry.as_ref(), + } +} + +/// The distinct drawings the views reference, in view order. +pub fn referenced_asset_ids(document: &AnatomicalSheetDocument) -> Vec<&str> { + let mut ids: Vec<&str> = Vec::new(); + for id in document.views.iter().filter_map(|v| v.svg_asset_id()) { + if !ids.contains(&id) { + ids.push(id); + } + } + ids +} diff --git a/crates/core/src/domain/sheet/review.rs b/crates/core/src/domain/sheet/review.rs new file mode 100644 index 00000000..02dcba91 --- /dev/null +++ b/crates/core/src/domain/sheet/review.rs @@ -0,0 +1,432 @@ +//! The review model of a sheet version (contract §6.3, §6.6): completeness counts, review +//! groups with their digests, removal groups, and the change list against a base. +//! +//! Groups: `general` (the document's texts, references, vertebral regions and annotation +//! categories: everything but views, annotations and finding zones), `view:` (the view +//! and the annotations drawn in it, document order), `zone:` (the finding zone with its +//! categories and nodes), and, against a base, a removal group for each base view or zone the +//! version no longer has. A digest is the SHA-256 of the RFC 8785 text of +//! `{"group": , …content}`, read from the typed document, so an omitted status is +//! written out as `inherited`; a removal group's content is `"removed": true`. A group is +//! coverable when it holds no `to_confirm` or `inherited` element (a removal always is). +//! Elements sharing an id (an integrity error) all go into their group, in document order. +//! +//! The change list is a reading aid (coverage rests on the digests): each element added, +//! removed, changed or whose marking alone changed, against the base, grouped where the +//! element now is (removed ones where they were). A node that moved has a new key: removed +//! plus added. + +use std::collections::{HashMap, HashSet}; + +use serde::Serialize; +use serde_json::{Map, Value, json}; +use sha2::{Digest, Sha256}; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::fingerprint::canonical_json; +use super::keys::{ElementKey, GENERAL_GROUP, Marked, marked_elements, view_group, zone_group}; +use super::schema::{AnatomicalSheetDocument, FindingNode, FindingZone, ReviewStatus}; + +/// Elements per review marking. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct StatusCounts { + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub to_confirm: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub reviewed: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub inherited: u64, +} + +impl StatusCounts { + fn add(&mut self, status: ReviewStatus) { + match status { + ReviewStatus::ToConfirm => self.to_confirm += 1, + ReviewStatus::Reviewed => self.reviewed += 1, + ReviewStatus::Inherited => self.inherited += 1, + } + } + + fn all_reviewed(&self) -> bool { + self.to_confirm == 0 && self.inherited == 0 + } +} + +/// Shown, never blocking (§6.7): the markings, the vet referral nodes, and the finding +/// categories and nodes that cite no reference. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct Completeness { + pub statuses: StatusCounts, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub vet_referrals: u64, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub uncited: u64, +} + +pub fn completeness(document: &AnatomicalSheetDocument) -> Completeness { + let mut out = Completeness::default(); + for element in marked_elements(document) { + out.statuses.add(element.status); + out.vet_referrals += u64::from(element.vet_referral); + out.uncited += u64::from(element.uncited); + } + out +} + +/// One review group of a verdict (the shape `acknowledge_sheet_review_group` reads). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct ReviewGroup { + pub key: String, + pub digest: String, + pub coverable: bool, + /// A base view or zone the version no longer has. + pub removed: bool, + pub statuses: StatusCounts, +} + +/// A digest could not be computed (a value nested beyond the canonical depth). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DigestError; + +/// The groups of `document`, then the removal groups against `base`. +pub fn review_groups( + document: &AnatomicalSheetDocument, + base: Option<&AnatomicalSheetDocument>, +) -> Result, DigestError> { + let value = serde_json::to_value(document).map_err(|_| DigestError)?; + let marked = marked_elements(document); + let mut groups = vec![group(GENERAL_GROUP, general_content(&value), &marked)?]; + for id in distinct(document.views.iter().map(|v| v.id())) { + let content = view_content(&value, id); + groups.push(group(&view_group(id), content, &marked)?); + } + for id in distinct(document.finding_zones.iter().map(|z| z.id.as_str())) { + let content = members_with_id(&value, "finding_zones", id); + groups.push(group( + &zone_group(id), + json!({ "finding_zones": content }), + &marked, + )?); + } + if let Some(base) = base { + for key in group_keys(base) { + if !groups.iter().any(|g| g.key == key) { + groups.push(removal_group(key)?); + } + } + } + Ok(groups) +} + +/// The group keys of a document, `general` first (no removal groups). +pub fn group_keys(document: &AnatomicalSheetDocument) -> Vec { + let views = distinct(document.views.iter().map(|v| v.id())).map(view_group); + let zones = distinct(document.finding_zones.iter().map(|z| z.id.as_str())).map(zone_group); + std::iter::once(GENERAL_GROUP.to_owned()) + .chain(views) + .chain(zones) + .collect() +} + +fn distinct<'a>(ids: impl Iterator) -> impl Iterator { + let mut seen = std::collections::HashSet::new(); + ids.filter(move |id| seen.insert(*id)) +} + +fn group(key: &str, content: Value, marked: &[Marked]) -> Result { + let mut statuses = StatusCounts::default(); + for element in marked.iter().filter(|m| m.group == key) { + statuses.add(element.status); + } + Ok(ReviewGroup { + key: key.to_owned(), + digest: digest(key, content)?, + coverable: statuses.all_reviewed(), + removed: false, + statuses, + }) +} + +fn removal_group(key: String) -> Result { + Ok(ReviewGroup { + digest: digest(&key, json!({ "removed": true }))?, + key, + coverable: true, + removed: true, + statuses: StatusCounts::default(), + }) +} + +/// SHA-256 of the canonical text of `{"group": key, …content}`. +fn digest(key: &str, content: Value) -> Result { + let mut object = match content { + Value::Object(map) => map, + _ => Map::new(), + }; + object.insert("group".to_owned(), Value::String(key.to_owned())); + let text = canonical_json(&Value::Object(object)).map_err(|_| DigestError)?; + Ok(Sha256::digest(text.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) +} + +fn general_content(document: &Value) -> Value { + let mut map = document.as_object().cloned().unwrap_or_default(); + for key in ["views", "annotations", "finding_zones"] { + map.remove(key); + } + Value::Object(map) +} + +fn view_content(document: &Value, view_id: &str) -> Value { + let annotations: Vec = array(document, "annotations") + .filter(|a| a.get("view_id").and_then(Value::as_str) == Some(view_id)) + .cloned() + .collect(); + json!({ "views": members_with_id(document, "views", view_id), "annotations": annotations }) +} + +fn members_with_id(document: &Value, collection: &str, id: &str) -> Vec { + array(document, collection) + .filter(|item| item.get("id").and_then(Value::as_str) == Some(id)) + .cloned() + .collect() +} + +fn array<'a>(document: &'a Value, collection: &str) -> impl Iterator { + document + .get(collection) + .and_then(Value::as_array) + .into_iter() + .flatten() +} + +// --------------------------------------------------------------------------- +// Change list + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum ChangeKind { + Added, + Removed, + /// Content changed (the marking may have changed too). + Changed, + /// Only the review marking changed. + StatusChanged, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct ElementChange { + pub group: String, + pub element: ElementKey, + pub change: ChangeKind, + pub status_before: Option, + pub status_after: Option, +} + +/// One element as the change list compares it: its group, its own content without the +/// marking and without its children, and its marking. +struct Entry { + key: ElementKey, + group: String, + content: Value, + status: Option, +} + +/// The changes of `document` against `base`: present elements in document order, then the +/// removed ones in base order. Of two elements sharing a key, the first counts. +pub fn change_list( + document: &AnatomicalSheetDocument, + base: &AnatomicalSheetDocument, +) -> Vec { + let now = first_entries(entries(document)); + let before = first_entries(entries(base)); + let before_by_key: HashMap<&ElementKey, &Entry> = before.iter().map(|e| (&e.key, e)).collect(); + let now_keys: HashSet<&ElementKey> = now.iter().map(|e| &e.key).collect(); + let mut out: Vec = now + .iter() + .filter_map(|entry| compared(entry, before_by_key.get(&entry.key).copied())) + .collect(); + out.extend( + before + .iter() + .filter(|old| !now_keys.contains(&old.key)) + .map(|old| change(old, ChangeKind::Removed, old.status, None)), + ); + out +} + +/// What became of `entry` since `old` (absent in the base: added); `None` when nothing did. +fn compared(entry: &Entry, old: Option<&Entry>) -> Option { + let kind = match old { + None => ChangeKind::Added, + Some(old) if old.content != entry.content => ChangeKind::Changed, + Some(old) if old.status != entry.status => ChangeKind::StatusChanged, + Some(_) => return None, + }; + Some(change( + entry, + kind, + old.and_then(|o| o.status), + entry.status, + )) +} + +fn change( + entry: &Entry, + change: ChangeKind, + status_before: Option, + status_after: Option, +) -> ElementChange { + ElementChange { + group: entry.group.clone(), + element: entry.key.clone(), + change, + status_before, + status_after, + } +} + +/// The entries in order, each key at its first occurrence only. +fn first_entries(entries: Vec) -> Vec { + let mut seen = HashSet::new(); + entries + .into_iter() + .filter(|entry| seen.insert(entry.key.clone())) + .collect() +} + +/// Every element of `document`, in document order: the general ones, the views and their +/// annotations, then each zone with its findings. +fn entries(document: &AnatomicalSheetDocument) -> Vec { + let mut out = general_entries(document); + out.extend(document.views.iter().map(|v| Entry { + key: ElementKey::View { + id: v.id().to_owned(), + }, + group: view_group(v.id()), + content: to_json(v), + status: None, + })); + out.extend(document.annotations.iter().map(|a| Entry { + key: ElementKey::Annotation { + id: a.id().to_owned(), + }, + group: view_group(a.view_id()), + content: without(to_json(a), &["review_status"]), + status: Some(super::keys::annotation_status(a)), + })); + for zone in &document.finding_zones { + zone_entries(zone, &mut out); + } + out +} + +/// The sheet's texts, the references, the vertebral regions and the annotation categories. +fn general_entries(document: &AnatomicalSheetDocument) -> Vec { + let general = |key: ElementKey, content: Value| Entry { + key, + group: GENERAL_GROUP.to_owned(), + content, + status: None, + }; + let texts = json!({ + "name": to_json(&document.name), + "description": to_json(&document.description), + "scope_disclaimer": to_json(&document.scope_disclaimer), + "attribution": to_json(&document.attribution), + }); + let references = document + .references + .iter() + .map(|r| general(ElementKey::Reference { id: r.id.clone() }, to_json(r))); + let regions = document.vertebral_config.regions.iter().map(|r| { + general( + ElementKey::Region { + code: r.code.clone(), + }, + to_json(r), + ) + }); + let categories = document + .categories + .iter() + .map(|c| general(ElementKey::Category { id: c.id.clone() }, to_json(c))); + std::iter::once(general(ElementKey::Sheet, texts)) + .chain(references) + .chain(regions) + .chain(categories) + .collect() +} + +fn zone_entries(zone: &FindingZone, out: &mut Vec) { + out.push(Entry { + key: ElementKey::Zone { + id: zone.id.clone(), + }, + group: zone_group(&zone.id), + content: json!({ "id": zone.id, "name": to_json(&zone.name) }), + status: None, + }); + for category in &zone.categories { + let path = vec![category.id.clone()]; + let content = to_json(category); + out.push(finding_entry( + &zone.id, + path.clone(), + content, + category.review_status, + )); + finding_entries(&zone.id, &category.children, path, out); + } +} + +fn finding_entry(zone_id: &str, path: Vec, content: Value, status: ReviewStatus) -> Entry { + Entry { + key: ElementKey::Finding { + zone_id: zone_id.to_owned(), + path, + }, + group: zone_group(zone_id), + content: without(content, &["review_status", "children"]), + status: Some(status), + } +} + +fn finding_entries(zone_id: &str, nodes: &[FindingNode], path: Vec, out: &mut Vec) { + for node in nodes { + let mut here = path.clone(); + here.push(node.id.clone()); + out.push(finding_entry( + zone_id, + here.clone(), + to_json(node), + node.review_status, + )); + finding_entries(zone_id, &node.children, here, out); + } +} + +fn without(value: Value, keys: &[&str]) -> Value { + match value { + Value::Object(mut map) => { + for key in keys { + map.remove(*key); + } + Value::Object(map) + } + other => other, + } +} + +/// A document part as a JSON value (a part that cannot be written compares as `null`). +fn to_json(item: &T) -> Value { + serde_json::to_value(item).unwrap_or(Value::Null) +} diff --git a/crates/core/src/domain/sheet/size.rs b/crates/core/src/domain/sheet/size.rs new file mode 100644 index 00000000..1d11e4ac --- /dev/null +++ b/crates/core/src/domain/sheet/size.rs @@ -0,0 +1,133 @@ +//! The size of a sheet document as the server measures it (contract §12.2, owner decision +//! 2026-10-28): the UTF-8 bytes of the text PostgreSQL prints for the stored `jsonb`, +//! `octet_length(content::text)`, capped at 2 MiB by the table CHECK and the save RPCs. +//! +//! That form is not `JSON.stringify`: `": "` follows each key and `", "` separates members +//! and elements; strings escape `"`, `\`, `\b \f \n \r \t` and the other controls as +//! `\u00xx`, every other character kept as UTF-8; numbers print as PostgreSQL's `numeric` +//! prints them (plain digits, never an exponent: `1e21` takes 22 bytes, `1.5e-7` ten). Key +//! order does not change a length, and a repeated key keeps its last value as `jsonb` does, +//! as the core's reader does. The measure is exact for a text whose numbers are written as +//! JavaScript writes them, which is every text the core produces; another spelling of the +//! same number (`1.50`, `1E2`) is stored as written and may measure differently. +//! +//! Lengths are summed without building the text, in one walk. + +use serde_json::Value; + +use crate::json::js_number; + +/// The server's cap on a document (`anatomical_sheet_versions_content_size`). +pub const MAX_DOCUMENT_BYTES: u64 = 2 * 1024 * 1024; + +/// `octet_length(value::jsonb::text)`. +pub fn document_text_bytes(value: &Value) -> u64 { + match value { + Value::Null | Value::Bool(true) => 4, + Value::Bool(false) => 5, + Value::Number(number) => number_bytes(number), + Value::String(text) => string_bytes(text), + Value::Array(items) => { + let inner: u64 = items.iter().map(document_text_bytes).sum(); + 2 + inner + separators(items.len()) + } + Value::Object(map) => { + let inner: u64 = map + .iter() + .map(|(key, item)| string_bytes(key) + 2 + document_text_bytes(item)) + .sum(); + 2 + inner + separators(map.len()) + } + } +} + +/// `", "` between `count` members or elements. +fn separators(count: usize) -> u64 { + 2 * u64::try_from(count.saturating_sub(1)).unwrap_or(u64::MAX) +} + +/// The quoted string as `escape_json` writes it. +fn string_bytes(text: &str) -> u64 { + let body: u64 = text + .chars() + .map(|c| match c { + '"' | '\\' | '\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2, + control if u32::from(control) < 0x20 => 6, + other => other.len_utf8() as u64, + }) + .sum(); + 2 + body +} + +/// The number as a page sends it (JavaScript's form), then as `numeric` prints it. +fn number_bytes(number: &serde_json::Number) -> u64 { + let javascript = number + .as_f64() + .map_or_else(|| number.to_string(), js_number); + numeric_text_bytes(&javascript) +} + +/// Length of `numeric_out(numeric_in(text))` for a JSON number text: the value written in +/// plain digits, the scale of the text kept (digits after the point, less the exponent), a +/// sign only when the value is not zero. +pub fn numeric_text_bytes(text: &str) -> u64 { + let (negative, body) = text + .strip_prefix('-') + .map_or((false, text), |rest| (true, rest)); + let (mantissa, exponent) = body.split_once(['e', 'E']).unwrap_or((body, "0")); + let exponent: i64 = exponent.trim_start_matches('+').parse().unwrap_or(0); + let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let digits: Vec = integer.bytes().chain(fraction.bytes()).collect(); + let point = i64::try_from(integer.len()).unwrap_or(i64::MAX) + exponent; + let scale = (i64::try_from(fraction.len()).unwrap_or(i64::MAX) - exponent).max(0); + let integer_digits = integer_digit_count(&digits, point); + let zero = digits.iter().all(|&d| d == b'0'); + let sign = u64::from(negative && !zero); + let fraction_bytes = if scale > 0 { + 1 + scale.unsigned_abs() + } else { + 0 + }; + sign + integer_digits + fraction_bytes +} + +/// Digits before the point once leading zeros are dropped, at least one (`0.5` → `0`). +fn integer_digit_count(digits: &[u8], point: i64) -> u64 { + let Ok(point) = usize::try_from(point) else { + return 1; + }; + let shown = point.min(digits.len()); + match digits[..shown].iter().position(|&d| d != b'0') { + Some(first) => (point - first) as u64, + None => 1, + } +} + +#[cfg(test)] +mod tests { + use super::numeric_text_bytes; + + #[test] + fn numbers_take_their_plain_numeric_length() { + let cases = [ + ("0", 1), + ("-0", 1), + ("7", 1), + ("-12", 3), + ("0.5", 3), + ("0.001", 5), + ("123.456", 7), + ("1e+21", 22), + ("1e21", 22), + ("1.5e-7", 10), + ("1e-7", 9), + ("5e-324", 326), + ("1.7976931348623157e+308", 309), + ("-1.5e-7", 11), + ("100", 3), + ]; + for (text, length) in cases { + assert_eq!(numeric_text_bytes(text), length, "{text}"); + } + } +} diff --git a/crates/core/src/domain/sheet/verdict.rs b/crates/core/src/domain/sheet/verdict.rs new file mode 100644 index 00000000..1b4b1f23 --- /dev/null +++ b/crates/core/src/domain/sheet/verdict.rs @@ -0,0 +1,363 @@ +//! The server verdict of a submitted revision (contract §6.4, §6.5, §6.7, O15): computed by +//! the core from data read on the server side, in the worker's keyless child (V1-2.3), never +//! in a page. It is bound to the round (sheet, version, revision, review) and carries what +//! approval and publication rely on: the outcome and its closed codes, the fingerprint, every +//! drawing the views reference checked against its row, the issues, the caps, the +//! completeness counts, the review groups with their digests and the change list. +//! +//! Field names are the ones the SQL reads (`groups[{key, digest, coverable}]`, +//! `drawings[{asset_id, sha256}]`, `fingerprint`: `20261028110000_sheet_review_workflow.sql`). +//! The submission rules are the first five lines of §6.7; the marking, disclaimer, coverage +//! and separation rules belong to approval and publication, in SQL. A strict-parse refusal is +//! an integrity fault of the stored text (§6.5, owner decision 2026-10-29). + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +#[cfg(feature = "ts")] +use ts_rs::TS; + +use super::caps::CapsReport; +use super::fingerprint::{FingerprintError, document_fingerprint}; +use super::report::{SheetReport, referenced_asset_ids, sheet_report}; +use super::review::{Completeness, ElementChange, ReviewGroup, change_list}; +use super::schema::AnatomicalSheetDocument; +use super::size::document_text_bytes; +use super::validate::{SheetIssue, SheetIssueSeverity}; +use crate::anatomy::svg::read_svg; +use crate::domain::js::parse_json; + +/// The format of the verdict object, bumped with any change of its meaning. +pub const VERDICT_FORMAT: u32 = 1; + +/// The longest document text the core reads at all (four times the server cap): anything +/// longer is refused unread. +pub const MAX_DOCUMENT_TEXT_BYTES: usize = 8 * 1024 * 1024; + +/// The closed failure codes, in the order the first one is chosen for the round. +pub mod codes { + pub const DOCUMENT: &str = "verification.integrity.document"; + pub const BASE: &str = "verification.integrity.base"; + pub const RULES: &str = "verification.validation.rules"; + pub const NO_GEOMETRY: &str = "verification.validation.no_geometry"; + pub const CAPS: &str = "verification.validation.caps"; + pub const DRAWING_MISSING: &str = "verification.integrity.drawing_missing"; + pub const SIZE_MISMATCH: &str = "verification.integrity.size_mismatch"; + pub const OBJECT_CONFLICT: &str = "verification.integrity.object_conflict"; + pub const SVG_REJECTED: &str = "verification.integrity.svg_rejected"; + pub const SVG_REMOVAL: &str = "verification.integrity.svg_removal"; + pub const FINGERPRINT: &str = "verification.integrity.fingerprint"; +} + +/// The round a verdict answers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct VerdictBinding { + pub sheet_id: String, + pub version_id: String, + pub revision: u32, + pub review_id: String, +} + +/// One drawing row of the sheet, and the object's bytes when Storage has them. +#[derive(Debug, Clone, Copy)] +pub struct VerdictDrawing<'a> { + pub asset_id: &'a str, + pub sha256: &'a str, + pub byte_size: u64, + pub bytes: Option<&'a [u8]>, +} + +/// What the worker reads on the server side: the document at the round's revision and the +/// base document, as text, and the rows of the drawings the document references. +#[derive(Debug, Clone)] +pub struct VerdictInput<'a> { + pub binding: VerdictBinding, + pub document: &'a str, + pub base_document: Option<&'a str>, + pub drawings: Vec>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum VerdictOutcome { + Passed, + Failed, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(rename_all = "snake_case")] +pub enum DrawingResult { + Ok, + /// No row, or no object in Storage. + Missing, + /// The object's size is not the row's. + SizeMismatch, + /// The object's bytes do not hash to the row's sha256, its key (`object_conflict`, §9.3). + HashMismatch, + /// The reader refuses the drawing (reason in `detail`). + SvgRejected, + /// The reader would take something out of it (names in `detail`); never repaired. + SvgRemoval, +} + +/// One drawing the views reference, as the verdict found it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct DrawingCheck { + pub asset_id: String, + /// The row's sha256; absent when no row was given. + pub sha256: Option, + /// The row's byte size; absent when no row was given. + #[cfg_attr(feature = "ts", ts(type = "number | null"))] + pub byte_size: Option, + pub result: DrawingResult, + pub detail: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct Verdict { + pub format: u32, + pub outcome: VerdictOutcome, + /// The first failure, as the round records it. + pub failure_code: Option, + pub failures: Vec, + pub sheet_id: String, + pub version_id: String, + pub revision: u32, + pub review_id: String, + pub verified_with: String, + /// `sha256-rfc8785-validated-v1`; absent when the document has an integrity error. + pub fingerprint: Option, + pub drawings: Vec, + #[cfg_attr(feature = "ts", ts(type = "number"))] + pub document_bytes: u64, + pub issues: Vec, + pub caps: Option, + pub completeness: Option, + pub groups: Vec, + /// Against the base; absent when the version has none. + pub changes: Option>, +} + +/// The core that computed a verdict. +pub fn verified_with() -> String { + format!("faunosteo-core {}", crate::CORE_VERSION) +} + +/// The verdict of `input`. Pure: the same input gives the same verdict. +pub fn compute_verdict(input: &VerdictInput<'_>) -> Verdict { + let mut verdict = empty_verdict(&input.binding); + if let Err(code) = verify(input, &mut verdict) { + fail(&mut verdict, code); + } + verdict +} + +/// Fills `verdict` from the input; an `Err` is a failure that leaves nothing else to check +/// (the document or the base unreadable, a group without a digest). +fn verify(input: &VerdictInput<'_>, verdict: &mut Verdict) -> Result<(), &'static str> { + let document = read_document(input.document).ok_or(codes::DOCUMENT)?; + let base = input + .base_document + .map(|text| read_document(text).ok_or(codes::BASE)) + .transpose()?; + let drawings = check_drawings(&document.typed, &input.drawings); + let sizes: Vec = drawings.iter().map(|d| d.size).collect(); + let base_typed = base.as_ref().map(|b| &b.typed); + let report = sheet_report(&document.typed, document.bytes, &sizes, base_typed) + .map_err(|_| codes::FINGERPRINT)?; + for code in rule_failures(&report) + .into_iter() + .chain(drawing_failures(&drawings)) + { + fail(verdict, code); + } + match document_fingerprint(&document.typed) { + Ok(fingerprint) => verdict.fingerprint = Some(fingerprint), + Err(FingerprintError::Invalid(_)) => {} + Err(_) => fail(verdict, codes::FINGERPRINT), + } + verdict.changes = base_typed.map(|b| change_list(&document.typed, b)); + verdict.drawings = drawings.into_iter().map(|d| d.check).collect(); + record_report(verdict, report); + Ok(()) +} + +fn record_report(verdict: &mut Verdict, report: SheetReport) { + verdict.document_bytes = report.document_bytes; + verdict.issues = report.issues; + verdict.caps = Some(report.caps); + verdict.completeness = Some(report.completeness); + verdict.groups = report.groups; +} + +fn empty_verdict(binding: &VerdictBinding) -> Verdict { + Verdict { + format: VERDICT_FORMAT, + outcome: VerdictOutcome::Passed, + failure_code: None, + failures: Vec::new(), + sheet_id: binding.sheet_id.clone(), + version_id: binding.version_id.clone(), + revision: binding.revision, + review_id: binding.review_id.clone(), + verified_with: verified_with(), + fingerprint: None, + drawings: Vec::new(), + document_bytes: 0, + issues: Vec::new(), + caps: None, + completeness: None, + groups: Vec::new(), + changes: None, + } +} + +/// Records a failure: the outcome turns `failed`, the first code names the round. +fn fail(verdict: &mut Verdict, code: &str) { + verdict.outcome = VerdictOutcome::Failed; + if verdict.failure_code.is_none() { + verdict.failure_code = Some(code.to_owned()); + } + if !verdict.failures.iter().any(|c| c == code) { + verdict.failures.push(code.to_owned()); + } +} + +/// A document read strictly, with its server measure. +pub struct ReadDocument { + pub typed: AnatomicalSheetDocument, + pub bytes: u64, +} + +/// The strict reading of a stored text: bounded, JSON as `JSON.parse` reads it, the full +/// shape of the contract; `None` when any step refuses it. +pub fn read_document(text: &str) -> Option { + if text.len() > MAX_DOCUMENT_TEXT_BYTES || crate::ops::over_value_budget(text) { + return None; + } + let value = parse_json(text).ok()?; + let bytes = document_text_bytes(&value); + // From `&Value`, as every other reader of the document: the owned form would compile a + // second copy of the schema's reader into the browser module. + let typed = AnatomicalSheetDocument::deserialize(&value).ok()?; + Some(ReadDocument { typed, bytes }) +} + +/// The failures the report carries, in code order. +fn rule_failures(report: &SheetReport) -> Vec<&'static str> { + let errors = || { + report + .issues + .iter() + .filter(|i| i.severity == SheetIssueSeverity::Error) + }; + let mut out = Vec::new(); + if errors().any(|i| i.code != super::report::GEOMETRY_MISSING) { + out.push(codes::RULES); + } + if errors().any(|i| i.code == super::report::GEOMETRY_MISSING) { + out.push(codes::NO_GEOMETRY); + } + if !report.caps.exceeded.is_empty() { + out.push(codes::CAPS); + } + out +} + +struct CheckedDrawing { + check: DrawingCheck, + /// The size the caps count: the object's, else the row's. + size: u64, +} + +/// Every drawing the views reference, in view order, against its row and its bytes. +fn check_drawings( + document: &AnatomicalSheetDocument, + rows: &[VerdictDrawing<'_>], +) -> Vec { + let by_id: HashMap<&str, &VerdictDrawing<'_>> = rows.iter().map(|r| (r.asset_id, r)).collect(); + referenced_asset_ids(document) + .into_iter() + .map(|asset_id| match by_id.get(asset_id) { + None => CheckedDrawing { + check: drawing_check(asset_id, None, DrawingResult::Missing, None), + size: 0, + }, + Some(row) => { + let (result, detail) = check_bytes(row); + CheckedDrawing { + check: drawing_check(asset_id, Some(row), result, detail), + size: row.bytes.map_or(row.byte_size, |b| b.len() as u64), + } + } + }) + .collect() +} + +fn drawing_check( + asset_id: &str, + row: Option<&VerdictDrawing<'_>>, + result: DrawingResult, + detail: Option, +) -> DrawingCheck { + DrawingCheck { + asset_id: asset_id.to_owned(), + sha256: row.map(|r| r.sha256.to_owned()), + byte_size: row.map(|r| r.byte_size), + result, + detail, + } +} + +/// Size, then the hash of the bytes against the row (the object key), then the reader. +fn check_bytes(row: &VerdictDrawing<'_>) -> (DrawingResult, Option) { + let Some(bytes) = row.bytes else { + return (DrawingResult::Missing, None); + }; + if bytes.len() as u64 != row.byte_size { + return (DrawingResult::SizeMismatch, None); + } + if sha256_hex(bytes) != row.sha256 { + return (DrawingResult::HashMismatch, None); + } + let Ok(text) = std::str::from_utf8(bytes) else { + return (DrawingResult::SvgRejected, Some("malformed".to_owned())); + }; + match read_svg(text) { + Err(rejection) => ( + DrawingResult::SvgRejected, + Some(rejection.reason().to_owned()), + ), + Ok(read) if !read.removed.is_empty() => { + (DrawingResult::SvgRemoval, Some(read.removed.join(", "))) + } + Ok(_) => (DrawingResult::Ok, None), + } +} + +fn drawing_failures(drawings: &[CheckedDrawing]) -> Vec<&'static str> { + let order = [ + (DrawingResult::Missing, codes::DRAWING_MISSING), + (DrawingResult::SizeMismatch, codes::SIZE_MISMATCH), + (DrawingResult::HashMismatch, codes::OBJECT_CONFLICT), + (DrawingResult::SvgRejected, codes::SVG_REJECTED), + (DrawingResult::SvgRemoval, codes::SVG_REMOVAL), + ]; + order + .into_iter() + .filter(|(result, _)| drawings.iter().any(|d| d.check.result == *result)) + .map(|(_, code)| code) + .collect() +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} diff --git a/crates/core/src/facade.rs b/crates/core/src/facade.rs index 7f73cffd..070c7e27 100644 --- a/crates/core/src/facade.rs +++ b/crates/core/src/facade.rs @@ -8,6 +8,7 @@ use serde::de::DeserializeOwned; use serde_json::{Map, Value}; use crate::domain::js::{JsonReadError, parse_json}; +use crate::domain::sheet::preview::{PreviewDrawing, PreviewFailure, PreviewInput, PreviewSheet}; use crate::domain::sheet::{BundledSheetData, LoadError, LoadedSheet}; use crate::domain::{ReportZone, SheetRef}; use crate::json::{pretty_js_round_trip, to_js_compact}; @@ -57,6 +58,52 @@ pub fn load_sheet(bundle: &str) -> Result { }) } +/// Loads a stored version for preview (V1-2.2, contract §10): `input` is the +/// `PreviewInput` JSON, the drawings came in as bytes. The failure names a closed kind +/// (`invalid_document`, `drawing_missing`, `drawing_hash_mismatch`, `fingerprint_mismatch`, +/// `caps`), or `invalid_shape` / `invalid_json` / `lone_surrogate` for the input itself. +pub fn load_preview(input: &str, drawings: Vec) -> Result { + let input: PreviewInput = parse_input(input)?; + PreviewSheet::load(input, drawings).map_err(preview_failure) +} + +fn preview_failure(failure: PreviewFailure) -> Failure { + Failure::new(failure.kind(), failure.detail()) +} + +/// Runs the operation `op` on a previewed version (`preview.state`, `view.canvas`). +pub fn call_with_preview(preview: &PreviewSheet, op: &str, input: &str) -> String { + render(crate::ops::on_preview(preview, op, input).unwrap_or_else(|| Err(unknown(op)))) +} + +/// Replaces a previewed draft's document by the text an edit produced: `{"ok":true}` or a +/// closed refusal (`invalid_document`, `read_only`); the drawings are not read again. +pub fn replace_preview_document(preview: &mut PreviewSheet, text: &str) -> String { + render( + preview + .replace_document(text) + .map(|()| Value::Null) + .map_err(preview_failure), + ) +} + +/// Adds a drawing to a previewed draft: `{"ok":true}` or `drawing_hash_mismatch`, +/// `read_only`. +pub fn add_preview_drawing(preview: &mut PreviewSheet, drawing: PreviewDrawing) -> String { + render( + preview + .add_drawing(drawing) + .map(|()| Value::Null) + .map_err(preview_failure), + ) +} + +/// The cleaning answer for a file picked for upload (contract §9.2): always `ok`, the value +/// says clean, cleanable or rejected. +pub fn clean_svg(bytes: &[u8]) -> String { + render(to_value(&crate::anatomy::svg::clean::clean_svg(bytes))) +} + /// Runs the operation `op` that needs the session's sheet. pub fn call_with_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> String { render(crate::ops::on_sheet(sheet, op, input).unwrap_or_else(|| Err(unknown(op)))) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index a3dab857..db4513f9 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -16,7 +16,14 @@ use crate::domain::editor::{ use crate::domain::js::parse_json; use crate::domain::report::{LateralSide, Observation, Report, SheetRef, Vertebra}; use crate::domain::session::{self, ImportFailure, RestoreFailure}; -use crate::domain::sheet::{LoadedSheet, SheetIndexData, check_sheet_document}; +use crate::domain::sheet::edit::{Dependent, EditCommand, apply_edit, dependents}; +use crate::domain::sheet::keys::ElementKey; +use crate::domain::sheet::loaded::Drawing; +use crate::domain::sheet::preview::PreviewSheet; +use crate::domain::sheet::verdict::MAX_DOCUMENT_TEXT_BYTES; +use crate::domain::sheet::{ + AnatomicalSheetDocument, LoadedSheet, SheetIndexData, check_sheet_document, +}; use crate::facade::{Failure, parse_input, to_value}; use crate::pdf::json_js::{MAX_JSON_VALUES, prescan}; @@ -103,6 +110,8 @@ pub fn free(op: &str, input: &str) -> Option { "report.remove_observation" => report_remove(input), "report.move_observation" => report_move(input), "vertebra.select" => vertebra_select(input), + "sheet.edit" => sheet_edit(input), + "sheet.dependents" => sheet_dependents(input), _ => return None, }) } @@ -114,6 +123,63 @@ fn sheet_check(input: &str) -> Outcome { to_value(&check) } +#[derive(Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(deny_unknown_fields)] +pub struct SheetEditInput { + pub document: AnatomicalSheetDocument, + pub command: EditCommand, +} + +#[derive(serde::Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct SheetEditOutput { + pub document: AnatomicalSheetDocument, +} + +#[derive(Deserialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +#[serde(deny_unknown_fields)] +pub struct SheetDependentsInput { + pub document: AnatomicalSheetDocument, + pub key: ElementKey, +} + +#[derive(serde::Serialize)] +#[cfg_attr(feature = "ts", derive(TS), ts(export))] +pub struct SheetDependents { + pub dependents: Vec, +} + +/// A sheet input the core reads: the document's own bound with room for the command, and +/// the OD-3 value budget, before the parser allocates its tree. +fn sheet_input(input: &str) -> Result { + if input.len() > MAX_DOCUMENT_TEXT_BYTES + MAX_COMMAND_BYTES || over_value_budget(input) { + return Err(Failure::new( + "too_large", + "the input is over the size budget", + )); + } + parse_input(input) +} + +/// Room for a command beside the document (an inserted zone with its whole tree). +const MAX_COMMAND_BYTES: usize = 2 * 1024 * 1024; + +fn sheet_edit(input: &str) -> Outcome { + let input: SheetEditInput = sheet_input(input)?; + let document = apply_edit(&input.document, input.command) + .map_err(|error| Failure::new(error.kind(), ""))?; + to_value(&SheetEditOutput { document }) +} + +fn sheet_dependents(input: &str) -> Outcome { + let input: SheetDependentsInput = sheet_input(input)?; + to_value(&SheetDependents { + dependents: dependents(&input.document, &input.key), + }) +} + fn report_new(input: &str) -> Outcome { let input: NewReportInput = parse_input(input)?; let stamp = NewReportStamp { @@ -386,20 +452,31 @@ pub const MAX_COMPOSED_BYTES: usize = 4 * 1024 * 1024; fn view_canvas(sheet: &LoadedSheet, input: &str) -> Outcome { let input: CanvasViewInput = parse_input(input)?; - let document = &sheet.document; - if !document.views.iter().any(|v| v.id() == input.view_id) { - return Err(Failure::new("unknown_view", &input.view_id)); + canvas_of(&sheet.document, &input.view_id, |asset| { + sheet.drawing(asset) + }) +} + +/// The canvas of `view_id` on `document`, its drawings looked up by asset id: the one +/// composition of the report editor's sheet and of a previewed version. +fn canvas_of<'a>( + document: &AnatomicalSheetDocument, + view_id: &str, + drawing_of: impl Fn(&str) -> Option<&'a Drawing>, +) -> Outcome { + if !document.views.iter().any(|v| v.id() == view_id) { + return Err(Failure::new("unknown_view", view_id)); } - let asset_id = asset_id_of_view(document, &input.view_id) - .ok_or_else(|| Failure::new("no_asset", &input.view_id))?; - let drawing = match sheet.drawing(asset_id) { + let asset_id = + asset_id_of_view(document, view_id).ok_or_else(|| Failure::new("no_asset", view_id))?; + let drawing = match drawing_of(asset_id) { None => return Err(Failure::new("no_asset", asset_id)), Some(Err(reason)) => return Err(Failure::new("svg_rejected", reason)), Some(Ok(drawing)) => drawing, }; - let canvas = compose_canvas(document, &input.view_id, drawing).map_err(|e| match e { - ComposeError::UnknownView => Failure::new("unknown_view", &input.view_id), - ComposeError::InvalidCharacter => Failure::new("invalid_character", &input.view_id), + let canvas = compose_canvas(document, view_id, drawing).map_err(|e| match e { + ComposeError::UnknownView => Failure::new("unknown_view", view_id), + ComposeError::InvalidCharacter => Failure::new("invalid_character", view_id), })?; let svg = serialize(&canvas); if svg.len() > MAX_COMPOSED_BYTES { @@ -407,3 +484,25 @@ fn view_canvas(sheet: &LoadedSheet, input: &str) -> Outcome { } to_value(&CanvasView { svg }) } + +// --------------------------------------------------------------------------- +// Previewed versions (V1-2.2, contract §10) + +/// Runs an operation on a previewed version; `None` when `op` is not one of them. +pub fn on_preview(preview: &PreviewSheet, op: &str, input: &str) -> Option { + Some(match op { + "preview.state" => preview + .state() + .map_err(|_| Failure::new("internal", "a review group has no digest")) + .and_then(|state| to_value(&state)), + "view.canvas" => preview_canvas(preview, input), + _ => return None, + }) +} + +fn preview_canvas(preview: &PreviewSheet, input: &str) -> Outcome { + let input: CanvasViewInput = parse_input(input)?; + canvas_of(preview.document(), &input.view_id, |asset| { + preview.drawing(asset) + }) +} diff --git a/crates/core/tests/oracles/v1-2-2/size.json b/crates/core/tests/oracles/v1-2-2/size.json new file mode 100644 index 00000000..e24d13e1 --- /dev/null +++ b/crates/core/tests/oracles/v1-2-2/size.json @@ -0,0 +1,99 @@ +{ + "generator": "crates/core/tests/oracles/v1-2-2/size.mjs", + "postgres": "PostgreSQL 17.5 on aarch64-unknown-linux-gnu, compiled by emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.74 (1092ec30a3fb1d46b1782ff1b4db5094d3d06ae5), 32-bit", + "vectors": [ + { + "name": "zero", + "text": "0", + "bytes": 1 + }, + { + "name": "negative_zero", + "text": "0", + "bytes": 1 + }, + { + "name": "integers", + "text": "[1,-12,100,9007199254740992,123456789012345680000]", + "bytes": 54 + }, + { + "name": "fractions", + "text": "[0.5,0.1,0.001,123.456,0.3333333333333333,-0.3333333333333333,0.000001]", + "bytes": 77 + }, + { + "name": "exponents", + "text": "[1e-7,1.5e-7,-1.5e-7,2.5e-10,1e+21,1.5e+21,1e+300,5e-324]", + "bytes": 730 + }, + { + "name": "extremes", + "text": "[1.7976931348623157e+308,5e-324,-1.7976931348623157e+308]", + "bytes": 951 + }, + { + "name": "literals", + "text": "[true,false,null]", + "bytes": 19 + }, + { + "name": "strings", + "text": "[\"\",\"a\",\"é\",\"€\",\"𝄞\",\"\\\"\",\"\\\\\",\"/\",\"