Files
faunosteo/crates/core/src/ops.rs
T
bchanot 52471dbbc0 feat(domain): R4.3a FileBytes sink and the bytes entries of the wasm facade
FileBytes gathers a file chunk by chunk in linear memory (capacity reserved from the
announced size, refused above the PDF cap); SheetHandle.import_pdf_bytes and
restore_copy_bytes consume it, so the worker streams file.stream() and the file lives
once, never as a JavaScript ArrayBuffer nor as a JSON-wrapped string. restore_copy:
strict UTF-8, one BOM, the OD-3 budget, draft.restore's kinds. Node: same envelopes as
import_pdf on the 51 O8 cases; rescue-copy parity with draft.restore.
2026-10-18 17:45:39 +02:00

410 lines
14 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::{LoadedSheet, SheetIndexData, check_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),
"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),
_ => 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)
}
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)?;
let document = &sheet.document;
if !document.views.iter().any(|v| v.id() == input.view_id) {
return Err(Failure::new("unknown_view", &input.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) {
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 svg = serialize(&canvas);
if svg.len() > MAX_COMPOSED_BYTES {
return Err(Failure::new("svg_rejected", "too_large"));
}
to_value(&CanvasView { svg })
}