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

+10
View File
@@ -0,0 +1,10 @@
# Workspace-level Cargo configuration (RUST_ARCHITECTURE_REVIEW III.3, III.5).
[target.wasm32-unknown-unknown]
# The shadow stack of the browser module, set explicitly (the toolchain default is also
# 1 MiB). packages/core-wasm/tests/panic.test.ts proves that exhausting it traps.
rustflags = ["-C", "link-arg=-zstack-size=1048576"]
[env]
# ts-rs writes the TypeScript types of the contracts here on `cargo test -p faunosteo-core --features ts`.
TS_RS_EXPORT_DIR = { value = "packages/core-wasm/types", relative = true }
+2
View File
@@ -18,3 +18,5 @@ graphify-out/
.gitea/
docs/
logos/
target/
packages/core-wasm/pkg/
+4
View File
@@ -59,3 +59,7 @@ graphify-out/
# Supabase CLI local state (written by supabase start / db reset)
supabase/.branches/
supabase/.temp/
# Rust workspace (R0): build output and the generated browser module
target/
packages/core-wasm/pkg/
Generated
+587
View File
@@ -0,0 +1,587 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bumpalo"
version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "cc"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
dependencies = [
"cfg-if",
]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "faunosteo-core"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"ts-rs",
]
[[package]]
name = "faunosteo-wasm"
version = "0.1.0"
dependencies = [
"faunosteo-core",
"wasm-bindgen",
]
[[package]]
name = "faunosteo-worker"
version = "0.1.0"
dependencies = [
"crc32fast",
"image",
"libc",
"libwebp-sys",
"rlimit",
"seccompiler",
]
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"libc",
]
[[package]]
name = "libc"
version = "0.2.190"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
[[package]]
name = "libwebp-sys"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b3a87b44e34d17161e4f17d92a463d596cb13825dcd1758ed18fd3a721e189c"
dependencies = [
"cc",
"glob",
"pkg-config",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rlimit"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f35ee2729c56bb610f6dba436bf78135f728b7373bdffae2ec815b2d3eb98cc3"
dependencies = [
"libc",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "seccompiler"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae55de56877481d112a559bbc12667635fdaf5e005712fd4e2b2fa50ffc884"
dependencies = [
"libc",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash",
"indexmap",
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "ts-rs"
version = "12.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
dependencies = [
"thiserror",
"ts-rs-macros",
]
[[package]]
name = "ts-rs-macros"
version = "12.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"termcolor",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 3.0.9",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]
+56
View File
@@ -0,0 +1,56 @@
# Faunosteo Rust workspace (plan R0, docs/development/RUST_ARCHITECTURE_REVIEW.md Part III).
# Three crates: core (feature-gated library), wasm (browser facade), worker (service binary).
# Every command runs through the builder image: docs/development/RUST.md.
[workspace]
resolver = "3"
members = ["crates/core", "crates/wasm", "crates/worker"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
rust-version = "1.99"
publish = false
# The path dependency on crates/core is declared per crate (`path = "../core"`): cargo-deny
# 0.20 reads a workspace-inherited path dependency as a wildcard and fails the bans check.
[workspace.dependencies]
serde = { version = "1.0.229", features = ["derive"] }
# preserve_order keeps the input key order of parsed documents (JSON.stringify semantics).
# float_roundtrip: the default parser is a fast path that can be one ULP off (found by the R0
# proof: 1715.4285714285713 came back as 1715.428571428571); JavaScript parses correctly.
serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] }
ts-rs = { version = "12.0", features = ["serde-compat"] }
# The CLI in docker/rust-builder.Dockerfile must be this exact version.
wasm-bindgen = "=0.2.129"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] }
libwebp-sys = "0.14.4"
seccompiler = "0.5.0"
rlimit = "0.11"
libc = "0.2"
# The library crates deny unwrap/expect so that no panic path depends on content;
# the worker binary relaxes disallowed_methods (it owns I/O) in its own [lints].
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
unwrap_used = "deny"
expect_used = "deny"
disallowed_methods = "deny"
# Dependencies optimised even in debug builds: the sandbox tests decode 4096² images under a
# 10 s CPU limit, which an unoptimised image decoder does not meet.
[profile.dev.package."*"]
opt-level = 3
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
# The worker child dies on a panic (the parent logs it); on wasm32 the std is abort anyway.
panic = "abort"
strip = "symbols"
[profile.release.package.faunosteo-wasm]
opt-level = "z"
+14
View File
@@ -0,0 +1,14 @@
# The core library never reads the clock, the file system or the environment: ids, time
# and bytes are inputs (RUST_ARCHITECTURE_REVIEW III.3). Tests and the worker binary
# allow these lints locally where they own I/O.
disallowed-methods = [
{ path = "std::time::SystemTime::now", reason = "the core takes time as an input" },
{ path = "std::time::Instant::now", reason = "the core takes time as an input" },
{ path = "std::fs::read", reason = "the core takes bytes as inputs" },
{ path = "std::fs::read_to_string", reason = "the core takes bytes as inputs" },
{ path = "std::fs::write", reason = "the core returns bytes, the caller writes" },
{ path = "std::fs::File::open", reason = "the core takes bytes as inputs" },
{ path = "std::fs::File::create", reason = "the core returns bytes, the caller writes" },
{ path = "std::env::var", reason = "configuration is injected into the core" },
{ path = "std::env::var_os", reason = "configuration is injected into the core" },
]
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "faunosteo-core"
description = "Faunosteo core: data contracts, rules and parsers shared by the browser (wasm), the worker and the tools"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish.workspace = true
[lib]
path = "src/lib.rs"
[features]
default = []
# Exports the TypeScript types of the contracts (ts-rs) on `cargo test -p faunosteo-core --features ts`.
ts = ["dep:ts-rs"]
[dependencies]
serde.workspace = true
serde_json.workspace = true
ts-rs = { workspace = true, optional = true }
[lints]
workspace = true
+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");
+39
View File
@@ -0,0 +1,39 @@
//! R0 proof (half of it): the JavaScript pretty form is idempotent on the real documents and
//! prints no integer-valued float with a fraction. The other half, byte equality against
//! `JSON.stringify(JSON.parse(text), null, 2)`, runs in `packages/core-wasm/tests` on the
//! same files through the wasm build.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
use faunosteo_core::json::pretty_js_round_trip;
fn fixture(relative: &str) -> String {
let path = format!("{}/../../{relative}", env!("CARGO_MANIFEST_DIR"));
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{path}: {error}"))
}
fn assert_round_trip(relative: &str) -> String {
let text = fixture(relative);
let once = pretty_js_round_trip(&text).expect("first pass");
let twice = pretty_js_round_trip(&once).expect("second pass");
assert_eq!(
once, twice,
"{relative}: the pretty form must be a fixed point"
);
assert!(
!once.contains(".0,") && !once.contains(".0\n"),
"{relative}: a float printed as x.0"
);
once
}
#[test]
fn demo_report_v3_round_trips() {
let text = assert_round_trip("apps/app/tests/fixtures/report-v3.demo.json");
assert!(text.starts_with("{\n \"version\": 3,\n"));
}
#[test]
fn equine_draft_document_round_trips() {
let text = assert_round_trip("supabase/seed/anatomical-sheets/equine/draft/document.json");
assert!(text.contains("\"schema_version\": 2"));
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "faunosteo-wasm"
description = "Browser facade of the Faunosteo core (wasm-bindgen), built into packages/core-wasm/pkg"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish.workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
path = "src/lib.rs"
[dependencies]
faunosteo-core = { path = "../core" }
wasm-bindgen.workspace = true
[lints]
workspace = true
+43
View File
@@ -0,0 +1,43 @@
//! wasm-bindgen facade over `faunosteo-core` (review III.3): JSON strings in and out, closed
//! outcome kinds. Built by `docker/wasm-build.sh` into `packages/core-wasm/pkg`; loaded
//! lazily by the application from R2 on (never at R0).
use wasm_bindgen::prelude::wasm_bindgen;
/// Version of the core compiled into this module.
#[wasm_bindgen]
pub fn core_version() -> String {
faunosteo_core::CORE_VERSION.to_owned()
}
/// Runs one core operation: `op` names it, `input` is its JSON text, the result is the
/// JSON text of the outcome envelope (`{"ok":true,"value":…}` or `{"ok":false,"kind":…}`).
#[wasm_bindgen]
pub fn call(op: &str, input: &str) -> String {
faunosteo_core::facade::call(op, input)
}
/// R0 proof: on wasm32 a panic is a trap (panic = abort), reaching JavaScript as a
/// `WebAssembly.RuntimeError`; the caller re-instantiates the module.
#[wasm_bindgen]
pub fn panic_for_test() {
panic!("deliberate panic for the R0 proof");
}
/// R0 proof: exhausting the shadow stack traps instead of corrupting memory.
#[wasm_bindgen]
pub fn recurse_for_test(depth: u32) -> u32 {
recurse(depth)
}
#[inline(never)]
fn recurse(depth: u32) -> u32 {
let mut frame = [depth; 32];
if depth == 0 {
return std::hint::black_box(&frame)[0];
}
let below = recurse(depth - 1);
frame[(below as usize) % 32] ^= below;
std::hint::black_box(&frame);
below.wrapping_add(1)
}
+46
View File
@@ -0,0 +1,46 @@
# cargo-deny policy (RUST_ARCHITECTURE_REVIEW Part V). `cargo deny check licenses bans sources`
# blocks in CI; `cargo deny check advisories` runs in the nightly job and at release time, so
# an unrelated advisory publication never reddens every branch.
[graph]
targets = [
{ triple = "x86_64-unknown-linux-gnu" },
{ triple = "x86_64-unknown-linux-musl" },
{ triple = "wasm32-unknown-unknown" },
]
all-features = true
[advisories]
yanked = "deny"
ignore = []
[licenses]
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Unicode-3.0",
"Zlib",
"MPL-2.0",
"CC0-1.0",
"Unlicense",
"BSL-1.0",
]
confidence-threshold = 0.9
[licenses.private]
ignore = true
[bans]
multiple-versions = "warn"
wildcards = "deny"
# The workspace path dependency on crates/core has no version requirement: not a wildcard.
allow-wildcard-paths = true
highlight = "all"
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
+27
View File
@@ -0,0 +1,27 @@
# Faunosteo reference Rust build environment (plan R0, RUST_ARCHITECTURE_REVIEW Annex B).
# Every Rust command of the repository runs through this image (CI and local), so the
# toolchain is identical everywhere and the production VPS never needs Rust.
#
# docker build -f docker/rust-builder.Dockerfile -t faunosteo_rust_builder:1.99.0 docker
# bash docker/rust-run.sh cargo test --workspace --exclude faunosteo-worker
#
# The pinned versions below must match rust-toolchain.toml (channel) and Cargo.lock
# (wasm-bindgen crate): docker/wasm-build.sh refuses to run when they differ.
FROM rust:1.99.0-bookworm
ARG WASM_BINDGEN_VERSION=0.2.129
ARG CARGO_DENY_VERSION=0.20.2
# The wasm target is the browser build of crates/wasm.
RUN rustup target add wasm32-unknown-unknown
# Build tools compiled from crates.io at pinned versions with their own lockfiles.
RUN cargo install wasm-bindgen-cli --version "${WASM_BINDGEN_VERSION}" --locked \
&& cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked \
&& rm -rf /usr/local/cargo/registry
# The official image installs rustup's minimal profile: without this line every container
# would download rustfmt and clippy again (rust-toolchain.toml lists them as components).
RUN rustup component add rustfmt clippy
WORKDIR /w
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# The Rust quality gate, identical in CI and locally: `pnpm rust:check`.
# Runs inside the builder image (glibc). The worker's sandbox tests run in its own
# Alpine/musl image (crates/worker/Dockerfile, stage `test`) because the seccomp
# allowlist is derived for the musl static binary that ships.
set -euo pipefail
cd "$(dirname "$0")/.."
cargo fmt --all --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo test --workspace --exclude faunosteo-worker --locked
# Exports the TypeScript types of the contracts (ts-rs) into packages/core-wasm/types;
# CI fails on a diff so the committed types never drift from the Rust structs.
cargo test -p faunosteo-core --features ts --locked
cargo deny check licenses bans sources
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Runs a command inside the reference Rust builder image with the repository mounted
# at /w. Cargo's registry and the target directory live in named Docker volumes
# (faunosteo_ prefix, DEPLOY.md "Docker resource naming") so incremental builds stay
# fast across runs while the host needs no Rust toolchain.
#
# bash docker/rust-run.sh cargo test --workspace --exclude faunosteo-worker
# bash docker/rust-run.sh bash docker/wasm-build.sh
set -euo pipefail
IMAGE="${FAUNOSTEO_RUST_BUILDER:-faunosteo_rust_builder:1.99.0}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TTY_FLAG=()
if [ -t 0 ] && [ -t 1 ]; then
TTY_FLAG=(-t)
fi
exec docker run --rm -i "${TTY_FLAG[@]}" \
-v "$ROOT":/w \
-v faunosteo_cargo_registry:/usr/local/cargo/registry \
-v faunosteo_rust_target:/w/target \
-w /w \
"$IMAGE" "$@"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Builds the browser module of crates/wasm into packages/core-wasm/pkg (git-ignored).
# Runs inside the builder image: `pnpm wasm:build` or `bash docker/rust-run.sh bash docker/wasm-build.sh`.
# The wasm-bindgen CLI must be the exact version of the wasm-bindgen crate in Cargo.lock
# (wasm-bindgen >= 0.2.128 refuses a mismatch at runtime; we refuse it up front).
set -euo pipefail
cd "$(dirname "$0")/.."
lock_version="$(awk '/^name = "wasm-bindgen"$/ { getline; sub(/^version = "/, ""); sub(/"$/, ""); print; exit }' Cargo.lock)"
cli_version="$(wasm-bindgen --version | awk '{ print $2 }')"
if [ "$lock_version" != "$cli_version" ]; then
echo "wasm-bindgen crate ${lock_version} (Cargo.lock) != wasm-bindgen-cli ${cli_version} (builder image)" >&2
exit 1
fi
cargo build -p faunosteo-wasm --release --target wasm32-unknown-unknown --locked
out=packages/core-wasm/pkg
rm -rf "$out"
wasm-bindgen --target web --out-dir "$out" --out-name faunosteo_wasm \
target/wasm32-unknown-unknown/release/faunosteo_wasm.wasm
raw=$(wc -c < "$out/faunosteo_wasm_bg.wasm")
gz=$(gzip -9 -c "$out/faunosteo_wasm_bg.wasm" | wc -c)
echo "faunosteo_wasm_bg.wasm: ${raw} bytes raw, ${gz} bytes gzip -9"
+6 -1
View File
@@ -29,7 +29,12 @@
"db:types:check": "supabase gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts",
"assets:upload": "pnpm --filter @faunosteo/supabase assets:upload",
"build:preview": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build",
"preview:draft": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build && pnpm --filter @faunosteo/app preview"
"preview:draft": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build && pnpm --filter @faunosteo/app preview",
"rust:builder": "docker build -f docker/rust-builder.Dockerfile -t faunosteo_rust_builder:1.99.0 docker",
"rust:check": "bash docker/rust-run.sh bash docker/rust-check.sh",
"wasm:build": "bash docker/rust-run.sh bash docker/wasm-build.sh",
"worker:test": "docker build -f crates/worker/Dockerfile --target test -t faunosteo_worker:test .",
"worker:image": "docker build -f crates/worker/Dockerfile -t faunosteo_worker:dev ."
},
"devDependencies": {
"pnpm": "10.13.1",
+21
View File
@@ -0,0 +1,21 @@
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
// pkg/ is the wasm-bindgen output, types/ the ts-rs output: generated, never linted.
{ ignores: ['node_modules/**', 'pkg/**', 'types/**'] },
{
files: ['**/*.ts'],
extends: [...tseslint.configs.recommended],
languageOptions: {
globals: { ...globals.node, ...globals.es2022 },
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
},
},
)
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@faunosteo/core-wasm",
"version": "0.1.0",
"private": true,
"description": "Faunosteo core compiled to WebAssembly: loader, generated TypeScript types of the contracts, and the R0 proofs (panic, serialisation, size)",
"license": "MIT",
"type": "module",
"exports": {
".": "./src/index.ts",
"./types": "./types/index.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit"
},
"devDependencies": {
"@faunosteo/domain": "workspace:*",
"@types/node": "^20.19.41",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vitest": "^3.2.7"
}
}
+72
View File
@@ -0,0 +1,72 @@
/**
* Loader of the Faunosteo core module (wasm-bindgen `--target web` output under `pkg/`,
* built by `pnpm wasm:build`, git-ignored).
*
* The module is never imported statically: `pkg/` may be absent on a host without Docker,
* and the application loads the core lazily behind the paths that need it (review III.3).
* No file of this package is reachable from the application before R2.
*/
import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
/** The functions the module exports (mirror of `pkg/faunosteo_wasm.d.ts`). */
export interface CoreModule {
core_version(): string
call(op: string, input: string): string
panic_for_test(): void
recurse_for_test(depth: number): number
}
/** Outcome envelope of every `call` (closed kinds, never an exception for content). */
export type CoreOutcome<T = unknown> =
| { ok: true; value: T }
| { ok: false; kind: string; detail?: string }
const PKG_JS = new URL('../pkg/faunosteo_wasm.js', import.meta.url)
const PKG_WASM = new URL('../pkg/faunosteo_wasm_bg.wasm', import.meta.url)
interface PkgModule extends CoreModule {
default(input: { module_or_path: BufferSource }): Promise<unknown>
}
/** True when `pnpm wasm:build` has produced the module. */
export function isCoreBuilt(): boolean {
return existsSync(fileURLToPath(PKG_WASM))
}
let instances = 0
/**
* Instantiates a fresh module (Node: bytes from disk). Each call is a new instance.
*
* The wasm-bindgen glue keeps its instance in a module-level variable and the ESM cache
* returns the same module for the same URL, so a second plain `import()` would hand back
* the previous (possibly trapped) instance: R0 proved that an instance is unusable after a
* trap (`memory access out of bounds` in the allocator on the next call). A cache-busting
* query gives a new module record, hence a new instance. The browser loader of R2 must do
* the same (static glue URL imported with a query, or a Worker recreated on trap).
*/
export async function loadCore(): Promise<CoreModule> {
instances += 1
const pkg = (await import(
`${PKG_JS.href}?instance=${instances}`
)) as PkgModule
const bytes = await readFile(PKG_WASM)
await pkg.default({ module_or_path: bytes })
return pkg
}
/** Runs one operation and parses its envelope. */
export function callCore<T = unknown>(
core: CoreModule,
op: string,
input: string,
): CoreOutcome<T> {
return JSON.parse(core.call(op, input)) as CoreOutcome<T>
}
/** Path of the built module on disk (size measurements). */
export function coreWasmPath(): string {
return fileURLToPath(PKG_WASM)
}
+56
View File
@@ -0,0 +1,56 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { callCore, loadCore } from '../src/index'
import { coreBuilt } from './helpers/core'
const CORE_MANIFEST = new URL(
'../../../crates/core/Cargo.toml',
import.meta.url,
)
const WORKSPACE_MANIFEST = new URL('../../../Cargo.toml', import.meta.url)
describe.skipIf(!coreBuilt)('core facade (wasm)', () => {
it('reports the workspace version of the core', async () => {
const core = await loadCore()
const workspace = readFileSync(fileURLToPath(WORKSPACE_MANIFEST), 'utf8')
const version = /\[workspace\.package\][^[]*?version = "([^"]+)"/s.exec(
workspace,
)?.[1]
expect(version).toBeDefined()
expect(readFileSync(fileURLToPath(CORE_MANIFEST), 'utf8')).toContain(
'version.workspace = true',
)
expect(core.core_version()).toBe(version)
})
it('answers with a closed outcome envelope', async () => {
const core = await loadCore()
expect(callCore(core, 'core_version', '')).toEqual({
ok: true,
value: core.core_version(),
})
expect(callCore(core, 'nope', '{}')).toMatchObject({
ok: false,
kind: 'unknown_op',
})
expect(callCore(core, 'pretty_json', '{ not json')).toMatchObject({
ok: false,
kind: 'invalid_json',
})
})
it('exposes exactly the documented functions', async () => {
const core = await loadCore()
for (const name of [
'core_version',
'call',
'panic_for_test',
'recurse_for_test',
]) {
expect(typeof (core as unknown as Record<string, unknown>)[name]).toBe(
'function',
)
}
})
})
+13
View File
@@ -0,0 +1,13 @@
import { isCoreBuilt } from '../../src/index'
/**
* The proofs need the built module. On a host without Docker they are skipped with a
* visible notice instead of failing `pnpm check`; CI always builds the module first.
*/
export const coreBuilt = isCoreBuilt()
if (!coreBuilt) {
console.warn(
'[core-wasm] pkg/ missing: run `pnpm wasm:build` (Docker builder); proofs skipped',
)
}
+52
View File
@@ -0,0 +1,52 @@
/**
* R0 proof: on wasm32 a Rust panic is a trap (`WebAssembly.RuntimeError`), the shadow
* stack overflow is a trap too (no silent corruption), and a trapped instance must never be
* reused: review III.3 rule 5 (poison and re-instantiate) rests on these three facts.
*
* Observed at R0 (Node 24, wasm-bindgen 0.2.129):
* - after a plain panic the same instance still answers calls, which is the dangerous case:
* the shadow stack pointer was never unwound, so later frames run in a shifted stack;
* - after a stack-exhaustion trap the next call on the same instance fails in the allocator
* (`memory access out of bounds`), deterministically;
* - a genuinely new instance (new module record, new memory) recovers in full.
*/
import { loadCore } from '../src/index'
import { coreBuilt } from './helpers/core'
describe.skipIf(!coreBuilt)('panics and stack exhaustion (wasm)', () => {
it('turns a panic into a WebAssembly.RuntimeError', async () => {
const core = await loadCore()
expect(() => core.panic_for_test()).toThrow(WebAssembly.RuntimeError)
})
it('traps on shadow stack exhaustion instead of returning garbage', async () => {
const core = await loadCore()
expect(core.recurse_for_test(100)).toBe(100)
// 2 000 000 frames of at least 128 bytes exceed the 1 MiB shadow stack by far.
expect(() => core.recurse_for_test(2_000_000)).toThrow(
WebAssembly.RuntimeError,
)
})
it('leaves a stack-trapped instance unusable and recovers with a fresh instance', async () => {
const poisoned = await loadCore()
expect(() => poisoned.recurse_for_test(2_000_000)).toThrow(
WebAssembly.RuntimeError,
)
expect(() => poisoned.core_version()).toThrow(WebAssembly.RuntimeError)
const fresh = await loadCore()
expect(fresh.core_version()).toMatch(/^\d+\.\d+\.\d+$/)
expect(JSON.parse(fresh.call('pretty_json', '[1.0]'))).toEqual({
ok: true,
value: '[\n 1\n]',
})
})
it('may keep answering after a plain panic, which is why no instance is reused after any trap', async () => {
const poisoned = await loadCore()
expect(() => poisoned.panic_for_test()).toThrow(WebAssembly.RuntimeError)
// Not asserted either way: the instance's stack pointer is undefined from here on.
const fresh = await loadCore()
expect(fresh.core_version()).toMatch(/^\d+\.\d+\.\d+$/)
})
})
@@ -0,0 +1,115 @@
/**
* R0 proof: the core's JSON output is byte-identical to `JSON.stringify(v, null, 2)` on the
* real documents, optional fields stay absent and nullable fields stay `null`, and the
* current Zod readers accept what the core writes (review I.2, D-R11).
*/
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { ReportZoneSchema, SheetRefSchema } from '@faunosteo/domain'
import type { ReportZone, SheetRef } from '../types/index'
import { callCore, loadCore, type CoreModule } from '../src/index'
import { coreBuilt } from './helpers/core'
const FIXTURES = [
'apps/app/tests/fixtures/report-v3.demo.json',
'apps/app/tests/fixtures/report-v2.full.json',
'supabase/seed/anatomical-sheets/equine/draft/document.json',
'supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json',
]
const NUMBER_CASES = [
1523, 1715.4285714285713, 0.85, 1e21, 1e-7, 0.000001, -0,
123456789012345680000, 5e-324, 1.7976931348623157e308, 100, -2.5, 0.1,
1.5e300, 12345678901234567890,
]
function repoFile(relative: string): string {
return readFileSync(
fileURLToPath(new URL(`../../../${relative}`, import.meta.url)),
'utf8',
)
}
function prettyByCore(core: CoreModule, text: string): string {
const outcome = callCore<string>(core, 'pretty_json', text)
if (!outcome.ok) throw new Error(`${outcome.kind}: ${outcome.detail ?? ''}`)
return outcome.value
}
describe.skipIf(!coreBuilt)('serialisation contract (wasm)', () => {
it.each(FIXTURES)(
'%s: core pretty output equals JSON.stringify(…, null, 2)',
async (relative) => {
const core = await loadCore()
const text = repoFile(relative)
const expected = JSON.stringify(JSON.parse(text), null, 2)
expect(prettyByCore(core, text)).toBe(expected)
},
)
it('prints every number as JavaScript does', async () => {
const core = await loadCore()
const text = JSON.stringify(NUMBER_CASES)
expect(prettyByCore(core, text)).toBe(
JSON.stringify(JSON.parse(text), null, 2),
)
})
it('writes optional fields absent and nullable fields null, readable by the Zod schemas', async () => {
const core = await loadCore()
const bare = callCore<ReportZone>(
core,
'report_zone',
JSON.stringify({ annotationId: 'hip', viewId: 'main' }),
)
expect(bare).toEqual({
ok: true,
value: { annotationId: 'hip', viewId: 'main' },
})
if (!bare.ok) return
expect(Object.keys(bare.value)).toEqual(['annotationId', 'viewId'])
expect(ReportZoneSchema.parse(bare.value)).toEqual(bare.value)
const full = callCore<ReportZone>(
core,
'report_zone',
JSON.stringify({
viewId: 'main',
annotationId: 'hip',
side: 'left',
unresolved: true,
extra: 1,
}),
)
expect(full).toEqual({
ok: true,
value: {
annotationId: 'hip',
viewId: 'main',
side: 'left',
unresolved: true,
},
})
const sheet = callCore<SheetRef>(
core,
'sheet_ref',
JSON.stringify({
sheetId: 'faunosteo-cheval',
versionId: null,
documentSha256: 'a'.repeat(64),
}),
)
expect(sheet.ok && sheet.value.versionId).toBeNull()
if (sheet.ok) expect(SheetRefSchema.parse(sheet.value)).toEqual(sheet.value)
const refused = callCore(
core,
'report_zone',
JSON.stringify({ annotationId: 'a', viewId: 'v', unresolved: false }),
)
expect(refused).toMatchObject({ ok: false, kind: 'invalid_shape' })
})
})
+26
View File
@@ -0,0 +1,26 @@
/**
* R0 measurement: served size of the module and instantiate time (D-R13 budget, enforced
* from R2 on the real core; R0 records the skeleton's numbers).
*/
import { readFileSync } from 'node:fs'
import { gzipSync } from 'node:zlib'
import { coreWasmPath, loadCore } from '../src/index'
import { coreBuilt } from './helpers/core'
/** D-R13: the served module (compressed) stays under this many bytes. */
const COMPRESSED_BUDGET_BYTES = 600_000
describe.skipIf(!coreBuilt)('module size and instantiate time (wasm)', () => {
it('stays under the compressed budget and reports its numbers', async () => {
const bytes = readFileSync(coreWasmPath())
const gzip = gzipSync(bytes, { level: 9 }).length
const started = performance.now()
await loadCore()
const instantiateMs = performance.now() - started
console.info(
`[core-wasm] faunosteo_wasm_bg.wasm: ${bytes.length} bytes raw, ${gzip} bytes gzip-9, instantiate ${instantiateMs.toFixed(1)} ms`,
)
expect(gzip).toBeLessThanOrEqual(COMPRESSED_BUDGET_BYTES)
})
})
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"types": ["node", "vitest/globals"],
"noEmit": true
},
"include": ["src", "tests", "types"],
"exclude": ["node_modules", "pkg"]
}
+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.
/**
* Side of a bilateral zone.
*/
export type LateralSide = "left" | "right";
+17
View File
@@ -0,0 +1,17 @@
// 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 { Vertebra } from "./Vertebra";
/**
* A zone of an observation. Unknown keys are ignored on input, as the Zod schema strips
* them; optional fields are written only when set.
*/
export type ReportZone = { annotationId: string, viewId: string, side?: LateralSide, vertebrae?: Array<Vertebra>,
/**
* Annotation name at selection time (or legacy name at migration).
*/
labelFrSnapshot?: string, labelEnSnapshot?: string,
/**
* Set by the migration when the legacy id has no canonical annotation.
*/
unresolved?: true, };
+14
View File
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Reference of the anatomical sheet a report was written against (`Report.sheet`).
*/
export type SheetRef = { sheetId: string,
/**
* Database version id once the sheet lives in the database; `null` for a bundled draft.
*/
versionId: string | null,
/**
* sha256 of the document file the report was written against.
*/
documentSha256: string, };
+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.
/**
* One vertebra of a spine zone: the region code and the 1-based index in that region.
*/
export type Vertebra = { region: string, index: number, };
+6
View File
@@ -0,0 +1,6 @@
// Types of the core contracts, generated by ts-rs from crates/core (`pnpm rust:check`
// regenerates them; CI fails when the committed files drift from the Rust structs).
export type { LateralSide } from './LateralSide'
export type { ReportZone } from './ReportZone'
export type { SheetRef } from './SheetRef'
export type { Vertebra } from './Vertebra'
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
globals: true,
include: ['tests/**/*.test.ts'],
},
})
+24
View File
@@ -146,6 +146,30 @@ importers:
specifier: ^3.2.7
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15)
packages/core-wasm:
devDependencies:
'@faunosteo/domain':
specifier: workspace:*
version: link:../domain
'@types/node':
specifier: ^20.19.41
version: 20.19.41
eslint:
specifier: ^9.17.0
version: 9.39.4(jiti@2.7.0)
globals:
specifier: ^15.14.0
version: 15.15.0
typescript:
specifier: ^5.7.2
version: 5.9.3
typescript-eslint:
specifier: ^8.19.0
version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3)
vitest:
specifier: ^3.2.7
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15)
packages/domain:
dependencies:
zod:
+6
View File
@@ -0,0 +1,6 @@
# Pinned toolchain, identical to docker/rust-builder.Dockerfile (FROM rust:1.99.0-bookworm)
# and crates/worker/Dockerfile (FROM rust:1.99.0-alpine3.24). Bump the three together.
# The wasm32 target is added by the builder image only (the worker image never needs it).
[toolchain]
channel = "1.99.0"
components = ["rustfmt", "clippy"]
+2
View File
@@ -0,0 +1,2 @@
edition = "2024"
max_width = 100