Wraps create_empty_sheet_document; refusals invalid_shape / invalid_json; ts-rs SheetEmptyInput, core-wasm proof, app wrapper emptySheetDocument.
531 lines
18 KiB
Rust
531 lines
18 KiB
Rust
//! The operations the facade exposes (R2 plan rev 2 §5): one input contract and one handler
|
|
//! per user action or load, each returning a closed failure instead of panicking. Free
|
|
//! operations take everything they need; sheet operations take the session's sheet.
|
|
|
|
use serde::Deserialize;
|
|
use serde_json::Value;
|
|
#[cfg(feature = "ts")]
|
|
use ts_rs::TS;
|
|
|
|
use crate::anatomy::compose::{ComposeError, asset_id_of_view, compose_canvas};
|
|
use crate::anatomy::svg::serialize::serialize;
|
|
use crate::domain::archive::build_sheet_snapshot;
|
|
use crate::domain::editor::{
|
|
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
|
|
};
|
|
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::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, LocalizedText, SheetIndexData, check_sheet_document,
|
|
create_empty_sheet_document,
|
|
};
|
|
use crate::facade::{Failure, parse_input, to_value};
|
|
use crate::pdf::json_js::{MAX_JSON_VALUES, prescan};
|
|
|
|
type Outcome = Result<Value, Failure>;
|
|
|
|
/// An index as JavaScript sent it: a number. Only a non-negative integer names a position.
|
|
#[derive(Debug, Clone, Copy, Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export, type = "number"))]
|
|
pub struct JsIndex(f64);
|
|
|
|
impl JsIndex {
|
|
/// The position, or `None` for a negative or fractional number.
|
|
fn position(self) -> Option<usize> {
|
|
let value = self.0;
|
|
let integral = value >= 0.0 && value.fract() == 0.0 && value < 4_294_967_296.0;
|
|
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
|
|
integral.then_some(value as usize)
|
|
}
|
|
|
|
/// For the filters (`filter((_, i) => i !== index)`): a number that names no position
|
|
/// removes nothing, as an index past the end does.
|
|
fn or_none(self) -> usize {
|
|
self.position().unwrap_or(usize::MAX)
|
|
}
|
|
}
|
|
|
|
fn editor_failure(error: EditorError) -> Failure {
|
|
Failure::new(error.kind(), "")
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Free operations
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct NewReportInput {
|
|
pub draft: NewReportDraft,
|
|
pub sheet: SheetRef,
|
|
pub id: String,
|
|
pub created_at: String,
|
|
pub observation_id: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ReportIdInput {
|
|
pub report: Report,
|
|
pub id: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ReportIndexInput {
|
|
pub report: Report,
|
|
pub index: JsIndex,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct MoveObservationInput {
|
|
pub report: Report,
|
|
pub index: JsIndex,
|
|
pub direction: MoveDirection,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct VertebraSelectInput {
|
|
pub selection: Vec<Vertebra>,
|
|
pub action: VertebraAction,
|
|
}
|
|
|
|
/// Runs a free operation; `None` when `op` is not one of them.
|
|
pub fn free(op: &str, input: &str) -> Option<Outcome> {
|
|
Some(match op {
|
|
"sheet.check" => sheet_check(input),
|
|
"sheet.empty" => sheet_empty(input),
|
|
"report.new" => report_new(input),
|
|
"report.add_observation" => report_add(input),
|
|
"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,
|
|
})
|
|
}
|
|
|
|
fn sheet_check(input: &str) -> Outcome {
|
|
let document = parse_json(input)?;
|
|
let check =
|
|
check_sheet_document(document).map_err(|error| Failure::new("invalid_shape", error))?;
|
|
to_value(&check)
|
|
}
|
|
|
|
/// A new sheet's starting point (V1-2 contract §7.4): the slug is not part of the document.
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SheetEmptyInput {
|
|
pub species_id: String,
|
|
pub name: LocalizedText,
|
|
}
|
|
|
|
/// An empty label is refused by the input's shape, an invalid species id by the document's.
|
|
fn sheet_empty(input: &str) -> Outcome {
|
|
let input: SheetEmptyInput = parse_input(input)?;
|
|
create_empty_sheet_document(&input.species_id, &input.name)
|
|
.map_err(|error| Failure::new("invalid_shape", error))
|
|
.and_then(|document| to_value(&document))
|
|
}
|
|
|
|
#[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 {
|
|
id: &input.id,
|
|
created_at: &input.created_at,
|
|
observation_id: &input.observation_id,
|
|
};
|
|
to_value(&editor::new_report(input.draft, input.sheet, &stamp))
|
|
}
|
|
|
|
fn report_add(input: &str) -> Outcome {
|
|
let input: ReportIdInput = parse_input(input)?;
|
|
to_value(&editor::add_observation(&input.report, &input.id))
|
|
}
|
|
|
|
fn report_remove(input: &str) -> Outcome {
|
|
let input: ReportIndexInput = parse_input(input)?;
|
|
to_value(&editor::remove_observation(
|
|
&input.report,
|
|
input.index.or_none(),
|
|
))
|
|
}
|
|
|
|
fn report_move(input: &str) -> Outcome {
|
|
let input: MoveObservationInput = parse_input(input)?;
|
|
let index = input
|
|
.index
|
|
.position()
|
|
.ok_or_else(|| editor_failure(EditorError::InvalidIndex))?;
|
|
editor::move_observation(&input.report, index, input.direction)
|
|
.map_err(editor_failure)
|
|
.and_then(|report| to_value(&report))
|
|
}
|
|
|
|
fn vertebra_select(input: &str) -> Outcome {
|
|
let input: VertebraSelectInput = parse_input(input)?;
|
|
editor::select_vertebrae(&input.selection, &input.action)
|
|
.map_err(editor_failure)
|
|
.and_then(|selection| to_value(&selection))
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Sheet operations
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ZoneClickInput {
|
|
pub observation: Option<Observation>,
|
|
pub annotation_id: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct AddSidesInput {
|
|
pub observation: Observation,
|
|
pub annotation_id: String,
|
|
pub sides: Vec<LateralSide>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ObservationIndexInput {
|
|
pub observation: Observation,
|
|
pub index: JsIndex,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct VertebraSyncInput {
|
|
pub observation: Observation,
|
|
pub selection: Vec<Vertebra>,
|
|
pub view_id: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct FindingToggleInput {
|
|
pub observation: Observation,
|
|
pub finding_zone_id: String,
|
|
pub path: Vec<String>,
|
|
pub leaf_position: JsIndex,
|
|
#[serde(default, deserialize_with = "crate::domain::js::present")]
|
|
#[cfg_attr(feature = "ts", ts(optional))]
|
|
pub side: Option<LateralSide>,
|
|
}
|
|
|
|
/// Runs an operation on the session's sheet; `None` when `op` is not one of them.
|
|
pub fn on_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> Option<Outcome> {
|
|
Some(match op {
|
|
"index_data" => to_value(&SheetIndexData::of(sheet)),
|
|
"zone.click" => zone_click(sheet, input),
|
|
"zone.add_sides" => zone_add_sides(sheet, input),
|
|
"zone.remove_at" => zone_remove_at(input),
|
|
"vertebra.initial" => vertebra_initial(sheet, input),
|
|
"vertebra.sync" => vertebra_sync(sheet, input),
|
|
"finding.toggle" => finding_toggle(sheet, input),
|
|
"draft.restore" => draft_restore(sheet, input),
|
|
"archive.import" => archive_import(sheet, input),
|
|
"archive.snapshot" => archive_snapshot(sheet, input),
|
|
"view.canvas" => view_canvas(sheet, input),
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
fn zone_click(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: ZoneClickInput = parse_input(input)?;
|
|
let click = editor::zone_click(
|
|
&sheet.indexed(),
|
|
input.observation.as_ref(),
|
|
&input.annotation_id,
|
|
);
|
|
to_value(&click)
|
|
}
|
|
|
|
fn zone_add_sides(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: AddSidesInput = parse_input(input)?;
|
|
editor::add_sides(
|
|
&sheet.indexed(),
|
|
&input.observation,
|
|
&input.annotation_id,
|
|
&input.sides,
|
|
)
|
|
.map_err(editor_failure)
|
|
.and_then(|observation| to_value(&observation))
|
|
}
|
|
|
|
fn zone_remove_at(input: &str) -> Outcome {
|
|
let input: ObservationIndexInput = parse_input(input)?;
|
|
to_value(&editor::remove_zone_at(
|
|
&input.observation,
|
|
input.index.or_none(),
|
|
))
|
|
}
|
|
|
|
fn vertebra_initial(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: ObservationIndexInput = parse_input(input)?;
|
|
to_value(&editor::vertebra_initial(
|
|
&sheet.indexed(),
|
|
&input.observation,
|
|
input.index.or_none(),
|
|
))
|
|
}
|
|
|
|
fn vertebra_sync(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: VertebraSyncInput = parse_input(input)?;
|
|
to_value(&editor::sync_vertebrae(
|
|
&sheet.indexed(),
|
|
&input.observation,
|
|
&input.selection,
|
|
&input.view_id,
|
|
))
|
|
}
|
|
|
|
fn finding_toggle(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: FindingToggleInput = parse_input(input)?;
|
|
let click = LeafClick {
|
|
finding_zone_id: &input.finding_zone_id,
|
|
path: &input.path,
|
|
leaf_position: input.leaf_position.or_none(),
|
|
side: input.side,
|
|
};
|
|
editor::toggle_finding(&sheet.indexed(), &input.observation, &click)
|
|
.map_err(editor_failure)
|
|
.and_then(|observation| to_value(&observation))
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct DraftRestoreInput {
|
|
/// The raw text of the tab's draft.
|
|
pub draft: String,
|
|
/// The raw text of the session's archive envelope, when one is stored.
|
|
pub archive: Option<String>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct SnapshotInput {
|
|
pub report: Report,
|
|
}
|
|
|
|
/// A failure that names the document version a reader refused.
|
|
fn versioned(kind: &'static str, found: Option<f64>) -> Failure {
|
|
Failure {
|
|
found,
|
|
..Failure::new(kind, "")
|
|
}
|
|
}
|
|
|
|
/// Content kinds (`invalid`, `unsupported_version`, `lone_surrogate`) mean the draft itself
|
|
/// is unreadable: the caller sets it aside, verbatim. `rebase_failed` is a defect of the loaded sheet, never of the
|
|
/// draft, and leaves it where it is.
|
|
fn draft_restore(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: DraftRestoreInput = parse_input(input)?;
|
|
// OD-3: a token-dense text is refused before the parser allocates its tree; the caller
|
|
// sets the text aside verbatim, as for any unreadable draft (`invalid`). The archive is
|
|
// checked too: a stored one was accepted under the budget, so only a crafted one fails.
|
|
let texts = [Some(input.draft.as_str()), input.archive.as_deref()];
|
|
if texts.into_iter().flatten().any(over_value_budget) {
|
|
return Err(Failure::new("invalid", "json value budget exceeded"));
|
|
}
|
|
session::restore_draft(sheet, &input.draft, input.archive.as_deref())
|
|
.map_err(restore_failure)
|
|
.and_then(|restore| to_value(&restore))
|
|
}
|
|
|
|
/// The closed kinds of a draft restore failure, shared with the rescue copy read as bytes.
|
|
pub(crate) fn restore_failure(failure: RestoreFailure) -> Failure {
|
|
match failure {
|
|
RestoreFailure::UnsupportedVersion(found) => versioned("unsupported_version", found),
|
|
RestoreFailure::LoneSurrogate(detail) => Failure::new("lone_surrogate", detail),
|
|
RestoreFailure::Invalid(detail) => Failure::new("invalid", detail),
|
|
RestoreFailure::Rebase(detail) => Failure::new("rebase_failed", detail),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn over_value_budget(text: &str) -> bool {
|
|
prescan(text.as_bytes()).values > MAX_JSON_VALUES
|
|
}
|
|
|
|
/// The input is the attachment's JSON as the byte scan read it (any shape).
|
|
fn archive_import(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
session::import_archive(sheet, input)
|
|
.map_err(import_failure)
|
|
.and_then(|import| to_value(&import))
|
|
}
|
|
|
|
/// The closed kinds of a session import failure, shared with the PDF import.
|
|
pub(crate) fn import_failure(failure: ImportFailure) -> Failure {
|
|
match failure {
|
|
ImportFailure::IncompatibleVersion(found) => versioned("incompatible_version", Some(found)),
|
|
ImportFailure::NoAttachment => Failure::new("no_attachment", ""),
|
|
ImportFailure::LoneSurrogate(detail) => Failure::new("lone_surrogate", detail),
|
|
ImportFailure::Invalid(detail) => Failure::new("invalid", detail),
|
|
}
|
|
}
|
|
|
|
fn archive_snapshot(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: SnapshotInput = parse_input(input)?;
|
|
to_value(&build_sheet_snapshot(sheet, &input.report))
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Anatomy (R3)
|
|
|
|
#[derive(Deserialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct CanvasViewInput {
|
|
pub view_id: String,
|
|
}
|
|
|
|
/// The editor canvas of one view, as SVG text the browser parses.
|
|
#[derive(serde::Serialize)]
|
|
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
|
|
pub struct CanvasView {
|
|
pub svg: String,
|
|
}
|
|
|
|
/// A composed view larger than this is refused (plan R3 C2: output bounded; the product
|
|
/// drawing composes to 143 KiB).
|
|
pub const MAX_COMPOSED_BYTES: usize = 4 * 1024 * 1024;
|
|
|
|
fn view_canvas(sheet: &LoadedSheet, input: &str) -> Outcome {
|
|
let input: CanvasViewInput = parse_input(input)?;
|
|
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, 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, view_id, drawing).map_err(|e| match e {
|
|
ComposeError::UnknownView => Failure::new("unknown_view", view_id),
|
|
ComposeError::InvalidCharacter => Failure::new("invalid_character", view_id),
|
|
ComposeError::UnscopedReference => Failure::new("svg_rejected", "unscoped_reference"),
|
|
ComposeError::ReservedId => Failure::new("svg_rejected", "reserved_id"),
|
|
ComposeError::RootVisibility => Failure::new("svg_rejected", "root_visibility"),
|
|
})?;
|
|
let svg = serialize(&canvas);
|
|
if svg.len() > MAX_COMPOSED_BYTES {
|
|
return Err(Failure::new("svg_rejected", "too_large"));
|
|
}
|
|
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)
|
|
})
|
|
}
|