feat(domain): V1-2.2 document measure, review groups, verdict, preview, edits

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.
This commit is contained in:
bchanot committed 2026-10-29 13:14:21 +01:00
1 parent ac71c5b662
commit 64a43840ce
21 files changed
+5204 -17

No files matched your search

@@ -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));
+167
View File
@@ -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<CapName>,
}
/// 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<CapName> {
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<CapName> = 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)
}
File diff suppressed because it is too large. Load diff
+7 -4
View File
@@ -44,11 +44,11 @@ pub struct SheetIndexData {
pub node_keys: Vec<String>,
}
fn sorted(positions: &HashMap<String, usize>) -> BTreeMap<String, usize> {
pub(crate) fn sorted(positions: &HashMap<String, usize>) -> BTreeMap<String, usize> {
positions.iter().map(|(id, &p)| (id.clone(), p)).collect()
}
fn names(
pub(crate) fn names(
indexed: IndexedDocument<'_>,
by_id: &HashMap<String, usize>,
) -> BTreeMap<String, LocalizedText> {
@@ -61,7 +61,7 @@ fn names(
.collect()
}
fn spine_ids(indexed: IndexedDocument<'_>) -> Vec<String> {
pub(crate) fn spine_ids(indexed: IndexedDocument<'_>) -> Vec<String> {
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<String, usize>) -> Vec<String> {
pub(crate) fn node_keys(
indexed: IndexedDocument<'_>,
by_id: &HashMap<String, usize>,
) -> Vec<String> {
let mut out = Vec::new();
for (position, zone) in indexed.document.finding_zones.iter().enumerate() {
if by_id.get(&zone.id) != Some(&position) {
+155
View File
@@ -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 (`<zoneId>/<categoryId>/<nodeId>…`), 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<String>,
},
}
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<String> {
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<Marked> {
let mut out: Vec<Marked> = 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<Marked>) {
for category in &zone.categories {
push_category(zone, category, out);
}
}
fn push_category(zone: &FindingZone, category: &FindingCategory, out: &mut Vec<Marked>) {
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<String>, out: &mut Vec<Marked>) {
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();
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub struct LoadedSheet {
/// drawing (refused, never repaired: LRN-055).
pub type Drawing = Result<Element, String>;
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(", "))),
+8
View File
@@ -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};
+327
View File
@@ -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<String>,
}
/// 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<u8>,
}
/// 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<CapName>),
/// 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::<Vec<_>>()
.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<String>,
assets: HashMap<String, Asset>,
/// Each drawing read once, by sha256.
drawings: HashMap<String, Drawing>,
reads: usize,
}
impl PreviewSheet {
pub fn load(input: PreviewInput, given: Vec<PreviewDrawing>) -> Result<Self, PreviewFailure> {
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<u64> {
referenced_asset_ids(&self.document)
.into_iter()
.filter_map(|id| self.assets.get(id).map(|a| a.bytes))
.collect()
}
pub fn state(&self) -> Result<PreviewState, DigestError> {
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<PreviewDrawingState> {
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<String>,
}
/// 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<String, usize>,
pub annotation_by_id: BTreeMap<String, usize>,
pub finding_zone_by_id: BTreeMap<String, usize>,
pub names: BTreeMap<String, LocalizedText>,
pub spine_ids: Vec<String>,
pub node_keys: Vec<String>,
}
fn preview_index(document: &AnatomicalSheetDocument) -> Option<PreviewIndex> {
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<String>,
pub report: SheetReport,
pub drawings: Vec<PreviewDrawingState>,
pub index: Option<PreviewIndex>,
/// The document as read (defaults filled in).
pub document: AnatomicalSheetDocument,
}
+81
View File
@@ -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<SheetIssue>,
pub caps: CapsReport,
pub completeness: Completeness,
pub groups: Vec<ReviewGroup>,
}
/// 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<SheetReport, DigestError> {
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<SheetIssue> {
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
}
+432
View File
@@ -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:<id>` (the view
//! and the annotations drawn in it, document order), `zone:<id>` (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": <key>, …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<Vec<ReviewGroup>, 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<String> {
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<Item = &'a str>) -> impl Iterator<Item = &'a str> {
let mut seen = std::collections::HashSet::new();
ids.filter(move |id| seen.insert(*id))
}
fn group(key: &str, content: Value, marked: &[Marked]) -> Result<ReviewGroup, DigestError> {
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<ReviewGroup, DigestError> {
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<String, DigestError> {
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<Value> = 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<Value> {
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<Item = &'a Value> {
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<ReviewStatus>,
pub status_after: Option<ReviewStatus>,
}
/// 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<ReviewStatus>,
}
/// 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<ElementChange> {
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<ElementChange> = 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<ElementChange> {
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<ReviewStatus>,
status_after: Option<ReviewStatus>,
) -> 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<Entry>) -> Vec<Entry> {
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<Entry> {
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<Entry> {
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<Entry>) {
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<String>, 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<String>, out: &mut Vec<Entry>) {
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<T: Serialize>(item: &T) -> Value {
serde_json::to_value(item).unwrap_or(Value::Null)
}
+133
View File
@@ -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<u8> = 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}");
}
}
}
+363
View File
@@ -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<VerdictDrawing<'a>>,
}
#[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<String>,
/// The row's byte size; absent when no row was given.
#[cfg_attr(feature = "ts", ts(type = "number | null"))]
pub byte_size: Option<u64>,
pub result: DrawingResult,
pub detail: Option<String>,
}
#[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<String>,
pub failures: Vec<String>,
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<String>,
pub drawings: Vec<DrawingCheck>,
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub document_bytes: u64,
pub issues: Vec<SheetIssue>,
pub caps: Option<CapsReport>,
pub completeness: Option<Completeness>,
pub groups: Vec<ReviewGroup>,
/// Against the base; absent when the version has none.
pub changes: Option<Vec<ElementChange>>,
}
/// 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<u64> = 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<ReadDocument> {
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<CheckedDrawing> {
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<String>,
) -> 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<String>) {
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()
}
+47
View File
@@ -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<LoadedSheet, Failure> {
})
}
/// 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<PreviewDrawing>) -> Result<PreviewSheet, Failure> {
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))))
+109 -10
View File
@@ -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<Outcome> {
"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<Dependent>,
}
/// 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<T: serde::de::DeserializeOwned>(input: &str) -> Result<T, Failure> {
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<Outcome> {
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)
})
}
@@ -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\",\"é\",\"€\",\"𝄞\",\"\\\"\",\"\\\\\",\"/\",\"<script>\",\"Hanche « gauche »\"]",
"bytes": 82
},
{
"name": "escapes",
"text": "[\"\\b\\f\\n\\r\\t\",\"\\u0001\\u001f\",\"\",\"

\",\"a\\\"b\\\\c\\nd\"]",
"bytes": 59
},
{
"name": "empty_containers",
"text": "[[],{},[[]],[{}],{\"a\":{}}]",
"bytes": 31
},
{
"name": "keys",
"text": "{\"é\":\"x\",\"𝄞\":1,\"a b\":[],\"\\\"\":\"\\\\\",\"\\n\":0}",
"bytes": 54
},
{
"name": "nested_arrays",
"text": "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]",
"bytes": 122
},
{
"name": "dense",
"text": "[{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"a\":1},{\"Line truncated
"bytes": 10000
},
{
"name": "pgtap_017_exponents",
"text": "{\"pad\":[1e-7,1e+21]}",
"bytes": 44
},
{
"name": "mixed",
"text": "{\"schema_version\":2,\"name\":{\"fr\":\"Cheval\",\"en\":\"Horse\"},\"views\":[{\"id\":\"main\",\"view_box\":{\"min_x\":-0.5,\"min_y\":1e-7,\"width\":1e+21,\"height\":2}}]}",
"bytes": 184
},
{
"name": "repeated_key",
"text": "{\"a\":1,\"b\":2,\"a\":22}",
"bytes": 17
},
{
"name": "whitespace",
"text": "{ \"a\" : [ 1 , 2 ] ,\n \"b\" : { } }",
"bytes": 22
}
],
"pgtap_017_base": {
"text": "{\"pad\": \"\", \"name\": {\"en\": \"R horse\", \"fr\": \"Cheval R\"}, \"views\": [{\"id\": \"main\", \"kind\": \"main\", \"name\": {\"en\": \"V\", \"fr\": \"V\"}, \"view_box\": null, \"svg_asset_id\": \"00000000-0000-4000-8000-000000000001\"}], \"categories\": [{\"id\": \"c\", \"name\": {\"en\": \"C\", \"fr\": \"C\"}, \"color\": null}], \"references\": [], \"species_id\": \"equine\", \"annotations\": [{\"id\": \"a1\", \"kind\": \"point\", \"name\": {\"en\": \"P\", \"fr\": \"P\"}, \"view_id\": \"main\", \"geometry\": null, \"laterality\": \"unpaired\", \"category_id\": \"c\", \"review_status\": \"reviewed\", \"finding_zone_id\": \"z1\", \"vertebral_region_code\": null}], \"attribution\": {\"notes\": null, \"authors\": [\"F\"], \"license\": null}, \"description\": {\"en\": \"d\", \"fr\": \"d\"}, \"finding_zones\": [{\"id\": \"z1\", \"name\": {\"en\": \"Z\", \"fr\": \"Z\"}, \"categories\": [{\"id\": \"cat\", \"kind\": \"dysfunction\", \"name\": {\"en\": \"D\", \"fr\": \"D\"}, \"children\": [{\"id\": \"n1\", \"name\": {\"en\": \"N\", \"fr\": \"N\"}, \"review_status\": \"reviewed\"}], \"review_status\": \"reviewed\"}]}], \"schema_version\": 2, \"scope_disclaimer\": {\"en\": \"x\", \"fr\": \"x\"}, \"vertebral_config\": {\"regions\": []}}",
"bytes": 1048
},
"seed": {
"file": "supabase/seed/anatomical-sheets/equine/draft/document.json",
"bytes": 184105
}
}
+92
View File
@@ -0,0 +1,92 @@
// V1-2.2 size oracle: PostgreSQL measures each text the way the save RPCs and the table CHECK
// do, `octet_length(text::jsonb::text)` (contract §12.2), and `size.json` freezes the answers
// the core's `document_text_bytes` must reproduce (`crates/core/tests/sheet_size.rs`).
//
// PostgreSQL is PGlite (PostgreSQL 17 compiled to WebAssembly, the Dockerless pgTAP runner of
// packages/supabase). Texts are written by JSON.stringify, as a page sends them, except the
// repeated-key case and the seed file, which are read as they stand.
//
// Run from the repository root: node crates/core/tests/oracles/v1-2-2/size.mjs
import { readFileSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
const root = new URL('../../../../../', import.meta.url)
const require = createRequire(new URL('packages/supabase/package.json', root))
const { PGlite } = await import(require.resolve('@electric-sql/pglite'))
const SEED = 'supabase/seed/anatomical-sheets/equine/draft/document.json'
const nested = (depth) => {
let value = []
for (let i = 0; i < depth; i += 1) value = [value]
return value
}
const values = {
zero: 0,
negative_zero: -0,
integers: [1, -12, 100, 9007199254740993, 123456789012345680000],
fractions: [0.5, 0.1, 0.001, 123.456, 1 / 3, -1 / 3, 1e-6],
exponents: [1e-7, 1.5e-7, -1.5e-7, 2.5e-10, 1e21, 1.5e21, 1e300, 5e-324],
extremes: [Number.MAX_VALUE, Number.MIN_VALUE, -Number.MAX_VALUE],
literals: [true, false, null],
strings: ['', 'a', 'é', '€', '𝄞', '"', '\\', '/', '<script>', 'Hanche « gauche »'],
escapes: ['\b\f\n\r\t', '\u0001\u001f', '\u007f', '

', 'a"b\\c\nd'],
empty_containers: [[], {}, [[]], [{}], { a: {} }],
keys: { é: 'x', '𝄞': 1, 'a b': [], '"': '\\', '\n': 0 },
nested_arrays: nested(60),
dense: Array.from({ length: 1000 }, () => ({ a: 1 })),
pgtap_017_exponents: { pad: [1e-7, 1e21] },
mixed: { schema_version: 2, name: { fr: 'Cheval', en: 'Horse' }, views: [{ id: 'main', view_box: { min_x: -0.5, min_y: 1e-7, width: 1e21, height: 2 } }] },
}
const texts = Object.entries(values).map(([name, value]) => ({ name, text: JSON.stringify(value) }))
texts.push({ name: 'repeated_key', text: '{"a":1,"b":2,"a":22}' })
texts.push({ name: 'whitespace', text: '{ "a" : [ 1 , 2 ] ,\n "b" : { } }' })
const db = new PGlite()
const measure = async (text) =>
(await db.query('select octet_length($1::jsonb::text) as n', [text])).rows[0].n
const vectors = []
for (const { name, text } of texts) vectors.push({ name, text, bytes: await measure(text) })
// The pgTAP 017 base document (`pg_temp.doc(asset, 'reviewed')`) with an empty pad: the
// `sized` fixtures pad it to cap − 1, cap and cap + 1 bytes.
await db.exec(`create function doc(p_asset uuid, st text) returns jsonb language sql as $$
select jsonb_build_object('schema_version', 2, 'species_id', 'equine',
'name', jsonb_build_object('fr', 'Cheval R', 'en', 'R horse'),
'description', jsonb_build_object('fr', 'd', 'en', 'd'),
'scope_disclaimer', jsonb_build_object('fr', 'x', 'en', 'x'),
'attribution', jsonb_build_object('authors', jsonb_build_array('F'), 'license', null, 'notes', null),
'vertebral_config', jsonb_build_object('regions', '[]'::jsonb), 'references', '[]'::jsonb,
'categories', jsonb_build_array(jsonb_build_object('id', 'c', 'name', jsonb_build_object('fr', 'C', 'en', 'C'), 'color', null)),
'views', jsonb_build_array(jsonb_build_object('id', 'main', 'kind', 'main', 'name', jsonb_build_object('fr', 'V', 'en', 'V'),
'svg_asset_id', p_asset, 'view_box', null)),
'annotations', jsonb_build_array(jsonb_build_object('id', 'a1', 'kind', 'point', 'view_id', 'main', 'category_id', 'c',
'laterality', 'unpaired', 'geometry', null, 'review_status', st, 'name', jsonb_build_object('fr', 'P', 'en', 'P'),
'finding_zone_id', 'z1', 'vertebral_region_code', null)),
'finding_zones', (select jsonb_agg(jsonb_build_object('id', 'z' || i, 'name', jsonb_build_object('fr', 'Z', 'en', 'Z'),
'categories', jsonb_build_array(jsonb_build_object('id', 'cat', 'kind', 'dysfunction', 'name', jsonb_build_object('fr', 'D', 'en', 'D'),
'review_status', st, 'children', jsonb_build_array(jsonb_build_object('id', 'n1', 'name', jsonb_build_object('fr', 'N', 'en', 'N'),
'review_status', st)))))) from generate_series(1, 1) i));
$$`)
const base = (
await db.query(
`select (doc('00000000-0000-4000-8000-000000000001', 'reviewed') || '{"pad": ""}'::jsonb)::text as t`,
)
).rows[0].t
const pgtap017 = { text: base, bytes: await measure(base) }
const seed = readFileSync(new URL(SEED, root), 'utf8')
const version = (await db.query('select version() as v')).rows[0].v
const oracle = {
generator: 'crates/core/tests/oracles/v1-2-2/size.mjs',
postgres: version,
vectors,
pgtap_017_base: pgtap017,
seed: { file: SEED, bytes: await measure(seed) },
}
writeFileSync(new URL('size.json', import.meta.url), `${JSON.stringify(oracle, null, 2)}\n`)
console.log(`${vectors.length} vectors, base ${pgtap017.bytes} B, seed ${oracle.seed.bytes} B, ${version}`)
+797
View File
@@ -0,0 +1,797 @@
//! V1-2.2: the editor's commands (contract §6.6, §8.1). The status rules, case by case; the
//! refusals; `dependents`; the facade; and a property test over random command sequences:
//! every output reads back strictly, existing keys survive unless removed, an edited or new
//! element is `to_confirm`, nothing ever becomes `inherited`.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashMap;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::domain::sheet::edit::{
EditCommand, EditError, Relation, apply_edit, dependents,
};
use faunosteo_core::domain::sheet::keys::{ElementKey, marked_elements};
use faunosteo_core::domain::sheet::schema::ReviewStatus;
use faunosteo_core::facade::call;
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft/document.json";
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// Two views (a detail crop of the main one), a point in each, a trigger, a zone with a
/// category and a two-level node, one reference, one region; everything `reviewed`.
fn small() -> AnatomicalSheetDocument {
serde_json::from_value(json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": {},
"attribution": { "authors": [], "license": null, "notes": null },
"vertebral_config": { "regions": [{ "code": "C", "name": name("Cervicales"), "count": 7 }] },
"references": [{ "id": "r1", "type": "book", "citation": "Atlas" }],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [
{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": "11111111-2222-4333-8444-555555555555", "view_box": null },
{ "id": "head", "kind": "detail", "name": name("Tête"), "svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": 4, "height": 4 }, "parent_view_id": "main" }
],
"annotations": [
{ "id": "a1", "kind": "point", "view_id": "main", "category_id": "c", "laterality": "left",
"geometry": { "type": "circle", "cx": 1, "cy": 1, "r": 1 }, "review_status": "reviewed",
"name": name("P1"), "finding_zone_id": "z1", "vertebral_region_code": "C" },
{ "id": "a2", "kind": "point", "view_id": "head", "category_id": "c", "laterality": "unpaired",
"geometry": { "type": "circle", "cx": 2, "cy": 2, "r": 1 }, "review_status": "reviewed",
"name": name("P2"), "finding_zone_id": "z1", "vertebral_region_code": null },
{ "id": "t1", "kind": "detail_trigger", "view_id": "main", "category_id": "c", "laterality": "unpaired",
"geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] }, "review_status": "reviewed",
"name": null, "opens_view_id": "head" }
],
"finding_zones": [{ "id": "z1", "name": name("Z"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("D"), "reference_ids": ["r1"], "review_status": "reviewed",
"children": [{ "id": "n1", "name": name("N1"), "review_status": "reviewed",
"children": [{ "id": "n2", "name": name("N2"), "review_status": "reviewed" }] }] }] }]
}))
.unwrap()
}
fn command(value: Value) -> EditCommand {
serde_json::from_value(value).unwrap()
}
fn edit(doc: &AnatomicalSheetDocument, value: Value) -> AnatomicalSheetDocument {
apply_edit(doc, command(value)).unwrap()
}
fn refused(doc: &AnatomicalSheetDocument, value: Value) -> EditError {
apply_edit(doc, command(value)).unwrap_err()
}
fn statuses(doc: &AnatomicalSheetDocument) -> HashMap<ElementKey, ReviewStatus> {
marked_elements(doc)
.into_iter()
.map(|m| (m.key, m.status))
.collect()
}
fn status(doc: &AnatomicalSheetDocument, key: Value) -> ReviewStatus {
let key: ElementKey = serde_json::from_value(key).unwrap();
statuses(doc)[&key]
}
fn finding(path: &[&str]) -> Value {
json!({ "kind": "finding", "zone_id": "z1", "path": path })
}
fn annotation(id: &str) -> Value {
json!({ "kind": "annotation", "id": id })
}
#[test]
fn inserted_elements_start_to_confirm_with_their_subtree() {
let doc = small();
let point = json!({ "id": "a3", "kind": "point", "view_id": "main", "category_id": "c", "laterality": "right",
"geometry": null, "review_status": "reviewed", "name": name("P3"), "finding_zone_id": null, "vertebral_region_code": null });
let next = edit(
&doc,
json!({ "op": "insert", "element": { "kind": "annotation", "value": point }, "position": 0 }),
);
assert_eq!(next.annotations[0].id(), "a3");
assert_eq!(
status(&next, annotation("a3")),
ReviewStatus::ToConfirm,
"a page's marking is ignored"
);
let subtree = json!({ "id": "n3", "name": name("N3"), "review_status": "reviewed",
"children": [{ "id": "n4", "name": name("N4"), "review_status": "inherited" }] });
let next = edit(
&doc,
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": subtree } }),
);
assert_eq!(
status(&next, finding(&["cat", "n3"])),
ReviewStatus::ToConfirm
);
assert_eq!(
status(&next, finding(&["cat", "n3", "n4"])),
ReviewStatus::ToConfirm
);
let zone = json!({ "id": "z2", "name": name("Z2"), "categories": [{ "id": "k", "kind": "custom", "name": name("K"),
"review_status": "reviewed", "children": [] }] });
let next = edit(
&doc,
json!({ "op": "insert", "element": { "kind": "zone", "value": zone } }),
);
let key = json!({ "kind": "finding", "zone_id": "z2", "path": ["k"] });
assert_eq!(status(&next, key), ReviewStatus::ToConfirm);
}
#[test]
fn a_content_change_reconfirms_an_identical_update_does_not() {
let doc = small();
let mut same = serde_json::to_value(&doc.annotations[0]).unwrap();
let unchanged = edit(
&doc,
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": same.clone() } }),
);
assert_eq!(unchanged, doc);
same["review_status"] = json!("to_confirm");
let ignored = edit(
&doc,
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": same.clone() } }),
);
assert_eq!(
status(&ignored, annotation("a1")),
ReviewStatus::Reviewed,
"update never sets a marking"
);
for (field, value) in [
("name", name("Autre")),
("laterality", json!("right")),
("color", json!("#112233")),
("finding_zone_id", Value::Null),
("view_id", json!("head")),
(
"geometry",
json!({ "type": "circle", "cx": 1.5, "cy": 1, "r": 1 }),
),
] {
let mut changed = serde_json::to_value(&doc.annotations[0]).unwrap();
changed[field] = value;
let next = edit(
&doc,
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": changed } }),
);
assert_eq!(
status(&next, annotation("a1")),
ReviewStatus::ToConfirm,
"{field}"
);
assert_eq!(status(&next, annotation("a2")), ReviewStatus::Reviewed);
}
let node = json!({ "id": "n1", "name": name("N1 bis"), "requires_vet_referral": false, "review_status": "reviewed" });
let next = edit(
&doc,
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": node } }),
);
assert_eq!(
status(&next, finding(&["cat", "n1"])),
ReviewStatus::ToConfirm
);
assert_eq!(
status(&next, finding(&["cat", "n1", "n2"])),
ReviewStatus::Reviewed,
"children untouched"
);
assert_eq!(
next.finding_zones[0].categories[0].children[0]
.children
.len(),
1,
"children kept"
);
let cited =
json!({ "id": "n1", "name": name("N1"), "reference_ids": [], "review_status": "reviewed" });
let next = edit(
&doc,
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": cited } }),
);
assert_eq!(
status(&next, finding(&["cat", "n1"])),
ReviewStatus::Reviewed,
"same content"
);
let flagged = json!({ "id": "n1", "name": name("N1"), "requires_vet_referral": true });
let next = edit(
&doc,
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": flagged } }),
);
assert_eq!(
status(&next, finding(&["cat", "n1"])),
ReviewStatus::ToConfirm
);
let category = json!({ "id": "cat", "kind": "anamnesis", "name": name("D"), "reference_ids": ["r1"], "children": [] });
let next = edit(
&doc,
json!({ "op": "update", "key": finding(&["cat"]), "element": { "kind": "finding_category", "value": category } }),
);
assert_eq!(status(&next, finding(&["cat"])), ReviewStatus::ToConfirm);
assert_eq!(next.finding_zones[0].categories[0].children.len(), 1);
}
#[test]
fn shared_elements_and_reorders_keep_the_markings() {
let doc = small();
let before = statuses(&doc);
let texts = json!({ "name": name("Chien domestique"), "description": { "fr": "d" }, "scope_disclaimer": { "fr": "x", "en": "x" },
"attribution": { "authors": ["B"], "license": null, "notes": null } });
let reference = json!({ "id": "r1", "type": "journal", "citation": "Revue" });
let region = json!({ "code": "C", "name": name("Cou"), "count": 7, "count_range": { "min": 6, "max": 8 } });
let category = json!({ "id": "c", "name": name("Catégorie"), "color": "#aa0000" });
for command in [
json!({ "op": "update", "key": { "kind": "sheet" }, "element": { "kind": "sheet", "value": texts } }),
json!({ "op": "update", "key": { "kind": "reference", "id": "r1" }, "element": { "kind": "reference", "value": reference } }),
json!({ "op": "update", "key": { "kind": "region", "code": "C" }, "element": { "kind": "region", "value": region } }),
json!({ "op": "update", "key": { "kind": "category", "id": "c" }, "element": { "kind": "category", "value": category } }),
json!({ "op": "move", "key": annotation("t1"), "position": 0 }),
json!({ "op": "move", "key": { "kind": "view", "id": "head" }, "position": 0 }),
] {
assert_eq!(statuses(&edit(&doc, command.clone())), before, "{command}");
}
let moved = edit(
&doc,
json!({ "op": "move", "key": annotation("t1"), "position": 0 }),
);
assert_eq!(moved.annotations[0].id(), "t1");
}
#[test]
fn a_redrawn_view_reconfirms_its_annotations_and_its_crops() {
let doc = small();
let mut main = serde_json::to_value(&doc.views[0]).unwrap();
main["svg_asset_id"] = json!("11111111-2222-4333-8444-000000000009");
let next = edit(
&doc,
json!({ "op": "update", "key": { "kind": "view", "id": "main" }, "element": { "kind": "view", "value": main } }),
);
assert_eq!(status(&next, annotation("a1")), ReviewStatus::ToConfirm);
assert_eq!(status(&next, annotation("t1")), ReviewStatus::ToConfirm);
assert_eq!(
status(&next, annotation("a2")),
ReviewStatus::ToConfirm,
"head crops main: its drawing changed too"
);
let mut head = serde_json::to_value(&doc.views[1]).unwrap();
head["view_box"]["width"] = json!(5);
let next = edit(
&doc,
json!({ "op": "update", "key": { "kind": "view", "id": "head" }, "element": { "kind": "view", "value": head } }),
);
assert_eq!(status(&next, annotation("a2")), ReviewStatus::ToConfirm);
assert_eq!(status(&next, annotation("a1")), ReviewStatus::Reviewed);
let mut renamed = serde_json::to_value(&doc.views[1]).unwrap();
renamed["name"] = name("Crâne");
let next = edit(
&doc,
json!({ "op": "update", "key": { "kind": "view", "id": "head" }, "element": { "kind": "view", "value": renamed } }),
);
assert_eq!(
status(&next, annotation("a2")),
ReviewStatus::Reviewed,
"a rename draws nothing new"
);
}
#[test]
fn markings_are_set_one_element_category_or_zone_at_a_time() {
let doc = small();
let next = edit(
&doc,
json!({ "op": "set_status", "key": finding(&["cat", "n1"]), "status": "to_confirm" }),
);
assert_eq!(
status(&next, finding(&["cat", "n1"])),
ReviewStatus::ToConfirm
);
assert_eq!(
status(&next, finding(&["cat", "n1", "n2"])),
ReviewStatus::Reviewed
);
let next = edit(
&next,
json!({ "op": "set_status", "key": finding(&["cat", "n1"]), "status": "reviewed" }),
);
assert_eq!(statuses(&next), statuses(&doc));
let inherited: Result<EditCommand, _> = serde_json::from_value(
json!({ "op": "set_status", "key": annotation("a1"), "status": "inherited" }),
);
assert!(inherited.is_err(), "no command assigns inherited");
let all_to_confirm = edit(
&doc,
json!({ "op": "set_status", "key": finding(&["cat"]), "status": "to_confirm" }),
);
let all_to_confirm = edit(
&all_to_confirm,
json!({ "op": "set_status", "key": finding(&["cat", "n1", "n2"]), "status": "to_confirm" }),
);
let marked = edit(
&all_to_confirm,
json!({ "op": "mark_reviewed", "key": finding(&["cat"]) }),
);
assert_eq!(status(&marked, finding(&["cat"])), ReviewStatus::Reviewed);
assert_eq!(
status(&marked, finding(&["cat", "n1", "n2"])),
ReviewStatus::Reviewed
);
let zone = edit(
&all_to_confirm,
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": "z1" } }),
);
assert_eq!(statuses(&zone), statuses(&doc));
for key in [
finding(&["cat", "n1"]),
annotation("a1"),
json!({ "kind": "view", "id": "main" }),
json!({ "kind": "sheet" }),
] {
assert_eq!(
refused(&doc, json!({ "op": "mark_reviewed", "key": key })),
EditError::InvalidTarget
);
}
assert_eq!(
refused(
&doc,
json!({ "op": "set_status", "key": { "kind": "view", "id": "main" }, "status": "reviewed" })
),
EditError::InvalidTarget
);
}
#[test]
fn a_removal_takes_the_descendants_and_leaves_references_to_the_panel() {
let doc = small();
let next = edit(
&doc,
json!({ "op": "remove", "key": finding(&["cat", "n1"]) }),
);
assert!(next.finding_zones[0].categories[0].children.is_empty());
let next = edit(
&doc,
json!({ "op": "remove", "key": { "kind": "view", "id": "head" } }),
);
assert_eq!(next.views.len(), 1);
assert_eq!(next.annotations.len(), 3, "a2 and t1 stay, dangling");
let issues = faunosteo_core::domain::sheet::validate_sheet_document(&next);
assert!(issues.iter().any(|i| i.code == "annotation.view.missing"));
let next = edit(
&doc,
json!({ "op": "remove", "key": { "kind": "zone", "id": "z1" } }),
);
assert!(next.finding_zones.is_empty());
}
#[test]
fn ambiguous_unknown_or_out_of_range_targets_are_refused() {
let doc = small();
let copy = serde_json::to_value(&doc.annotations[0]).unwrap();
let cases = [
(
json!({ "op": "insert", "element": { "kind": "annotation", "value": copy.clone() } }),
EditError::DuplicateKey,
),
(
json!({ "op": "insert", "element": { "kind": "annotation", "value": copy.clone() }, "position": 9 }),
EditError::DuplicateKey,
),
(
json!({ "op": "remove", "key": annotation("zz") }),
EditError::UnknownKey,
),
(
json!({ "op": "remove", "key": finding(&["cat", "zz"]) }),
EditError::UnknownKey,
),
(
json!({ "op": "remove", "key": finding(&[]) }),
EditError::UnknownKey,
),
(
json!({ "op": "remove", "key": { "kind": "sheet" } }),
EditError::InvalidTarget,
),
(
json!({ "op": "move", "key": annotation("a1"), "position": 3 }),
EditError::InvalidPosition,
),
(
json!({ "op": "update", "key": annotation("a2"), "element": { "kind": "annotation", "value": copy.clone() } }),
EditError::IdChanged,
),
(
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "zone", "value": { "id": "a1", "name": name("x"), "categories": [] } } }),
EditError::InvalidTarget,
),
(
json!({ "op": "insert", "parent": { "kind": "zone", "id": "z1" }, "element": { "kind": "finding_node", "value": { "id": "x", "name": name("x") } } }),
EditError::InvalidTarget,
),
(
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": { "id": "n1", "name": name("x") } } }),
EditError::DuplicateKey,
),
(
json!({ "op": "insert", "parent": { "kind": "zone", "id": "z9" }, "element": { "kind": "finding_category", "value": { "id": "k", "kind": "custom", "name": name("x"), "children": [] } } }),
EditError::UnknownKey,
),
(
json!({ "op": "insert", "element": { "kind": "sheet", "value": { "name": name("x"), "description": {}, "scope_disclaimer": {}, "attribution": { "authors": [], "license": null, "notes": null } } } }),
EditError::InvalidTarget,
),
];
for (command, error) in cases {
assert_eq!(refused(&doc, command.clone()), error, "{command}");
}
let twins = json!({ "id": "n9", "name": name("x"), "children": [{ "id": "k", "name": name("k") }, { "id": "k", "name": name("k") }] });
assert_eq!(
refused(
&doc,
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": twins } })
),
EditError::DuplicateKey
);
}
#[test]
fn findings_stop_at_eight_levels() {
let doc = small();
// n2 sits at level 3 (category 1, n1 2, n2 3): five more levels fit, six do not.
let nested = |levels: usize| {
let mut node = json!({ "id": format!("d{levels}"), "name": name("d") });
for level in (1..levels).rev() {
node = json!({ "id": format!("d{level}"), "name": name("d"), "children": [node] });
}
node
};
let under_n2 = finding(&["cat", "n1", "n2"]);
edit(
&doc,
json!({ "op": "insert", "parent": under_n2.clone(), "element": { "kind": "finding_node", "value": nested(5) } }),
);
assert_eq!(
refused(
&doc,
json!({ "op": "insert", "parent": under_n2, "element": { "kind": "finding_node", "value": nested(6) } })
),
EditError::TooDeep
);
}
#[test]
fn dependents_list_what_a_removal_leaves_dangling_or_takes() {
let doc = small();
let of = |key: Value| -> Vec<(ElementKey, Relation)> {
let key: ElementKey = serde_json::from_value(key).unwrap();
dependents(&doc, &key)
.into_iter()
.map(|d| (d.element, d.relation))
.collect()
};
let a = |id: &str| ElementKey::Annotation { id: id.to_owned() };
let f = |path: &[&str]| ElementKey::Finding {
zone_id: "z1".to_owned(),
path: path.iter().map(|s| (*s).to_owned()).collect(),
};
assert_eq!(
of(json!({ "kind": "view", "id": "head" })),
[(a("a2"), Relation::DrawnIn), (a("t1"), Relation::Opens)]
);
assert_eq!(
of(json!({ "kind": "view", "id": "main" }))[0],
(
ElementKey::View {
id: "head".to_owned()
},
Relation::ChildView
)
);
assert_eq!(of(json!({ "kind": "category", "id": "c" })).len(), 3);
assert_eq!(
of(json!({ "kind": "region", "code": "C" })),
[(a("a1"), Relation::UsesRegion)]
);
assert_eq!(
of(json!({ "kind": "reference", "id": "r1" })),
[(f(&["cat"]), Relation::Cites)]
);
assert_eq!(
of(json!({ "kind": "zone", "id": "z1" })),
[
(a("a1"), Relation::LinksZone),
(a("a2"), Relation::LinksZone),
(f(&["cat"]), Relation::Descendant),
(f(&["cat", "n1"]), Relation::Descendant),
(f(&["cat", "n1", "n2"]), Relation::Descendant)
]
);
assert_eq!(
of(finding(&["cat", "n1"])),
[(f(&["cat", "n1", "n2"]), Relation::Descendant)]
);
assert!(of(annotation("a1")).is_empty());
}
#[test]
fn the_facade_runs_the_commands_with_closed_kinds() {
let doc = serde_json::to_value(small()).unwrap();
let input = json!({ "document": doc, "command": { "op": "remove", "key": annotation("a1") } });
let outcome: Value = serde_json::from_str(&call("sheet.edit", &input.to_string())).unwrap();
assert_eq!(outcome["ok"], json!(true));
assert_eq!(
outcome["value"]["document"]["annotations"]
.as_array()
.unwrap()
.len(),
2
);
let bad = json!({ "document": doc, "command": { "op": "remove", "key": annotation("zz") } });
let outcome: Value = serde_json::from_str(&call("sheet.edit", &bad.to_string())).unwrap();
assert_eq!(outcome["kind"], json!("unknown_key"));
let shape = json!({ "document": doc, "command": { "op": "remove" } });
assert!(call("sheet.edit", &shape.to_string()).contains(r#""kind":"invalid_shape""#));
let deps = json!({ "document": doc, "key": { "kind": "view", "id": "head" } });
let outcome: Value =
serde_json::from_str(&call("sheet.dependents", &deps.to_string())).unwrap();
assert_eq!(
outcome["value"]["dependents"][0],
json!({ "element": annotation("a2"), "relation": "drawn_in" })
);
let huge = format!("{{\"document\":\"{}\"}}", "x".repeat(11 * 1024 * 1024));
assert!(call("sheet.edit", &huge).contains(r#""kind":"too_large""#));
}
// ---------------------------------------------------------------------------
// Property test
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
if n == 0 {
0
} else {
(self.next() % n as u64) as usize
}
}
fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
(!items.is_empty()).then(|| &items[self.below(items.len())])
}
}
/// A random command against the document as it stands; ids from `counter`.
fn random_command(doc: &AnatomicalSheetDocument, rng: &mut Rng, counter: &mut usize) -> Value {
*counter += 1;
let id = format!("g{counter}");
let marked: Vec<ElementKey> = marked_elements(doc).into_iter().map(|m| m.key).collect();
let views: Vec<&str> = doc.views.iter().map(|v| v.id()).collect();
let view = rng.pick(&views).copied().unwrap_or("main");
let findings: Vec<&ElementKey> = marked
.iter()
.filter(|k| matches!(k, ElementKey::Finding { path, .. } if path.len() < 8))
.collect();
match rng.below(9) {
0 => {
json!({ "op": "insert", "position": rng.below(2), "element": { "kind": "annotation", "value": {
"id": id, "kind": "point", "view_id": view, "category_id": "c", "laterality": "left",
"geometry": { "type": "circle", "cx": rng.below(9), "cy": 1, "r": 1 }, "review_status": "reviewed",
"name": name(&id), "finding_zone_id": "z1", "vertebral_region_code": null } } })
}
1 => match rng.pick(&findings) {
Some(ElementKey::Finding { zone_id, path }) => json!({ "op": "insert",
"parent": { "kind": "finding", "zone_id": zone_id, "path": path },
"element": { "kind": "finding_node", "value": { "id": id, "name": name(&id), "review_status": "reviewed" } } }),
_ => {
json!({ "op": "insert", "element": { "kind": "zone", "value": { "id": id, "name": name(&id), "categories": [] } } })
}
},
2 => {
json!({ "op": "insert", "element": { "kind": "view", "value": { "id": id, "kind": "detail", "name": name(&id),
"svg_asset_id": null, "view_box": { "min_x": 0, "min_y": 0, "width": 1 + rng.below(4), "height": 2 }, "parent_view_id": view } } })
}
3 | 4 => {
let key = rng.pick(&marked).cloned();
match key {
Some(key) => update_command(doc, &key, rng),
None => json!({ "op": "remove", "key": { "kind": "sheet" } }),
}
}
5 => {
json!({ "op": "remove", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet) })
}
6 => {
json!({ "op": "move", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet), "position": rng.below(3) })
}
7 => {
json!({ "op": "set_status", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet),
"status": if rng.below(2) == 0 { "reviewed" } else { "to_confirm" } })
}
_ => {
let zone = rng
.pick(&doc.finding_zones)
.map(|z| z.id.clone())
.unwrap_or_default();
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone } })
}
}
}
/// An update of `key`: its current value, renamed half the time.
fn update_command(doc: &AnatomicalSheetDocument, key: &ElementKey, rng: &mut Rng) -> Value {
let rename = rng.below(2) == 0;
let (kind, mut value) = match key {
ElementKey::Annotation { id } => (
"annotation",
serde_json::to_value(doc.annotations.iter().find(|a| a.id() == id).unwrap()).unwrap(),
),
ElementKey::Finding { zone_id, path } => {
let zone = doc.finding_zones.iter().find(|z| &z.id == zone_id).unwrap();
let category = zone.categories.iter().find(|c| c.id == path[0]).unwrap();
if path.len() == 1 {
("finding_category", serde_json::to_value(category).unwrap())
} else {
let mut nodes = &category.children;
let mut node = None;
for segment in &path[1..] {
let found = nodes.iter().find(|n| &n.id == segment).unwrap();
nodes = &found.children;
node = Some(found);
}
("finding_node", serde_json::to_value(node.unwrap()).unwrap())
}
}
_ => unreachable!(),
};
let changes = rename && value["name"] != name("renamed");
if rename {
value["name"] = name("renamed");
}
json!({ "op": "update", "key": key, "element": { "kind": kind, "value": value }, "changes": changes })
}
#[test]
fn random_command_sequences_keep_every_invariant() {
let equine: AnatomicalSheetDocument =
serde_json::from_value(parse_json(&common::repo_file(SEED)).unwrap()).unwrap();
for (seed, start) in [
(0x9e37_79b9_7f4a_7c15_u64, small()),
(0x2545_f491_4f6c_dd1d, equine),
] {
let mut rng = Rng(seed);
let mut counter = 0;
let mut doc = start;
let (mut applied, mut refusals) = (0, 0);
for _ in 0..400 {
let mut raw = random_command(&doc, &mut rng, &mut counter);
let changes = raw.as_object_mut().unwrap().remove("changes");
let Ok(command) = serde_json::from_value::<EditCommand>(raw.clone()) else {
continue;
};
let before = statuses(&doc);
let inherited_before = before
.values()
.filter(|s| **s == ReviewStatus::Inherited)
.count();
match apply_edit(&doc, command) {
Err(_) => refusals += 1,
Ok(next) => {
applied += 1;
let text = serde_json::to_string(&next).unwrap();
let reread: AnatomicalSheetDocument =
serde_json::from_value(parse_json(&text).unwrap()).unwrap();
assert_eq!(reread, next, "strictly parseable: {raw}");
let after = statuses(&next);
let inherited_after = after
.values()
.filter(|s| **s == ReviewStatus::Inherited)
.count();
assert!(
inherited_after <= inherited_before,
"nothing becomes inherited: {raw}"
);
check_command(&raw, changes.as_ref(), &before, &after);
doc = next;
}
}
}
assert!(
applied > 200 && refusals > 0,
"{applied} applied, {refusals} refused"
);
}
}
/// The marking rule of the command just applied, on the keys it names.
fn check_command(
raw: &Value,
changes: Option<&Value>,
before: &HashMap<ElementKey, ReviewStatus>,
after: &HashMap<ElementKey, ReviewStatus>,
) {
let op = raw["op"].as_str().unwrap();
let key = || serde_json::from_value::<ElementKey>(raw["key"].clone()).unwrap();
match op {
"insert" => {
let new: Vec<_> = after.keys().filter(|k| !before.contains_key(*k)).collect();
assert!(
new.iter().all(|k| after[*k] == ReviewStatus::ToConfirm),
"{raw}"
);
}
"update" => {
let key = key();
let expected = if changes == Some(&json!(true)) {
ReviewStatus::ToConfirm
} else {
before[&key]
};
assert_eq!(after[&key], expected, "{raw}");
assert!(
before
.iter()
.all(|(k, s)| *k == key || after.get(k) == Some(s)),
"{raw}"
);
}
"move" => assert_eq!(before, after, "{raw}"),
"set_status" => {
let expected = if raw["status"] == json!("reviewed") {
ReviewStatus::Reviewed
} else {
ReviewStatus::ToConfirm
};
assert_eq!(after[&key()], expected);
assert!(
before
.iter()
.all(|(k, s)| *k == key() || after.get(k) == Some(s)),
"{raw}"
);
}
"remove" => {
let gone: Vec<_> = before.keys().filter(|k| !after.contains_key(*k)).collect();
assert!(
gone.iter().all(|k| k == &&key() || is_below(k, &key())),
"{raw}"
);
}
_ => {}
}
}
fn is_below(key: &ElementKey, ancestor: &ElementKey) -> bool {
match (key, ancestor) {
(ElementKey::Finding { zone_id, .. }, ElementKey::Zone { id }) => zone_id == id,
(
ElementKey::Finding {
zone_id: a,
path: p,
},
ElementKey::Finding {
zone_id: b,
path: q,
},
) => a == b && p.len() > q.len() && p.starts_with(q),
_ => false,
}
}
+350
View File
@@ -0,0 +1,350 @@
//! V1-2.2: `PreviewSheet` (contract §8.1, §10). The equine draft previews with the index,
//! the fingerprint and the canvases of the bundled sheet; hash, fingerprint, caps and
//! missing-drawing faults refuse a published version; a draft loads with them reported and
//! draws with its integrity errors; a document replacement redraws without reading the
//! drawings again; no report operation runs on a preview.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::preview::{
PreviewDrawing, PreviewDrawingStatus, PreviewFailure, PreviewInput, PreviewSheet, PreviewState,
PreviewStatus,
};
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet, SheetIndexData};
use faunosteo_core::facade::{call_with_preview, call_with_sheet};
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
const HORSE_SHA: &str = "0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541";
const FINGERPRINT: &str = "12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2";
fn document_text() -> String {
common::repo_file(&format!("{SEED}/document.json"))
}
fn horse() -> Vec<u8> {
std::fs::read(common::repo_path(&format!("{SEED}/assets/horse.svg"))).unwrap()
}
fn horse_drawing() -> PreviewDrawing {
PreviewDrawing {
asset_id: HORSE_ID.to_owned(),
sha256: HORSE_SHA.to_owned(),
bytes: horse(),
}
}
fn input(status: PreviewStatus, document: String, fingerprint: Option<&str>) -> PreviewInput {
PreviewInput {
status,
document,
fingerprint: fingerprint.map(str::to_owned),
}
}
fn published() -> PreviewSheet {
let input = input(PreviewStatus::Published, document_text(), Some(FINGERPRINT));
PreviewSheet::load(input, vec![horse_drawing()]).unwrap()
}
fn load_err(input: PreviewInput, drawings: Vec<PreviewDrawing>) -> PreviewFailure {
match PreviewSheet::load(input, drawings) {
Ok(_) => panic!("loaded"),
Err(failure) => failure,
}
}
/// The report editor's sheet, from the same seed folder as the bundle plugin reads.
fn bundled() -> LoadedSheet {
let reference = parse_json(&common::repo_file(&format!("{SEED}/sheet-ref.json"))).unwrap();
let payload = json!({
"status": "draft",
"ref": reference,
"document": parse_json(&document_text()).unwrap(),
"migrationMap": parse_json(&common::repo_file(&format!("{SEED}/report-migration-map.json"))).unwrap(),
"assets": { HORSE_ID: String::from_utf8(horse()).unwrap() },
"assetHashes": { HORSE_ID: HORSE_SHA }
});
let data: BundledSheetData = serde_json::from_value(payload).unwrap();
LoadedSheet::from_bundle(data).unwrap()
}
fn state(sheet: &PreviewSheet) -> PreviewState {
sheet.state().unwrap()
}
fn canvas(outcome: String) -> Value {
serde_json::from_str(&outcome).unwrap()
}
#[test]
fn the_equine_draft_previews_as_the_bundled_sheet() {
let preview = published();
let state = state(&preview);
let bundle = bundled();
let data = SheetIndexData::of(&bundle);
assert_eq!(state.fingerprint.as_deref(), Some(FINGERPRINT));
assert_eq!(bundle.reference.document_sha256, FINGERPRINT);
let index = state.index.unwrap();
assert_eq!(index.main_view_id, data.main_view_id);
assert_eq!(index.view_by_id, data.view_by_id);
assert_eq!(index.annotation_by_id, data.annotation_by_id);
assert_eq!(index.finding_zone_by_id, data.finding_zone_by_id);
assert_eq!(index.names, data.names);
assert_eq!(index.spine_ids, data.spine_ids);
assert_eq!(index.node_keys, data.node_keys);
assert_eq!(state.document, data.document);
for view in ["main", "head"] {
let input = json!({ "viewId": view }).to_string();
let from_preview = canvas(call_with_preview(&preview, "view.canvas", &input));
assert_eq!(from_preview["ok"], json!(true), "{view}");
assert_eq!(
from_preview,
canvas(call_with_sheet(&bundle, "view.canvas", &input)),
"{view}"
);
}
assert_eq!(state.report.groups.len(), 30);
assert_eq!(state.report.document_bytes, 184_105);
assert_eq!(state.drawings.len(), 1);
assert_eq!(state.drawings[0].state, PreviewDrawingStatus::Ok);
assert_eq!(preview.drawing_reads(), 1);
}
#[test]
fn a_hash_mismatch_is_refused_in_every_mode() {
let mut bytes = horse();
bytes[200] ^= 1;
for status in [
PreviewStatus::Draft,
PreviewStatus::Published,
PreviewStatus::Deprecated,
] {
let drawing = PreviewDrawing {
bytes: bytes.clone(),
..horse_drawing()
};
let failure = load_err(
input(status, document_text(), Some(FINGERPRINT)),
vec![drawing],
);
assert_eq!(
failure,
PreviewFailure::DrawingHashMismatch(HORSE_ID.to_owned())
);
assert_eq!(failure.kind(), "drawing_hash_mismatch");
}
let not_hex = PreviewDrawing {
sha256: "X".repeat(64),
..horse_drawing()
};
let failure = load_err(
input(PreviewStatus::Draft, document_text(), None),
vec![not_hex],
);
assert_eq!(failure.kind(), "drawing_hash_mismatch");
}
#[test]
fn a_published_version_needs_its_fingerprint_its_drawings_and_its_caps() {
let wrong = "a".repeat(64);
for stored in [Some(wrong.as_str()), None] {
let failure = load_err(
input(PreviewStatus::Published, document_text(), stored),
vec![horse_drawing()],
);
assert_eq!(failure, PreviewFailure::FingerprintMismatch);
}
let deprecated = input(
PreviewStatus::Deprecated,
document_text(),
Some(FINGERPRINT),
);
assert_eq!(
load_err(deprecated, vec![]),
PreviewFailure::DrawingMissing(HORSE_ID.to_owned())
);
// Over a cap: 1 025 annotations, its own fingerprint stored.
let mut over = parse_json(&document_text()).unwrap();
let template = over["annotations"][0].clone();
let annotations = over["annotations"].as_array_mut().unwrap();
for i in annotations.len()..1025 {
let mut copy = template.clone();
copy["id"] = json!(format!("extra-{i}"));
annotations.push(copy);
}
let text = over.to_string();
let fingerprint = faunosteo_core::domain::sheet::fingerprint::sheet_fingerprint(&text).unwrap();
let failure = load_err(
input(PreviewStatus::Published, text.clone(), Some(&fingerprint)),
vec![horse_drawing()],
);
assert_eq!(failure.kind(), "caps");
assert_eq!(failure.detail(), "annotations");
// The same document as a draft loads, the excess reported.
let draft = PreviewSheet::load(
input(PreviewStatus::Draft, text, None),
vec![horse_drawing()],
)
.unwrap();
let names: Vec<&str> = state(&draft)
.report
.caps
.exceeded
.iter()
.map(|c| c.as_str())
.collect();
assert_eq!(names, ["annotations"]);
}
#[test]
fn an_unreadable_document_is_refused_in_every_mode() {
for status in [PreviewStatus::Draft, PreviewStatus::Published] {
for text in ["{", r#"{"schema_version":2}"#, "[]"] {
let failure = load_err(input(status, text.to_owned(), None), vec![]);
assert_eq!(failure.kind(), "invalid_document", "{text}");
}
}
}
#[test]
fn a_draft_loads_with_its_missing_drawings_and_draws_with_its_issues() {
let missing =
PreviewSheet::load(input(PreviewStatus::Draft, document_text(), None), vec![]).unwrap();
assert_eq!(
state(&missing).drawings[0].state,
PreviewDrawingStatus::Missing
);
let canvas_out = canvas(call_with_preview(
&missing,
"view.canvas",
r#"{"viewId":"main"}"#,
));
assert_eq!(
(canvas_out["ok"].clone(), canvas_out["kind"].clone()),
(json!(false), json!("no_asset"))
);
// Integrity errors: a duplicate annotation id and a dangling category.
let mut invalid = parse_json(&document_text()).unwrap();
let copy = invalid["annotations"][0].clone();
invalid["annotations"].as_array_mut().unwrap().push(copy);
invalid["annotations"][1]["category_id"] = json!("nowhere");
let draft = PreviewSheet::load(
input(PreviewStatus::Draft, invalid.to_string(), None),
vec![horse_drawing()],
)
.unwrap();
let state = state(&draft);
assert!(state.fingerprint.is_none());
let codes: Vec<&str> = state
.report
.issues
.iter()
.map(|i| i.code.as_str())
.collect();
assert!(
codes.contains(&"annotation.id.duplicate")
&& codes.contains(&"annotation.category.missing")
);
let drawn = canvas(call_with_preview(
&draft,
"view.canvas",
r#"{"viewId":"main"}"#,
));
assert_eq!(drawn["ok"], json!(true));
assert!(
drawn["value"]["svg"]
.as_str()
.unwrap()
.contains("data-anno-id")
);
}
#[test]
fn a_replaced_document_redraws_without_reading_the_drawings_again() {
let mut draft = PreviewSheet::load(
input(PreviewStatus::Draft, document_text(), None),
vec![horse_drawing()],
)
.unwrap();
let before = canvas(call_with_preview(
&draft,
"view.canvas",
r#"{"viewId":"main"}"#,
));
let mut edited = parse_json(&document_text()).unwrap();
edited["annotations"].as_array_mut().unwrap().truncate(3);
for _ in 0..5 {
assert_eq!(
faunosteo_core::facade::replace_preview_document(&mut draft, &edited.to_string()),
r#"{"ok":true,"value":null}"#
);
}
let after = canvas(call_with_preview(
&draft,
"view.canvas",
r#"{"viewId":"main"}"#,
));
assert_eq!(after["ok"], json!(true));
assert_ne!(after, before);
assert_eq!(
draft.drawing_reads(),
1,
"the drawing was read once, at load"
);
assert_eq!(draft.document().annotations.len(), 3);
// A refused replacement keeps the previous document.
let refused = faunosteo_core::facade::replace_preview_document(&mut draft, "{");
assert!(refused.contains(r#""kind":"invalid_document""#));
assert_eq!(draft.document().annotations.len(), 3);
// A drawing added while open is read once, however often it is added.
let svg =
br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 4"><path d="M0 0"/></svg>"#
.to_vec();
let sha = faunosteo_core::domain::sheet::verdict::sha256_hex(&svg);
for id in [
"22222222-0000-4000-8000-000000000001",
"22222222-0000-4000-8000-000000000002",
] {
let added = PreviewDrawing {
asset_id: id.to_owned(),
sha256: sha.clone(),
bytes: svg.clone(),
};
draft.add_drawing(added).unwrap();
}
assert_eq!(draft.drawing_reads(), 2);
}
#[test]
fn a_published_version_is_never_edited() {
let mut sheet = published();
assert_eq!(
sheet.replace_document(&document_text()),
Err(PreviewFailure::ReadOnly)
);
assert_eq!(
sheet.add_drawing(horse_drawing()),
Err(PreviewFailure::ReadOnly)
);
}
#[test]
fn no_report_operation_runs_on_a_preview() {
let preview = published();
for op in [
"draft.restore",
"archive.import",
"archive.snapshot",
"zone.click",
"index_data",
] {
let outcome = canvas(call_with_preview(&preview, op, "{}"));
assert_eq!(outcome["kind"], json!("unknown_op"), "{op}");
}
let state = canvas(call_with_preview(&preview, "preview.state", "{}"));
assert_eq!(state["value"]["status"], json!("published"));
}
+351
View File
@@ -0,0 +1,351 @@
//! V1-2.2: completeness, review groups, digests, removal groups and the change list
//! (contract §6.3, §6.6), on the equine draft (the counts of contract §1 and §14.1) and on
//! derived versions built by the edit commands.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::domain::sheet::edit::{EditCommand, apply_edit};
use faunosteo_core::domain::sheet::keys::ElementKey;
use faunosteo_core::domain::sheet::review::{
ChangeKind, ElementChange, ReviewGroup, change_list, completeness, review_groups,
};
use faunosteo_core::domain::sheet::schema::ReviewStatus;
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft/document.json";
fn equine() -> AnatomicalSheetDocument {
serde_json::from_value(parse_json(&common::repo_file(SEED)).unwrap()).unwrap()
}
fn edit(document: &AnatomicalSheetDocument, command: Value) -> AnatomicalSheetDocument {
let command: EditCommand = serde_json::from_value(command).unwrap();
apply_edit(document, command).unwrap()
}
fn groups(
document: &AnatomicalSheetDocument,
base: Option<&AnatomicalSheetDocument>,
) -> Vec<ReviewGroup> {
review_groups(document, base).unwrap()
}
fn group<'a>(groups: &'a [ReviewGroup], key: &str) -> &'a ReviewGroup {
groups
.iter()
.find(|g| g.key == key)
.unwrap_or_else(|| panic!("{key}"))
}
#[test]
fn the_equine_draft_has_the_counts_of_the_contract() {
let document = equine();
let counts = completeness(&document);
assert_eq!(counts.statuses.to_confirm, 188);
assert_eq!(counts.statuses.reviewed, 31);
assert_eq!(counts.statuses.inherited, 620);
let total = counts.statuses.to_confirm + counts.statuses.reviewed + counts.statuses.inherited;
assert_eq!(total, 839, "28 annotations, 81 categories, 730 nodes");
assert!(counts.vet_referrals > 0 && counts.uncited > 0);
let all = groups(&document, None);
assert_eq!(all.len(), 30, "general, 2 views, 27 zones");
assert_eq!(all[0].key, "general");
assert_eq!(all.iter().filter(|g| g.key.starts_with("view:")).count(), 2);
assert_eq!(
all.iter().filter(|g| g.key.starts_with("zone:")).count(),
27
);
assert!(all.iter().all(|g| g.digest.len() == 64 && !g.removed));
let marked: u64 = all
.iter()
.map(|g| g.statuses.to_confirm + g.statuses.reviewed + g.statuses.inherited)
.sum();
assert_eq!(
marked, 839,
"every marked element sits in exactly one group"
);
assert!(group(&all, "general").coverable);
assert_eq!(
all.iter().filter(|g| g.coverable).count(),
1,
"only general: nothing reviewed whole"
);
}
#[test]
fn digests_are_stable_and_local_to_their_group() {
let document = equine();
let before = groups(&document, None);
assert_eq!(before, groups(&document.clone(), None));
let zone = document.finding_zones[3].id.clone();
let renamed = edit(
&document,
json!({ "op": "update", "key": { "kind": "zone", "id": zone },
"element": { "kind": "zone", "value": { "id": zone, "name": { "fr": "Autre", "en": "Other" }, "categories": [] } } }),
);
let after = groups(&renamed, None);
for (old, new) in before.iter().zip(&after) {
assert_eq!(old.key, new.key);
assert_eq!(
old.digest == new.digest,
old.key != format!("zone:{zone}"),
"{}",
old.key
);
}
}
#[test]
fn an_omitted_status_digests_as_written_out_inherited() {
let text = common::repo_file(SEED);
let mut value = parse_json(&text).unwrap();
let pointer = first_omitted_status(&value).expect("the seed omits inherited somewhere");
let omitted: AnatomicalSheetDocument = serde_json::from_value(value.clone()).unwrap();
value.pointer_mut(&pointer).unwrap()["review_status"] = json!("inherited");
let explicit: AnatomicalSheetDocument = serde_json::from_value(value).unwrap();
assert_eq!(groups(&omitted, None), groups(&explicit, None));
}
/// The JSON pointer of the first finding node written without a `review_status`.
fn first_omitted_status(document: &Value) -> Option<String> {
let zones = document["finding_zones"].as_array()?;
for (z, zone) in zones.iter().enumerate() {
for (c, category) in zone["categories"].as_array()?.iter().enumerate() {
for (n, node) in category["children"].as_array()?.iter().enumerate() {
if node.get("review_status").is_none() {
return Some(format!("/finding_zones/{z}/categories/{c}/children/{n}"));
}
}
}
}
None
}
#[test]
fn a_group_is_coverable_once_every_element_is_reviewed() {
let document = equine();
let zone = document.finding_zones[0].id.clone();
let marked = edit(
&document,
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone } }),
);
let all = groups(&marked, None);
let target = group(&all, &format!("zone:{zone}"));
assert!(target.coverable);
assert_eq!(target.statuses.to_confirm + target.statuses.inherited, 0);
assert_ne!(
target.digest,
group(&groups(&document, None), &format!("zone:{zone}")).digest
);
}
#[test]
fn a_derived_version_that_deletes_a_zone_has_its_removal_group() {
let base = equine();
let zone = base.finding_zones[5].id.clone();
let derived = edit(
&base,
json!({ "op": "remove", "key": { "kind": "zone", "id": zone } }),
);
let all = groups(&derived, Some(&base));
assert_eq!(
all.len(),
30,
"29 groups of the version and one removal group"
);
let removal = all.last().unwrap();
assert_eq!(removal.key, format!("zone:{zone}"));
assert!(removal.removed && removal.coverable);
assert_ne!(
removal.digest,
group(&groups(&base, None), &removal.key).digest
);
// A second derivation removing the same zone gives the same removal digest (carry).
let again = groups(&derived.clone(), Some(&base));
assert_eq!(again.last().unwrap().digest, removal.digest);
// Unchanged groups keep the base's digest; without a base nothing is a removal.
let base_groups = groups(&base, None);
for g in all.iter().filter(|g| !g.removed) {
assert_eq!(g.digest, group(&base_groups, &g.key).digest, "{}", g.key);
}
assert!(groups(&derived, None).iter().all(|g| !g.removed));
// The change list names the zone and everything that went with it.
let changes = change_list(&derived, &base);
let removed: Vec<&ElementChange> = changes
.iter()
.filter(|c| c.change == ChangeKind::Removed)
.collect();
assert!(removed.iter().all(|c| c.group == removal.key));
assert!(
removed
.iter()
.any(|c| c.element == ElementKey::Zone { id: zone.clone() })
);
let zone_size = 1 + count_findings(&base, &zone);
assert_eq!(removed.len(), zone_size);
assert_eq!(changes.len(), zone_size, "nothing else changed");
}
fn count_findings(document: &AnatomicalSheetDocument, zone_id: &str) -> usize {
fn nodes(list: &[faunosteo_core::domain::sheet::FindingNode]) -> usize {
list.iter().map(|n| 1 + nodes(&n.children)).sum()
}
let zone = document
.finding_zones
.iter()
.find(|z| z.id == zone_id)
.unwrap();
zone.categories.iter().map(|c| 1 + nodes(&c.children)).sum()
}
#[test]
fn the_change_list_tells_added_changed_status_changed_and_moved() {
let base = equine();
let zone = base.finding_zones[0].clone();
let category = zone.categories[0].clone();
let node = category.children[0].clone();
let path = vec![category.id.clone(), node.id.clone()];
let finding = |path: &[String]| json!({ "kind": "finding", "zone_id": zone.id, "path": path });
// Status only.
let marked = edit(
&base,
json!({ "op": "set_status", "key": finding(&path), "status": "reviewed" }),
);
// A renamed node: content changed.
let mut renamed = node.clone();
renamed.name.fr = format!("{} (corrigé)", renamed.name.fr);
let changed = edit(
&marked,
json!({ "op": "update", "key": finding(&[category.id.clone(), category.children[1].id.clone()]),
"element": { "kind": "finding_node", "value": { "id": category.children[1].id, "name": renamed.name, "children": [] } } }),
);
// A new node under the category.
let added = edit(
&changed,
json!({ "op": "insert", "parent": finding(std::slice::from_ref(&category.id)),
"element": { "kind": "finding_node", "value": { "id": "n-new", "name": { "fr": "Nouveau", "en": "New" } } } }),
);
let changes = change_list(&added, &base);
let kind_of = |path: &[String]| {
changes
.iter()
.find(|c| {
c.element
== ElementKey::Finding {
zone_id: zone.id.clone(),
path: path.to_vec(),
}
})
.map(|c| (c.change, c.status_before, c.status_after))
};
assert_eq!(
kind_of(&path),
Some((
ChangeKind::StatusChanged,
Some(node.review_status),
Some(ReviewStatus::Reviewed)
))
);
let second = vec![category.id.clone(), category.children[1].id.clone()];
assert_eq!(kind_of(&second).map(|k| k.0), Some(ChangeKind::Changed));
assert_eq!(
kind_of(&second).map(|k| k.2),
Some(Some(ReviewStatus::ToConfirm))
);
let new = vec![category.id.clone(), "n-new".to_owned()];
assert_eq!(
kind_of(&new),
Some((ChangeKind::Added, None, Some(ReviewStatus::ToConfirm)))
);
assert_eq!(changes.len(), 3);
assert!(
changes
.iter()
.all(|c| c.group == format!("zone:{}", zone.id))
);
// A node re-created under another parent (no move in level 1): removed plus added.
let leaf = &category.children[2];
let other = &zone.categories[1];
let removed = edit(
&base,
json!({ "op": "remove", "key": finding(&[category.id.clone(), leaf.id.clone()]) }),
);
let mut copy = serde_json::to_value(leaf).unwrap();
copy["children"] = json!([]);
let recreated = edit(
&removed,
json!({ "op": "insert", "parent": finding(std::slice::from_ref(&other.id)), "element": { "kind": "finding_node", "value": copy } }),
);
let moved = change_list(&recreated, &base);
assert!(moved.iter().any(|c| c.change == ChangeKind::Removed));
assert!(moved.iter().any(|c| c.change == ChangeKind::Added));
}
#[test]
fn a_reorder_changes_the_group_digest_only() {
let base = equine();
let zone = &base.finding_zones[0];
let path = [zone.categories[0].id.clone()];
let moved = edit(
&base,
json!({ "op": "move", "key": { "kind": "finding", "zone_id": zone.id, "path": path }, "position": 1 }),
);
assert!(change_list(&moved, &base).is_empty(), "no element changed");
let key = format!("zone:{}", zone.id);
assert_ne!(
group(&groups(&moved, None), &key).digest,
group(&groups(&base, None), &key).digest
);
}
#[test]
fn a_removal_digest_is_bound_to_its_group_key() {
let base = equine();
let first = base.finding_zones[0].id.clone();
let second = base.finding_zones[1].id.clone();
let without_first = edit(
&base,
json!({ "op": "remove", "key": { "kind": "zone", "id": first } }),
);
let derived = edit(
&without_first,
json!({ "op": "remove", "key": { "kind": "zone", "id": second } }),
);
let removals: Vec<ReviewGroup> = groups(&derived, Some(&base))
.into_iter()
.filter(|g| g.removed)
.collect();
assert_eq!(removals.len(), 2);
assert_ne!(removals[0].digest, removals[1].digest);
}
#[test]
fn an_inherited_element_alone_keeps_its_group_uncoverable() {
let document = equine();
let zone = document.finding_zones[0].clone();
let marked = edit(
&document,
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone.id } }),
);
let mut value = serde_json::to_value(&marked).unwrap();
value["finding_zones"][0]["categories"][0]["children"][0]
.as_object_mut()
.unwrap()
.remove("review_status");
let one_inherited: AnatomicalSheetDocument = serde_json::from_value(value).unwrap();
let key = format!("zone:{}", zone.id);
let all = groups(&one_inherited, None);
let target = group(&all, &key);
assert_eq!(
(target.statuses.to_confirm, target.statuses.inherited),
(0, 1)
);
assert!(
!target.coverable,
"an omitted status is inherited, never acknowledgeable"
);
assert!(group(&groups(&marked, None), &key).coverable);
}
+120
View File
@@ -0,0 +1,120 @@
//! V1-2.2: the document size as the server measures it (contract §12.2). Every vector of
//! `oracles/v1-2-2/size.json` was measured by PostgreSQL (`octet_length(text::jsonb::text)`,
//! PGlite 17.5); the equine seed's value equals the one the contract recorded on the real
//! image (184 105 bytes). The pgTAP 017 fixtures are rebuilt on the same base document:
//! cap − 1, cap and cap + 1 bytes in 1-, 3- and 4-byte characters, a dense document, numbers
//! JavaScript prints with an exponent.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::size::{MAX_DOCUMENT_BYTES, document_text_bytes};
use serde_json::{Value, json};
fn oracle() -> Value {
common::oracle_file("v1-2-2/size.json").1
}
fn measure(text: &str) -> u64 {
document_text_bytes(&parse_json(text).unwrap())
}
#[test]
fn every_postgresql_vector_is_reproduced() {
let oracle = oracle();
let vectors = oracle["vectors"].as_array().unwrap();
assert!(vectors.len() >= 17);
for vector in vectors {
let text = vector["text"].as_str().unwrap();
assert_eq!(
measure(text),
vector["bytes"].as_u64().unwrap(),
"{}",
vector["name"]
);
}
}
#[test]
fn the_equine_seed_measures_as_on_the_server() {
let oracle = oracle();
let seed = &oracle["seed"];
let text = common::repo_file(seed["file"].as_str().unwrap());
assert_eq!(measure(&text), 184_105);
assert_eq!(seed["bytes"].as_u64(), Some(184_105));
}
/// `pg_temp.sized(base, bytes, unit)`: the base with a `pad` string of units, then `x`s, so
/// that the whole document measures `bytes`.
fn sized(base: &Value, bytes: u64, unit: &str) -> Value {
let mut empty = base.clone();
empty["pad"] = json!("");
let free = bytes - document_text_bytes(&empty);
let width = unit.len() as u64;
let pad = unit.repeat((free / width) as usize) + &"x".repeat((free % width) as usize);
let mut document = base.clone();
document["pad"] = Value::String(pad);
document
}
fn pgtap_base() -> (Value, u64) {
let oracle = oracle();
let base = &oracle["pgtap_017_base"];
let mut value = parse_json(base["text"].as_str().unwrap()).unwrap();
value.as_object_mut().unwrap().remove("pad");
(value, base["bytes"].as_u64().unwrap())
}
#[test]
fn the_pgtap_017_cap_vectors_measure_as_the_server_does() {
let (base, with_empty_pad) = pgtap_base();
let mut empty = base.clone();
empty["pad"] = json!("");
assert_eq!(document_text_bytes(&empty), with_empty_pad);
for unit in ["x", "€", "𝄞"] {
for bytes in [
MAX_DOCUMENT_BYTES - 1,
MAX_DOCUMENT_BYTES,
MAX_DOCUMENT_BYTES + 1,
] {
let document = sized(&base, bytes, unit);
assert_eq!(document_text_bytes(&document), bytes, "{unit} {bytes}");
}
}
let wide = sized(&base, MAX_DOCUMENT_BYTES, "€");
let characters = wide["pad"].as_str().unwrap().chars().count();
assert!(characters < 800_000, "2 MiB in far fewer characters");
}
#[test]
fn a_dense_document_is_measured_as_text_not_as_binary_jsonb() {
let (mut document, _) = pgtap_base();
document["pad"] = Value::Array(vec![json!({ "a": 1 }); 100_000]);
let bytes = document_text_bytes(&document);
// `{"a": 1}` is 8 bytes and `, ` separates them: the array is 2 + 800 000 + 199 998
// bytes; the member adds `"pad"`, `: ` and the `, ` before it.
let mut without = document.clone();
without.as_object_mut().unwrap().remove("pad");
assert_eq!(bytes - document_text_bytes(&without), 1_000_000 + 5 + 2 + 2);
assert!(bytes <= MAX_DOCUMENT_BYTES);
}
#[test]
fn exponent_numbers_count_in_their_plain_form() {
let (mut document, _) = pgtap_base();
document["pad"] = Value::Array(vec![json!(1e21); 100_000]);
let compact = faunosteo_core::json::to_js_compact(&document).unwrap();
// The page's compact text is under the cap (`1e+21` is five bytes); PostgreSQL prints
// 22 digits per number and refuses it.
assert!((compact.len() as u64) < MAX_DOCUMENT_BYTES);
assert!(document_text_bytes(&document) > MAX_DOCUMENT_BYTES);
}
#[test]
fn the_measure_is_linear_in_the_numbers() {
let document = Value::Array(vec![json!(0); 600_000]);
let started = std::time::Instant::now();
assert_eq!(document_text_bytes(&document), 2 + 600_000 + 2 * 599_999);
assert!(started.elapsed().as_secs() < 2);
}
+542
View File
@@ -0,0 +1,542 @@
//! V1-2.2: the server verdict (contract §6.4, §6.5, §6.7). A clean sheet and the equine draft
//! pass; each submission rule fails alone with its closed code; the caps hold at cap − 1 and
//! cap and fail at cap + 1 (labels in astral characters included); the shape is the one the
//! M5 SQL reads; the same input gives the same verdict; a synthetic document at the caps is
//! verified in time.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::sheet::fingerprint::sheet_fingerprint;
use faunosteo_core::domain::sheet::verdict::{
DrawingResult, Verdict, VerdictBinding, VerdictDrawing, VerdictInput, VerdictOutcome, codes,
compute_verdict, sha256_hex,
};
use serde_json::{Value, json};
const ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DRAWING: &str =
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#;
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
fn binding() -> VerdictBinding {
VerdictBinding {
sheet_id: "aaaaaaaa-0000-4000-8000-000000000001".to_owned(),
version_id: "aaaaaaaa-0000-4000-8000-000000000002".to_owned(),
revision: 3,
review_id: "aaaaaaaa-0000-4000-8000-000000000003".to_owned(),
}
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// A small valid document drawn on `ASSET`: one view, one point, one zone with a category
/// and a node, everything `to_confirm` (submittable, not yet approvable).
fn document() -> Value {
json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": { "fr": "Outil", "en": "Tool" },
"attribution": { "authors": ["A"], "license": null, "notes": null },
"vertebral_config": { "regions": [] }, "references": [],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": ASSET, "view_box": null }],
"annotations": [{ "id": "a1", "kind": "point", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 1, "cy": 1, "r": 1 },
"review_status": "to_confirm", "name": name("P"), "finding_zone_id": "z1", "vertebral_region_code": null }],
"finding_zones": [{ "id": "z1", "name": name("Z"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("D"), "review_status": "to_confirm",
"children": [{ "id": "n1", "name": name("N"), "review_status": "to_confirm" }] }] }]
})
}
fn row(bytes: &[u8]) -> VerdictDrawing<'_> {
VerdictDrawing {
asset_id: ASSET,
sha256: Box::leak(sha256_hex(bytes).into_boxed_str()),
byte_size: bytes.len() as u64,
bytes: Some(bytes),
}
}
fn verdict_of(document: &Value, drawings: Vec<VerdictDrawing<'_>>) -> Verdict {
let text = document.to_string();
compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: None,
drawings,
})
}
fn verdict(document: &Value) -> Verdict {
verdict_of(document, vec![row(DRAWING.as_bytes())])
}
#[test]
fn a_clean_sheet_passes_bound_to_its_round() {
let doc = document();
let verdict = verdict(&doc);
assert_eq!(
verdict.outcome,
VerdictOutcome::Passed,
"{:?}",
verdict.failures
);
assert_eq!(
(verdict.failure_code.as_deref(), verdict.failures.len()),
(None, 0)
);
assert_eq!(
verdict.fingerprint,
Some(sheet_fingerprint(&doc.to_string()).unwrap())
);
let b = binding();
assert_eq!(
(
&verdict.sheet_id,
&verdict.version_id,
verdict.revision,
&verdict.review_id
),
(&b.sheet_id, &b.version_id, b.revision, &b.review_id)
);
assert_eq!(verdict.format, 1);
assert!(verdict.verified_with.starts_with("faunosteo-core "));
assert_eq!(verdict.drawings.len(), 1);
assert_eq!(verdict.drawings[0].result, DrawingResult::Ok);
let keys: Vec<&str> = verdict.groups.iter().map(|g| g.key.as_str()).collect();
assert_eq!(keys, ["general", "view:main", "zone:z1"]);
assert!(
verdict.groups.iter().skip(1).all(|g| !g.coverable),
"to_confirm left"
);
assert!(verdict.changes.is_none());
let completeness = verdict.completeness.unwrap();
assert_eq!(completeness.statuses.to_confirm, 3);
assert_eq!(completeness.uncited, 2);
}
#[test]
fn the_shape_is_what_the_sql_reads() {
let value = serde_json::to_value(verdict(&document())).unwrap();
assert!(value["fingerprint"].as_str().unwrap().len() == 64);
for group in value["groups"].as_array().unwrap() {
assert!(group["key"].is_string() && group["digest"].is_string());
assert!(group["coverable"].is_boolean());
}
let drawing = &value["drawings"][0];
assert_eq!(drawing["asset_id"], json!(ASSET));
assert_eq!(drawing["sha256"], json!(sha256_hex(DRAWING.as_bytes())));
assert_eq!(value["outcome"], json!("passed"));
assert_eq!(
value["verified_with"].as_str().map(|s| s.len() <= 100),
Some(true)
);
}
#[test]
fn the_equine_draft_passes_with_its_fingerprint_and_thirty_groups() {
let text = common::repo_file(&format!("{SEED}/document.json"));
let horse = std::fs::read(common::repo_path(&format!("{SEED}/assets/horse.svg"))).unwrap();
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: None,
drawings: vec![VerdictDrawing {
asset_id: HORSE_ID,
sha256: "0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541",
byte_size: 132_997,
bytes: Some(&horse),
}],
});
assert_eq!(
verdict.outcome,
VerdictOutcome::Passed,
"{:?}",
verdict.failures
);
assert_eq!(
verdict.fingerprint.as_deref(),
Some("12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2")
);
assert_eq!(verdict.groups.len(), 30);
assert_eq!(verdict.document_bytes, 184_105);
assert!(
verdict
.issues
.iter()
.all(|i| i.severity != faunosteo_core::domain::sheet::SheetIssueSeverity::Error)
);
}
fn failures(verdict: &Verdict) -> Vec<&str> {
verdict.failures.iter().map(String::as_str).collect()
}
#[test]
fn an_unreadable_document_or_base_fails_as_integrity() {
for text in ["{", "[]", r#"{"schema_version":2}"#] {
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: text,
base_document: None,
drawings: vec![],
});
assert_eq!(failures(&verdict), [codes::DOCUMENT], "{text}");
assert!(verdict.fingerprint.is_none() && verdict.groups.is_empty());
}
let mut unknown = document();
unknown["extra"] = json!(1);
assert_eq!(
failures(&verdict(&unknown)),
[codes::DOCUMENT],
"strict shape"
);
let text = document().to_string();
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: Some("{\"broken\""),
drawings: vec![row(DRAWING.as_bytes())],
});
assert_eq!(failures(&verdict), [codes::BASE]);
}
#[test]
fn each_submission_rule_fails_alone() {
let mut duplicate = document();
let copy = duplicate["annotations"][0].clone();
duplicate["annotations"].as_array_mut().unwrap().push(copy);
let v = verdict(&duplicate);
assert_eq!(failures(&v), [codes::RULES]);
assert!(
v.fingerprint.is_none(),
"no fingerprint with an integrity error"
);
assert!(v.issues.iter().any(|i| i.code == "annotation.id.duplicate"));
let mut undrawn = document();
undrawn["annotations"][0]["geometry"] = Value::Null;
let v = verdict(&undrawn);
assert_eq!(failures(&v), [codes::NO_GEOMETRY]);
assert!(
v.fingerprint.is_some(),
"a missing geometry is no integrity error"
);
assert!(v.issues.iter().any(|i| i.code == "annotation.geometry.missing" && i.path == "annotations[0].geometry"));
}
#[test]
fn each_drawing_fault_fails_with_its_code() {
let doc = document();
let bytes = DRAWING.as_bytes();
let base = row(bytes);
let cases: Vec<(Vec<VerdictDrawing<'_>>, &str, DrawingResult)> = vec![
(vec![], codes::DRAWING_MISSING, DrawingResult::Missing),
(
vec![VerdictDrawing {
bytes: None,
..base
}],
codes::DRAWING_MISSING,
DrawingResult::Missing,
),
(
vec![VerdictDrawing {
byte_size: 1,
..base
}],
codes::SIZE_MISMATCH,
DrawingResult::SizeMismatch,
),
(
vec![VerdictDrawing {
sha256: "ab",
..base
}],
codes::OBJECT_CONFLICT,
DrawingResult::HashMismatch,
),
];
for (drawings, code, result) in cases {
let v = verdict_of(&doc, drawings);
assert_eq!(failures(&v), [code]);
assert_eq!(v.drawings[0].result, result);
assert!(v.fingerprint.is_some());
}
let invalid: &[u8] = b"<svg xmlns=\"http://www.w3.org/2000/svg\">\xff</svg>";
let doctype = b"<!DOCTYPE svg><svg xmlns=\"http://www.w3.org/2000/svg\"/>";
let styled = br#"<svg xmlns="http://www.w3.org/2000/svg"><style>.a{fill:red}</style><path class="a" d="M0 0"/></svg>"#;
for (bytes, code, detail) in [
(invalid, codes::SVG_REJECTED, "malformed"),
(&doctype[..], codes::SVG_REJECTED, "doctype"),
(&styled[..], codes::SVG_REMOVAL, "style"),
] {
let v = verdict_of(&doc, vec![row(bytes)]);
assert_eq!(failures(&v), [code]);
assert_eq!(v.drawings[0].detail.as_deref(), Some(detail));
}
}
/// `count` annotations drawn in the main view, all in zone `z1`.
fn with_annotations(count: usize) -> Value {
let mut doc = document();
let template = doc["annotations"][0].clone();
doc["annotations"] = (0..count)
.map(|i| {
let mut a = template.clone();
a["id"] = json!(format!("a{i}"));
a
})
.collect();
doc
}
fn caps_failed(doc: &Value) -> bool {
let v = verdict(doc);
assert!(
v.failures.iter().all(|c| c == codes::CAPS),
"{:?}",
v.failures
);
v.failures.iter().any(|c| c == codes::CAPS)
}
#[test]
fn the_caps_hold_at_the_cap_and_fail_one_over() {
assert!(!caps_failed(&with_annotations(1023)) && !caps_failed(&with_annotations(1024)));
assert!(caps_failed(&with_annotations(1025)));
// Labels in UTF-16 units: 𝄞 counts two.
for (label, over) in [
("𝄞".repeat(255) + "a", false),
("𝄞".repeat(256), false),
("𝄞".repeat(256) + "a", true),
] {
let mut doc = document();
doc["finding_zones"][0]["name"] = json!({ "fr": label, "en": "Z" });
assert_eq!(caps_failed(&doc), over);
}
for (depth, over) in [(7, false), (8, false), (9, true)] {
let mut doc = document();
doc["finding_zones"][0]["categories"][0]["children"] = chain(depth - 1);
assert_eq!(caps_failed(&doc), over, "depth {depth}");
}
for (nodes, over) in [(8191, false), (8192, false), (8193, true)] {
let mut doc = document();
let flat: Vec<Value> = (0..nodes - 1)
.map(|i| json!({ "id": format!("n{i}"), "name": name("N"), "review_status": "to_confirm" }))
.collect();
doc["finding_zones"][0]["categories"][0]["children"] = Value::Array(flat);
assert_eq!(caps_failed(&doc), over, "{nodes} nodes");
}
}
/// `levels` nested nodes below the category.
fn chain(levels: usize) -> Value {
let mut children = json!([]);
for i in (0..levels).rev() {
children = json!([{ "id": format!("d{i}"), "name": name("N"), "review_status": "to_confirm", "children": children }]);
}
children
}
#[test]
fn the_document_cap_is_the_server_measure() {
let measure = |doc: &Value| verdict(doc).document_bytes;
let mut doc = document();
doc["description"] = json!({ "fr": "" });
let empty = measure(&doc);
for (bytes, over) in [
(2_097_151_u64, false),
(2_097_152, false),
(2_097_153, true),
] {
let mut sized = doc.clone();
sized["description"]["fr"] = json!(
"é".repeat(((bytes - empty) / 2) as usize)
+ &"x".repeat(((bytes - empty) % 2) as usize)
);
assert_eq!(measure(&sized), bytes);
assert_eq!(caps_failed(&sized), over, "{bytes}");
}
}
#[test]
fn drawings_count_toward_the_caps() {
let mut doc = document();
let ids = [
ASSET,
"11111111-2222-4333-8444-000000000002",
"11111111-2222-4333-8444-000000000003",
"11111111-2222-4333-8444-000000000004",
"11111111-2222-4333-8444-000000000005",
];
let views: Vec<Value> = ids
.iter()
.enumerate()
.map(|(i, id)| match i {
0 => json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": id, "view_box": null }),
_ => json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": id,
"view_box": null, "parent_view_id": "main" }),
})
.collect();
let triggers: Vec<Value> = (1..ids.len())
.map(|i| json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 2, "cy": 2, "r": 1 },
"review_status": "to_confirm", "name": null, "opens_view_id": format!("d{i}") }))
.collect();
doc["views"] = Value::Array(views);
doc["annotations"].as_array_mut().unwrap().extend(triggers);
let bytes = DRAWING.as_bytes();
let rows = |n: usize| -> Vec<VerdictDrawing<'_>> {
ids.iter()
.take(n)
.map(|id| VerdictDrawing {
asset_id: id,
..row(bytes)
})
.collect()
};
let mut four = doc.clone();
four["views"].as_array_mut().unwrap().pop();
four["annotations"].as_array_mut().unwrap().pop();
assert_eq!(failures(&verdict_of(&four, rows(4))), Vec::<&str>::new());
let v = verdict_of(&doc, rows(5));
assert_eq!(failures(&v), [codes::CAPS]);
assert!(
v.caps
.unwrap()
.exceeded
.iter()
.any(|c| c.as_str() == "drawings")
);
}
#[test]
fn the_first_failure_names_the_round_in_code_order() {
let mut doc = with_annotations(1025);
doc["annotations"][0]["geometry"] = Value::Null;
let copy = doc["annotations"][1].clone();
doc["annotations"].as_array_mut().unwrap().push(copy);
let v = verdict_of(&doc, vec![]);
assert_eq!(
failures(&v),
[
codes::RULES,
codes::NO_GEOMETRY,
codes::CAPS,
codes::DRAWING_MISSING
]
);
assert_eq!(v.failure_code.as_deref(), Some(codes::RULES));
assert_eq!(v.outcome, VerdictOutcome::Failed);
}
#[test]
fn the_same_input_gives_the_same_verdict() {
let doc = document();
let first = serde_json::to_string(&verdict(&doc)).unwrap();
assert_eq!(first, serde_json::to_string(&verdict(&doc)).unwrap());
}
#[test]
fn a_base_gives_removal_groups_and_the_change_list() {
let mut base = document();
base["finding_zones"]
.as_array_mut()
.unwrap()
.push(json!({ "id": "z2", "name": name("Z2"), "categories": [] }));
let text = document().to_string();
let base_text = base.to_string();
let v = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: Some(&base_text),
drawings: vec![row(DRAWING.as_bytes())],
});
assert_eq!(v.outcome, VerdictOutcome::Passed);
let last = v.groups.last().unwrap();
assert_eq!(
(last.key.as_str(), last.removed, last.coverable),
("zone:z2", true, true)
);
let changes = v.changes.unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].group, "zone:z2");
}
/// A document at every cap: 64 views, 1 024 annotations, 8 192 finding nodes, depth 8.
fn at_caps() -> Value {
let mut doc = document();
let mut views = vec![
json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": ASSET, "view_box": null }),
];
let mut annotations = Vec::new();
for i in 1..64 {
views.push(json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": 5, "height": 5 }, "parent_view_id": "main" }));
annotations.push(json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] },
"review_status": "reviewed", "name": null, "opens_view_id": format!("d{i}") }));
}
let zones: Vec<Value> = (0..64)
.map(|z| {
let mut children = vec![chain_reviewed(7)];
children.extend((0..120).map(|n| json!({ "id": format!("l{n}"), "name": name("Nœud de lésion"), "review_status": "reviewed" })));
json!({ "id": format!("z{z}"), "name": name("Zone"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("Catégorie"), "review_status": "reviewed", "children": children }] })
})
.collect();
for i in 0..(1024 - 63) {
annotations.push(json!({ "id": format!("p{i}"), "kind": "point", "view_id": format!("d{}", 1 + i % 63),
"category_id": "c", "laterality": "left", "geometry": { "type": "circle", "cx": 1.25, "cy": 2.5, "r": 0.5 },
"review_status": "reviewed", "name": name("Point"), "finding_zone_id": format!("z{}", i % 64),
"vertebral_region_code": null }));
}
doc["views"] = Value::Array(views);
doc["annotations"] = Value::Array(annotations);
doc["finding_zones"] = Value::Array(zones);
doc
}
fn chain_reviewed(levels: usize) -> Value {
let mut node =
json!({ "id": format!("c{levels}"), "name": name("N"), "review_status": "reviewed" });
for level in (1..levels).rev() {
node = json!({ "id": format!("c{level}"), "name": name("N"), "review_status": "reviewed", "children": [node] });
}
node
}
#[test]
fn a_document_at_every_cap_is_verified_in_time() {
let doc = at_caps();
let started = std::time::Instant::now();
let v = verdict(&doc);
let elapsed = started.elapsed();
assert_eq!(v.outcome, VerdictOutcome::Passed, "{:?}", v.failures);
let caps = v.caps.unwrap();
assert_eq!(
(
caps.views,
caps.annotations,
caps.finding_nodes,
caps.finding_depth
),
(64, 1024, 8192, 8)
);
assert_eq!(v.groups.len(), 1 + 64 + 64);
assert!(v.groups.iter().all(|g| g.coverable));
println!(
"verdict at the caps: {} ms, document {} bytes",
elapsed.as_millis(),
v.document_bytes
);
assert!(
elapsed.as_secs() < 20,
"the core's share of the 120 s budget"
);
}