feat(workspace): R2 facade operations for the editor rules, the publish check and the sheet index data

Free ops: sheet.check, report.new, report.add_observation,
report.remove_observation, report.move_observation, vertebra.select.
Sheet ops: index_data, zone.click, zone.add_sides, zone.remove_at,
vertebra.initial, vertebra.sync, finding.toggle. Input contracts exported
to TypeScript; a JavaScript index that names no position removes nothing
in the filters and is refused by the move (the TypeScript swap would have
written a hole). Shipped module 999 KB raw, 319 KB gzip (budget 600 KB).
This commit is contained in:
bchanot committed 2026-10-14 00:19:20 +02:00
1 parent 3639c8778e
commit 6c0533c1da
25 files changed
+470 -11

No files matched your search

+3 -7
View File
@@ -42,7 +42,7 @@ pub fn call(op: &str, input: &str) -> String {
.map_err(|error| Failure::new("invalid_json", error)),
"sheet_ref" => echo::<SheetRef>(input),
"report_zone" => echo::<ReportZone>(input),
_ => Err(unknown(op)),
_ => crate::ops::free(op, input).unwrap_or_else(|| Err(unknown(op))),
};
render(outcome)
}
@@ -57,12 +57,8 @@ pub fn load_sheet(bundle: &str) -> Result<LoadedSheet, Failure> {
}
/// Runs the operation `op` that needs the session's sheet.
pub fn call_with_sheet(sheet: &LoadedSheet, op: &str, _input: &str) -> String {
let outcome = match op {
"sheet.ref" => to_value(&sheet.reference),
_ => Err(unknown(op)),
};
render(outcome)
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))))
}
fn unknown(op: &str) -> Failure {
+1
View File
@@ -8,6 +8,7 @@
pub mod domain;
pub mod facade;
pub mod json;
pub mod ops;
/// Version of the core, reported by the wasm facade and the worker.
pub const CORE_VERSION: &str = env!("CARGO_PKG_VERSION");
+276
View File
@@ -0,0 +1,276 @@
//! 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::domain::editor::{
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
};
use crate::domain::report::{LateralSide, Observation, Report, SheetRef, Vertebra};
use crate::domain::sheet::{LoadedSheet, SheetIndexData, check_sheet_document};
use crate::facade::{Failure, parse_input, to_value};
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: Value = parse_input(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),
_ => 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))
}
+4 -4
View File
@@ -87,18 +87,18 @@ describe('core runtime', () => {
const runtime = new CoreRuntime(countingSource())
await runtime.ready()
const sheet = runtime.sheet(BUNDLE)
expect(sheet.call('sheet.ref', '')).toMatchObject({
expect(sheet.call('index_data', '')).toMatchObject({
ok: true,
value: { sheetId: 'sheet', versionId: null },
value: { ref: { sheetId: 'sheet', versionId: null } },
})
trap(runtime)
expect(sheet.call('sheet.ref', '')).toMatchObject({
expect(sheet.call('index_data', '')).toMatchObject({
kind: 'core_unavailable',
})
await runtime.ready()
// A call through the stack-trapped instance would fail in its allocator and poison
// again: one generation more and a ready runtime prove the handle was rebuilt.
expect(sheet.call('sheet.ref', '')).toMatchObject({ ok: true })
expect(sheet.call('index_data', '')).toMatchObject({ ok: true })
expect(runtime.generation).toBe(2)
expect(runtime.status).toBe('ready')
})
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LateralSide } from "./LateralSide";
import type { Observation } from "./Observation";
export type AddSidesInput = { observation: Observation, annotationId: string, sides: Array<LateralSide>, };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { JsIndex } from "./JsIndex";
import type { LateralSide } from "./LateralSide";
import type { Observation } from "./Observation";
export type FindingToggleInput = { observation: Observation, findingZoneId: string, path: Array<string>, leafPosition: JsIndex, side?: LateralSide, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* An index as JavaScript sent it: a number. Only a non-negative integer names a position.
*/
export type JsIndex = number;
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type MoveDirection = "up" | "down";
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { JsIndex } from "./JsIndex";
import type { MoveDirection } from "./MoveDirection";
import type { Report } from "./Report";
export type MoveObservationInput = { report: Report, index: JsIndex, direction: MoveDirection, };
@@ -0,0 +1,12 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Animal } from "./Animal";
import type { NextAppointment } from "./NextAppointment";
import type { Observation } from "./Observation";
import type { Owner } from "./Owner";
import type { Practitioner } from "./Practitioner";
/**
* What a new report needs before version, id, dates and the sheet are stamped
* (`Omit<Report, 'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'>`).
*/
export type NewReportDraft = { date: string, practitioner: Practitioner, animal: Animal, owner: Owner, observations: Array<Observation>, conclusion: string, recommendations: string, nextAppointment?: NextAppointment, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { NewReportDraft } from "./NewReportDraft";
import type { SheetRef } from "./SheetRef";
export type NewReportInput = { draft: NewReportDraft, sheet: SheetRef, id: string, createdAt: string, observationId: string, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { JsIndex } from "./JsIndex";
import type { Observation } from "./Observation";
export type ObservationIndexInput = { observation: Observation, index: JsIndex, };
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Report } from "./Report";
export type ReportIdInput = { report: Report, id: string, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { JsIndex } from "./JsIndex";
import type { Report } from "./Report";
export type ReportIndexInput = { report: Report, index: JsIndex, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SheetIssue } from "./SheetIssue";
/**
* The issues of a shape-valid document and whether they allow publication.
*/
export type SheetCheck = { issues: Array<SheetIssue>, publishable: boolean, };
@@ -0,0 +1,39 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AnatomicalSheetDocument } from "./AnatomicalSheetDocument";
import type { LocalizedText } from "./LocalizedText";
import type { SheetRef } from "./SheetRef";
import type { SheetStatus } from "./SheetStatus";
export type SheetIndexData = { status: SheetStatus, ref: SheetRef, speciesId: string, schemaVersion: number,
/**
* The first `main` view of the document.
*/
mainViewId: string,
/**
* The document as parsed (defaults filled in).
*/
document: AnatomicalSheetDocument,
/**
* Position in `document.views` by id; the last duplicate wins.
*/
viewById: { [key in string]: number },
/**
* Position in `document.annotations` by id; the last duplicate wins.
*/
annotationById: { [key in string]: number },
/**
* Position in `document.finding_zones` by id; the last duplicate wins.
*/
findingZoneById: { [key in string]: number },
/**
* Display name of every annotation id (a trigger: its own, else its view's).
*/
names: { [key in string]: LocalizedText },
/**
* Ids that open the vertebra picker, in document order, each once.
*/
spineIds: Array<string>,
/**
* Every finding path the sheet holds, as the JSON text of `[zoneId, ...path]`.
*/
nodeKeys: Array<string>, };
+4
View File
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SheetIssueSeverity } from "./SheetIssueSeverity";
export type SheetIssue = { code: string, severity: SheetIssueSeverity, path: string, message: string, };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SheetIssueSeverity = "error" | "warning";
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* One tap of the picker.
*/
export type VertebraAction = { "kind": "toggle", region: string, index: number, } | { "kind": "all", region: string, count: number, } | { "kind": "none", region: string, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Vertebra } from "./Vertebra";
import type { VertebraAction } from "./VertebraAction";
export type VertebraSelectInput = { selection: Array<Vertebra>, action: VertebraAction, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Observation } from "./Observation";
import type { Vertebra } from "./Vertebra";
export type VertebraSyncInput = { observation: Observation, selection: Array<Vertebra>, viewId: string, };
+30
View File
@@ -0,0 +1,30 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LateralSide } from "./LateralSide";
import type { Observation } from "./Observation";
import type { Vertebra } from "./Vertebra";
import type { ZoneClickKind } from "./ZoneClickKind";
/**
* What a click on an annotation did, with what the editor needs to follow it up.
*/
export type ZoneClick = { kind: ZoneClickKind,
/**
* `open_view`: the detail view to open.
*/
viewId?: string,
/**
* The active observation after the click, when the click changed it.
*/
observation?: Observation,
/**
* `open_vertebra_picker`: the zone the picker edits.
*/
zoneIndex?: number,
/**
* `open_laterality_picker`: the sides already recorded.
*/
sidesPresent?: Array<LateralSide>,
/**
* `open_vertebra_picker`: the picker's initial selection.
*/
vertebrae?: Array<Vertebra>, };
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Observation } from "./Observation";
export type ZoneClickInput = { observation: Observation | null, annotationId: string, };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* The kind of a click decision (`ZoneClickDecision.kind`).
*/
export type ZoneClickKind = "ignore" | "open_view" | "activate_fallback" | "open_vertebra_picker" | "open_laterality_picker" | "remove_both_sides" | "toggle";
+20
View File
@@ -1,6 +1,7 @@
// Types of the core contracts, generated by ts-rs from crates/core (`pnpm rust:check`
// regenerates them; the drift gate fails when the committed files differ from the Rust structs).
// This index lists every generated file: tests/types-index.test.ts keeps it complete.
export type { AddSidesInput } from './AddSidesInput'
export type { AnatomicalSheetDocument } from './AnatomicalSheetDocument'
export type { Animal } from './Animal'
export type { AnnotationCategory } from './AnnotationCategory'
@@ -15,21 +16,28 @@ export type { DetailView } from './DetailView'
export type { FindingCategoryKind } from './FindingCategoryKind'
export type { FindingCategory } from './FindingCategory'
export type { FindingNode } from './FindingNode'
export type { FindingToggleInput } from './FindingToggleInput'
export type { Finding } from './Finding'
export type { FindingZone } from './FindingZone'
export type { Geometry } from './Geometry'
export type { ImageAsset } from './ImageAsset'
export type { JsIndex } from './JsIndex'
export type { Laterality } from './Laterality'
export type { LateralSide } from './LateralSide'
export type { Locale } from './Locale'
export type { LocalizedOptionalText } from './LocalizedOptionalText'
export type { LocalizedText } from './LocalizedText'
export type { MainView } from './MainView'
export type { MoveDirection } from './MoveDirection'
export type { MoveObservationInput } from './MoveObservationInput'
export type { NewReportDraft } from './NewReportDraft'
export type { NewReportInput } from './NewReportInput'
export type { NextAppointmentDate } from './NextAppointmentDate'
export type { NextAppointmentPeriod } from './NextAppointmentPeriod'
export type { NextAppointment } from './NextAppointment'
export type { ObservableAnnotation } from './ObservableAnnotation'
export type { ObservableKind } from './ObservableKind'
export type { ObservationIndexInput } from './ObservationIndexInput'
export type { Observation } from './Observation'
export type { Owner } from './Owner'
export type { PathGeometry } from './PathGeometry'
@@ -42,10 +50,16 @@ export type { Practitioner } from './Practitioner'
export type { Reference } from './Reference'
export type { ReferenceType } from './ReferenceType'
export type { ReportArchiveEnvelope } from './ReportArchiveEnvelope'
export type { ReportIdInput } from './ReportIdInput'
export type { ReportIndexInput } from './ReportIndexInput'
export type { Report } from './Report'
export type { ReportZone } from './ReportZone'
export type { ReviewStatus } from './ReviewStatus'
export type { Severity } from './Severity'
export type { SheetCheck } from './SheetCheck'
export type { SheetIndexData } from './SheetIndexData'
export type { SheetIssueSeverity } from './SheetIssueSeverity'
export type { SheetIssue } from './SheetIssue'
export type { SheetRef } from './SheetRef'
export type { SheetSnapshotAsset } from './SheetSnapshotAsset'
export type { SheetSnapshotRef } from './SheetSnapshotRef'
@@ -53,7 +67,13 @@ export type { SheetSnapshot } from './SheetSnapshot'
export type { SheetStatus } from './SheetStatus'
export type { SheetView } from './SheetView'
export type { SvgAsset } from './SvgAsset'
export type { VertebraAction } from './VertebraAction'
export type { VertebralConfig } from './VertebralConfig'
export type { VertebralRegion } from './VertebralRegion'
export type { VertebraSelectInput } from './VertebraSelectInput'
export type { VertebraSyncInput } from './VertebraSyncInput'
export type { Vertebra } from './Vertebra'
export type { ViewBox } from './ViewBox'
export type { ZoneClickInput } from './ZoneClickInput'
export type { ZoneClickKind } from './ZoneClickKind'
export type { ZoneClick } from './ZoneClick'