Skip to content

Latest commit

 

History

History
159 lines (130 loc) · 9.21 KB

wasm.md

File metadata and controls

159 lines (130 loc) · 9.21 KB

WebAssembly (Blazor) support

Status: not possible yet (#126). This document records what was tried with matrix-rust-sdk matrix-sdk-ffi/20260909, uniffi-bindgen-cs 0.11.0 and .NET 10.0.12 (wasm-tools workload), what works and what blocks it, so the work can be picked up once the blockers are resolved upstream.

Approach

.NET on browser-wasm (Blazor WebAssembly, wasmbrowser, wasmconsole) can't load shared libraries, native code has to be statically linked into dotnet.native.wasm with emscripten. The bindings keep working unchanged through [DllImport], so the plan is:

  1. Build matrix-sdk-ffi as a static library for wasm32-unknown-emscripten with the emscripten version of the .NET workload (3.1.56 for .NET 10).
  2. Link it into the app with <NativeFileReference> and <WasmBuildNative>true</WasmBuildNative>.

What works

  • matrix-sdk-ffi compiles for wasm32-unknown-emscripten with three small SDK patches (see below) and links into a .NET 10 wasm app.
  • A P/Invoke into the library (ffi_matrix_sdk_ffi_uniffi_contract_version) runs in the .NET wasm runtime under Node.
  • The uniffi API on wasm differs from the native one only by the SQLite parts (24 symbols: SqliteStoreBuilder, ClientBuilder.SqliteStore, ClientBuilder.SessionPaths, secrets bundle database functions and their checksums). matrix-sdk-ffi additionally exposes ClientBuilder.IndexeddbStore on wasm.

Blockers

1. matrix-rust-sdk on wasm requires wasm-bindgen

On every target_family = "wasm" target matrix-rust-sdk uses wasm-bindgen: wasm-bindgen is a non-optional dependency of matrix-sdk-common, tasks are spawned with wasm_bindgen_futures::spawn_local, reqwest uses its fetch backend, the only usable store is IndexedDB (SQLite needs tokio/fs, which tokio doesn't support on wasm) and timers use gloo-timers.

The JavaScript side of these imports is generated by the wasm-bindgen CLI, which only supports wasm32-unknown-unknown. Linked with the full bindings, dotnet.native.wasm imports 195 functions from the __wbindgen_placeholder__ module (IndexedDB, fetch, setTimeout, queueMicrotask, promises, ...) and fails to instantiate:

WebAssembly.instantiate(): Import #3 module="__wbindgen_placeholder__" error: module is not an object or function

wasm-bindgen gained experimental emscripten support (Cloudflare, 2026-09), but it is pre-release and relies on emscripten's -sWASM_BINDGEN setting, which emscripten 3.1.56 of the .NET 10 workload doesn't have.

2. uniffi-bindgen-cs callbacks use delegates

The generated bindings register every callback interface and the future continuation callback with Marshal.GetFunctionPointerForDelegate (165 calls, 189 delegate types) in the static constructor of _UniFFILib. Mono on wasm only supports native-to-managed calls into [UnmanagedCallersOnly] (or [MonoPInvokeCallback]) methods, so the first call into the bindings fails, even synchronous ones like SdkGitSha():

System.PlatformNotSupportedException: No native to managed transition for method
'void Matrix.RustSdk.Bindings.UniffiCallbackInterfaceAccountDataListener:OnChange (...)', missing [UnmanagedCallersOnly] attribute.

This needs a change in the uniffi-bindgen-cs templates. Full AOT on iOS fails for the same reason: NordSecurity/uniffi-bindgen-cs#175.

Smaller issues and workarounds

These are solved or have known workarounds, but would have to go into the build once the blockers are gone.

  • matrix-sdk-ffi doesn't compile for wasm. matrix-rust-sdk's CI checks the core crates on wasm but not matrix-sdk-ffi, which always enables matrix-sdk/experimental-search. The search code boxes its streams as Send, which doesn't hold on wasm. Patch (fits upstream, it affects wasm32-unknown-unknown too):

    --- a/crates/matrix-sdk/src/message_search.rs
    +++ b/crates/matrix-sdk/src/message_search.rs
    +#[cfg(not(target_family = "wasm"))]
     type RoomResultStream = Pin<Box<dyn Stream<Item = Result<(f32, OwnedEventId), IndexError>> + Send>>;
    +#[cfg(target_family = "wasm")]
    +type RoomResultStream = Pin<Box<dyn Stream<Item = Result<(f32, OwnedEventId), IndexError>>>>;
    --- a/crates/matrix-sdk-ui/src/search_service.rs
    +++ b/crates/matrix-sdk-ui/src/search_service.rs
    +#[cfg(not(target_family = "wasm"))]
     type ResultsStream =
         Pin<Box<dyn Stream<Item = Result<Vec<(OwnedRoomId, TimelineEvent)>, SearchError>> + Send>>;
    +#[cfg(target_family = "wasm")]
    +type ResultsStream =
    +    Pin<Box<dyn Stream<Item = Result<Vec<(OwnedRoomId, TimelineEvent)>, SearchError>>>>;
    --- a/bindings/matrix-sdk-ffi/src/search_service.rs
    +++ b/bindings/matrix-sdk-ffi/src/search_service.rs
    -        self.inner.set_query(query).await.map_err(|err| ClientError::from(anyhow::Error::from(err)))
    +        self.inner.set_query(query).await.map_err(ClientError::from_err)
    -        self.inner.paginate().await.map_err(|err| ClientError::from(anyhow::Error::from(err)))
    +        self.inner.paginate().await.map_err(ClientError::from_err)
  • gloo-timers doesn't compile with panic=unwind (the emscripten default): wasm-bindgen requires UnwindSafe closures then. Build with RUSTFLAGS="-C panic=abort".

  • No SQLite: build with --no-default-features --features js,indexeddb,unstable-msc4274,experimental-element-recent-emojis,experimental-push-secrets,experimental-search. The C# bindings would need a wasm variant without the SQLite API (or stubs), otherwise the checksum check fails.

  • Only the static library: cargo build also links the cdylib as an emscripten side module, which fails (zstd-sys isn't built with -fPIC). Use cargo rustc --crate-type staticlib.

  • Library name: the P/Invoke table uses the file name of the NativeFileReference, so the archive has to be called matrix_sdk_ffi.a (not libmatrix_sdk_ffi.a) to match [DllImport("matrix_sdk_ffi")].

  • Newer LLVM than emscripten 3.1.56: the SDK needs Rust 1.95+, whose objects declare the wasm features bulk-memory-opt and call-indirect-overlong. emcc passes them to its binaryen, which doesn't know them (Unknown option '--enable-bulk-memory-opt'). Stripping the target_features section isn't enough because emcc then disables bulk memory. It worked with a wasm-opt wrapper that drops the two flags; a proper fix would rewrite the feature names in the objects' target_features sections.

  • WasmNativeStrip: the .NET DWARF strip step runs wasm-opt with only simd, exception-handling and bulk-memory enabled, but Rust's default wasm features also include nontrapping-fptoint, sign-ext, reference-types and multivalue. Set <WasmNativeStrip>false</WasmNativeStrip>.

  • Size: the debug build of dotnet.native.wasm is 134 MB, a release build with opt-level = "z" and LTO is needed.

Reproducing

Build the static library in the emscripten image matching the .NET workload, on a copy of the submodule with the patch applied:

docker run --rm -v "$PWD/matrix-rust-sdk:/sdk" -w /sdk emscripten/emsdk:3.1.56 bash -c '
  curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --target wasm32-unknown-emscripten
  . $HOME/.cargo/env
  RUSTFLAGS="-C panic=abort" cargo rustc --locked -p matrix-sdk-ffi --lib --crate-type staticlib \
    --target wasm32-unknown-emscripten --no-default-features \
    --features js,indexeddb,unstable-msc4274,experimental-element-recent-emojis,experimental-push-secrets,experimental-search
  cp target/wasm32-unknown-emscripten/debug/libmatrix_sdk_ffi.a matrix_sdk_ffi.a'

Then link it into a .NET app (mcr.microsoft.com/dotnet/sdk:10.0 with dotnet workload install wasm-tools and python3), with the wasm-opt wrapper from above:

<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <WasmBuildNative>true</WasmBuildNative>
    <WasmNativeStrip>false</WasmNativeStrip>
    <WasmMainJSPath>main.mjs</WasmMainJSPath>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="../src/Matrix.RustSdk.Bindings/Matrix.RustSdk.Bindings.csproj" />
    <NativeFileReference Include="matrix_sdk_ffi.a" />
  </ItemGroup>
</Project>

dotnet publish -c Release and run node main.mjs in bin/Release/net10.0/publish/wwwroot (with a package.json containing {"type": "module"}).

Alternatives

  • Separate wasm module: build matrix-sdk-ffi for wasm32-unknown-unknown with wasm-bindgen (the configuration matrix-rust-sdk supports, used by uniffi-bindgen-react-native for the web) and call it from C# through [JSImport]/[JSExport] instead of P/Invoke. Both modules have separate memories, so every RustBuffer has to be copied and callbacks go through JavaScript. That needs a different bindings generator, uniffi-bindgen-cs can't produce it.
  • Wait for upstream: once wasm-bindgen's emscripten support is released and .NET ships an emscripten with -sWASM_BINDGEN, and uniffi-bindgen-cs generates [UnmanagedCallersOnly] callbacks, the static linking approach above should work with the listed workarounds.