chore(workspace): Rust workspace R0 — builder image, core crate (JS-compatible JSON, report contracts, facade), wasm facade, core-wasm package with proofs

This commit is contained in:
bchanot committed 2026-10-13 00:01:25 +02:00
1 parent 5fec0654d3
commit 2a38fa37b5
39 files changed
+1913 -1

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
//! Data contracts of the core.
//!
//! R0 carries the Report v3 reference types (sheet reference, zone, vertebra) to prove the
//! serialisation rules against the current Zod schemas; the full contracts and the rules
//! arrive at R2 (review Part VI.2).
pub mod report;
pub use report::{LateralSide, ReportZone, SheetRef, Unresolved, Vertebra};
+137
View File
@@ -0,0 +1,137 @@
//! Report v3 reference types (`packages/domain/src/report/v3.ts`), field order as the Zod
//! schemas declare it. Optional fields are absent when unset and nullable fields are `null`
//! (review I.2): the serde attributes below are the contract, not a convenience.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "ts")]
use ts_rs::TS;
/// Reference of the anatomical sheet a report was written against (`Report.sheet`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SheetRef {
pub sheet_id: String,
/// Database version id once the sheet lives in the database; `null` for a bundled draft.
pub version_id: Option<String>,
/// sha256 of the document file the report was written against.
pub document_sha256: String,
}
/// Side of a bilateral zone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum LateralSide {
Left,
Right,
}
/// One vertebra of a spine zone: the region code and the 1-based index in that region.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Vertebra {
pub region: String,
pub index: u32,
}
/// A zone of an observation. Unknown keys are ignored on input, as the Zod schema strips
/// them; optional fields are written only when set.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportZone {
pub annotation_id: String,
pub view_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
/// Annotation name at selection time (or legacy name at migration).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_fr_snapshot: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_en_snapshot: Option<String>,
/// Set by the migration when the legacy id has no canonical annotation.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional, type = "true"))]
pub unresolved: Option<Unresolved>,
}
/// The literal `true` flag of a zone or finding the sheet cannot place
/// (`z.literal(true).optional()` in Zod).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Unresolved;
impl Serialize for Unresolved {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bool(true)
}
}
impl<'de> Deserialize<'de> for Unresolved {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if bool::deserialize(deserializer)? {
Ok(Unresolved)
} else {
Err(D::Error::custom(
"unresolved must be the literal true when present",
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json::to_js_pretty;
#[test]
fn optional_fields_are_absent_and_nullable_fields_are_null() {
let zone = ReportZone {
annotation_id: "hip".to_owned(),
view_id: "main".to_owned(),
..ReportZone::default()
};
let Ok(text) = to_js_pretty(&zone) else {
panic!("serialisation failed");
};
assert_eq!(
text,
"{\n \"annotationId\": \"hip\",\n \"viewId\": \"main\"\n}"
);
let sheet = SheetRef {
sheet_id: "faunosteo-cheval".to_owned(),
version_id: None,
document_sha256: "0".repeat(64),
};
let Ok(text) = to_js_pretty(&sheet) else {
panic!("serialisation failed");
};
assert!(text.contains("\"versionId\": null"));
}
#[test]
fn unresolved_accepts_true_only() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":true}"#);
assert_eq!(parsed.ok().and_then(|z| z.unresolved), Some(Unresolved));
let refused: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":false}"#);
assert!(refused.is_err());
}
#[test]
fn unknown_keys_are_ignored_like_the_zod_strip_schema() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","extra":1}"#);
assert!(parsed.is_ok());
}
}
+90
View File
@@ -0,0 +1,90 @@
//! The call surface the wasm facade and the tools expose (review III.3): one operation
//! name, one JSON text in, one JSON text out, closed outcome kinds, never a panic on
//! content. The envelope is `{"ok":true,"value":…}` or `{"ok":false,"kind":…,"detail":…}`.
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use crate::domain::{ReportZone, SheetRef};
use crate::json::pretty_js_round_trip;
/// Runs the operation `op` on the JSON text `input` and returns the outcome envelope.
///
/// Operations of R0: `core_version`, `pretty_json` (JavaScript pretty form of any JSON
/// text), `sheet_ref` and `report_zone` (parse and re-emit a contract type).
pub fn call(op: &str, input: &str) -> String {
let outcome = match op {
"core_version" => Ok(Value::String(crate::CORE_VERSION.to_owned())),
"pretty_json" => pretty_js_round_trip(input)
.map(Value::String)
.map_err(|error| Failure::new("invalid_json", error)),
"sheet_ref" => echo::<SheetRef>(input),
"report_zone" => echo::<ReportZone>(input),
_ => Err(Failure::new(
"unknown_op",
format!("no operation named {op}"),
)),
};
render(outcome)
}
fn echo<T: DeserializeOwned + Serialize>(input: &str) -> Result<Value, Failure> {
let parsed: T =
serde_json::from_str(input).map_err(|error| Failure::new("invalid_shape", error))?;
serde_json::to_value(parsed).map_err(|error| Failure::new("internal", error))
}
struct Failure {
kind: &'static str,
detail: String,
}
impl Failure {
fn new(kind: &'static str, detail: impl std::fmt::Display) -> Self {
Self {
kind,
detail: detail.to_string(),
}
}
}
fn render(outcome: Result<Value, Failure>) -> String {
let envelope = match outcome {
Ok(value) => json!({ "ok": true, "value": value }),
Err(failure) => json!({ "ok": false, "kind": failure.kind, "detail": failure.detail }),
};
serde_json::to_string(&envelope).unwrap_or_else(|_| {
r#"{"ok":false,"kind":"internal","detail":"outcome serialisation failed"}"#.to_owned()
})
}
#[cfg(test)]
mod tests {
use super::call;
#[test]
fn unknown_operation_is_a_closed_kind() {
let outcome = call("nope", "{}");
assert!(outcome.contains(r#""ok":false"#));
assert!(outcome.contains(r#""kind":"unknown_op""#));
}
#[test]
fn invalid_json_never_panics() {
let outcome = call("pretty_json", "{ not json");
assert!(outcome.contains(r#""kind":"invalid_json""#));
}
#[test]
fn report_zone_round_trip_keeps_the_declared_order() {
let outcome = call(
"report_zone",
r#"{"viewId":"v","side":"left","annotationId":"a"}"#,
);
assert_eq!(
outcome,
r#"{"ok":true,"value":{"annotationId":"a","viewId":"v","side":"left"}}"#
);
}
}
+227
View File
@@ -0,0 +1,227 @@
//! JSON output with JavaScript number semantics.
//!
//! `JSON.stringify(value, null, 2)` and `serde_json`'s pretty printer agree on everything
//! (two-space indent, `": "`, `[]` and `{}` for empty containers, raw non-ASCII, `\u00XX`
//! control escapes) except finite floats: JavaScript prints `1523` for `1523.0` and `1e+21`
//! for `1e21`, `serde_json` prints `1523.0` and `1e21`. The documents of the repository carry
//! integer-valued coordinates as floats, so the archive attachment and the generated seed
//! files need the JavaScript form (review I.2, D-R11).
use std::io;
use serde::Serialize;
use serde_json::ser::{Formatter, PrettyFormatter};
/// Formats a finite `f64` exactly as ECMAScript `Number::toString(10)` does.
///
/// Non-finite values have no JSON form (`JSON.stringify` writes `null`): same here.
pub fn js_number(value: f64) -> String {
if !value.is_finite() {
return "null".to_owned();
}
if value == 0.0 {
return "0".to_owned();
}
let (digits, point) = shortest_digits(value.abs());
let mut out = String::with_capacity(digits.len() + 8);
if value.is_sign_negative() {
out.push('-');
}
write_decimal(&mut out, &digits, point);
out
}
/// Shortest round-trip digits of a positive finite value and the position `n` of the
/// decimal point relative to the first digit (ECMAScript's `n`): value = 0.d₁d₂… × 10ⁿ.
///
/// Rust's `LowerExp` prints the shortest round-trip mantissa (`1.7154285714285713e3`),
/// chosen by the same rule as ECMAScript (shortest, then closest to the value).
fn shortest_digits(value: f64) -> (String, i32) {
let scientific = format!("{value:e}");
let (mantissa, exponent) = scientific
.split_once('e')
.unwrap_or((scientific.as_str(), "0"));
let exponent: i32 = exponent.parse().unwrap_or(0);
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
(digits, exponent + 1)
}
/// ECMAScript Number::toString steps 6 to 10 for `k` digits and point position `n`.
fn write_decimal(out: &mut String, digits: &str, n: i32) {
let k = i32::try_from(digits.len()).unwrap_or(i32::MAX);
if k <= n && n <= 21 {
out.push_str(digits);
out.extend(std::iter::repeat_n('0', (n - k).unsigned_abs() as usize));
} else if 0 < n && n <= 21 {
let (integer, fraction) = digits.split_at(n.unsigned_abs() as usize);
out.push_str(integer);
out.push('.');
out.push_str(fraction);
} else if -6 < n && n <= 0 {
out.push_str("0.");
out.extend(std::iter::repeat_n('0', n.unsigned_abs() as usize));
out.push_str(digits);
} else {
let (first, rest) = digits.split_at(1);
out.push_str(first);
if !rest.is_empty() {
out.push('.');
out.push_str(rest);
}
let exponent = n - 1;
out.push('e');
out.push(if exponent < 0 { '-' } else { '+' });
out.push_str(&exponent.unsigned_abs().to_string());
}
}
/// `serde_json`'s pretty formatter with JavaScript float printing.
pub struct JsPrettyFormatter<'a> {
inner: PrettyFormatter<'a>,
}
impl Default for JsPrettyFormatter<'_> {
fn default() -> Self {
Self {
inner: PrettyFormatter::new(),
}
}
}
impl Formatter for JsPrettyFormatter<'_> {
fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
where
W: ?Sized + io::Write,
{
writer.write_all(js_number(f64::from(value)).as_bytes())
}
fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
where
W: ?Sized + io::Write,
{
writer.write_all(js_number(value).as_bytes())
}
fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.begin_array(writer)
}
fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.end_array(writer)
}
fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.begin_array_value(writer, first)
}
fn end_array_value<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.end_array_value(writer)
}
fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.begin_object(writer)
}
fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.end_object(writer)
}
fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.begin_object_key(writer, first)
}
fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.begin_object_value(writer)
}
fn end_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.inner.end_object_value(writer)
}
}
/// Serialises `value` as `JSON.stringify(value, null, 2)` would (no trailing newline).
pub fn to_js_pretty<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, JsPrettyFormatter::default());
value.serialize(&mut serializer)?;
String::from_utf8(buffer).map_err(<serde_json::Error as serde::ser::Error>::custom)
}
/// Parses JSON text and re-emits it in the JavaScript pretty form, keeping the key order.
pub fn pretty_js_round_trip(text: &str) -> Result<String, serde_json::Error> {
let value: serde_json::Value = serde_json::from_str(text)?;
to_js_pretty(&value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn integer_valued_floats_print_without_a_fraction() {
assert_eq!(js_number(1523.0), "1523");
assert_eq!(js_number(-7.0), "-7");
assert_eq!(
js_number(123_456_789_012_345_680_000.0),
"123456789012345680000"
);
}
#[test]
fn fractions_and_small_values_follow_the_javascript_thresholds() {
assert_eq!(js_number(0.85), "0.85");
assert_eq!(js_number(1_715.428_571_428_571_3), "1715.4285714285713");
assert_eq!(js_number(0.000_001), "0.000001");
assert_eq!(js_number(0.000_000_1), "1e-7");
assert_eq!(js_number(1e21), "1e+21");
assert_eq!(js_number(1.5e300), "1.5e+300");
assert_eq!(js_number(5e-324), "5e-324");
}
#[test]
fn zero_and_non_finite_values() {
assert_eq!(js_number(0.0), "0");
assert_eq!(js_number(-0.0), "0");
assert_eq!(js_number(f64::NAN), "null");
assert_eq!(js_number(f64::INFINITY), "null");
}
#[test]
fn pretty_output_matches_the_javascript_shape() {
let text = r#"{"b":[1,2.0,{"c":[]}],"a":{},"d":"é\u0001","e":-0.0}"#;
let expected = "{\n \"b\": [\n 1,\n 2,\n {\n \"c\": []\n }\n ],\n \"a\": {},\n \"d\": \"é\\u0001\",\n \"e\": 0\n}";
let Ok(actual) = pretty_js_round_trip(text) else {
panic!("round trip failed");
};
assert_eq!(actual, expected);
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Faunosteo core library (plan R0, `docs/development/RUST_ARCHITECTURE_REVIEW.md`).
//!
//! Rules of the crate (review Part III.3): no I/O, no clock, no random ids; every input
//! is bytes or JSON text, every output is plain data. The same code serves the browser
//! (`crates/wasm`), the worker and the tools. R0 ships the serialisation rules and the
//! first contract types; the business rules arrive with R2.
pub mod domain;
pub mod facade;
pub mod json;
/// Version of the core, reported by the wasm facade and the worker.
pub const CORE_VERSION: &str = env!("CARGO_PKG_VERSION");