Middleware
For new code, we recommend the effect router over middleware. It routes each effect the app emits to the shell or to Rust code running alongside the core, including the follow-up effects of a resolved request.
Middleware is a somewhat advanced feature for split effect handling, i.e. handling some effects in the shell, and some still in the core, but outside the app's state loop.
Middleware can be useful when you have an existing 3rd party library written in Rust which you want to use, but it isn't written in a sans-I/O way with managed effects or otherwise isn't compatible with Crux. This is sadly most libraries with side effects.
It is quite likely most apps will never need to use middleware. Before reaching for middleware, we encourage you to consider:
- Implementing the side-effect in each Shell using native, platform SDKs. Shared libraries give a productivity boost at first, but for the same reason Crux uses Capabilities, they can't always be the best platform citizens, and often rely on very low-level system APIs which compromise the experience, don't collaborate well with platform security measures, etc.
- Moving coordination logic from the Rust implementation into a custom capability in the core and implementing it on top of lower level capabilities, e.g. HTTP. This would be the case for HTTP API SDK type libraries, but may well not be practical at first
Only if neither of these is a good option, reach for a middleware. The cost of using it is that the effect handling becomes less straightforward, which may cause some headaches debugging effect ordering, etc.
We are also still learning how middleware operates in the wild, and the API may change more than the rest of Crux tends to.
All that said, the feature is used in production with success today and should work well.
How it works
Middleware sits between the Core and the Shell in the effect processing pipeline. When the app requests effects, they pass through the middleware stack on their way to the shell. A middleware layer can intercept specific effect variants, handle them (performing the side-effect in Rust), and resolve the request, all without the shell ever seeing that effect. Effects the middleware doesn't handle pass through to the shell as normal.
We'll walk through the counter-middleware example to see how this works in practice. This example is a counter app that has a "random" button: when pressed, the counter changes by a random amount. The random number generation is handled by a middleware, rather than by the shell.
The diagram shows the layers of the example on native targets. Each effect goes out from the core through the layers, and each output comes back in through the same layers.
Defining the operation
First, we need an Operation type that describes the request and its output. This is the
same as defining a capability's protocol: a request type and a response type:
/// Request a random number between the two values, both included. The answer
/// is a single [`RandomNumber`].
#[derive(Operation, Facet, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[operation(request, output = RandomNumber)]
pub struct RandomNumberRequest(pub isize, pub isize);
#[derive(Facet, Debug, PartialEq, Eq, Deserialize)]
pub struct RandomNumber(pub isize);
The RandomNumberRequest carries the range (min and max, both included), and RandomNumber carries the result.
#[derive(Operation)] writes the Operation implementation, and
#[operation(request, output = RandomNumber)] tells it two things: a
RandomNumberRequest produces a RandomNumber, and it is a request, answered
exactly once. The kind is what lets the app send it with
Command::request_from_shell (and only that), and what gives the generated shell
handler a typed random method that returns a RandomNumber. See
Building capabilities.
The app uses this operation as one variant of its Effect enum:
#[effect(facet_typegen)]
#[derive(Debug)]
pub enum Effect {
Render(RenderOperation),
Http(HttpRequest),
ServerSentEvents(SseRequest),
Random(RandomNumberRequest),
}
And the app can request a random number using Command::request_from_shell, just as it
would for any shell-handled effect:
Event::Random => Command::request_from_shell(RandomNumberRequest(-5, 5))
.map(|out| out.0)
.then_send(Event::UpdateBy),
The app doesn't know or care that this effect will be intercepted by middleware; it just requests the effect and handles the response.
Implementing EffectMiddleware
The EffectMiddleware trait is how you tell Crux what to do when it encounters a specific
effect. You implement try_process_effect, which receives the operation and an
EffectResolver that you use to send back the result.
Here's the RngMiddleware from the example:
use std::{
sync::mpsc::{Sender, channel},
thread::spawn,
};
use crux_core::middleware::{EffectMiddleware, EffectResolver};
use rand::rngs::SysRng;
use rand::{RngExt, SeedableRng, TryRng as _, rngs::StdRng};
use crate::capabilities::{RandomNumber, RandomNumberRequest};
pub struct RngMiddleware {
jobs_tx: Sender<(RandomNumberRequest, EffectResolver<RandomNumber>)>,
}
impl RngMiddleware {
pub fn new() -> Self {
let (jobs_tx, jobs_rx) = channel::<(RandomNumberRequest, EffectResolver<RandomNumber>)>();
// Persistent background worker
spawn(move || {
let mut sys_rng = SysRng;
let mut rng =
StdRng::seed_from_u64(sys_rng.try_next_u64().expect("could not seed RNG"));
while let Ok((RandomNumberRequest(from, to), mut resolver)) = jobs_rx.recv() {
// rand samples no `isize`, so draw an `i64` from the same range.
#[allow(clippy::cast_possible_truncation)]
let out = rng.random_range(from as i64..=to as i64) as isize;
resolver.resolve(RandomNumber(out));
}
});
Self { jobs_tx }
}
}
impl EffectMiddleware for RngMiddleware {
type Op = RandomNumberRequest;
fn try_process_effect(
&self,
operation: RandomNumberRequest,
resolver: EffectResolver<RandomNumber>,
) {
self.jobs_tx
.send((operation, resolver))
.expect("Job failed to send to worker thread");
}
}
A few things to note:
- The
type Opassociated type tells Crux which operation this middleware handles (RandomNumberRequestin this case). try_process_effectreceives the operation and anEffectResolver. You must callresolver.resolve(output)with the result when the work is done: once for a request, once per item for a stream, never for a notification.EffectResolveris generic over the output rather than the operation, so if you need to know which you're holding, ask it:resolver.kind()returns theOperationKind.- The processing happens on a background thread. This is important: the middleware
must not block the caller of
process_event. On native targets this typically means spawning a thread; on WASM it means an async task (e.g.spawn_local). - The background thread pattern shown here (a persistent worker with a channel) is a good approach when the middleware holds state (like the RNG seed). For stateless work, you could simply spawn a thread per request.
Wiring it up
The middleware is composed with the Core in the FFI module, where you build the
bridge between the core and the shell. The example splits the wiring by target:
native runs the middleware on a background thread; WebAssembly skips it because
this middleware is thread::spawn based.
pub fn new(shell: Arc<dyn CruxShell>) -> Self {
// Native: RngMiddleware handles `Random` in a background task, so its
// effects are delivered to the shell asynchronously via the callback.
#[cfg(not(target_family = "wasm"))]
let core = Core::<Counter>::new()
.handle_effects_using(RngMiddleware::new())
.map_effect::<Effect>()
.bridge::<BincodeFfiFormat>(move |effect_bytes| match effect_bytes {
Ok(effect) => shell.process_effects(effect),
Err(e) => panic!("{e}"),
});
// Wasm: no background tasks, so effects are returned synchronously from
// update/resolve. The callback is wired for API parity but unused.
#[cfg(target_family = "wasm")]
let core =
Core::<Counter>::new().bridge::<BincodeFfiFormat>(
move |effect_bytes| match effect_bytes {
Ok(effect) => shell.process_effects(effect),
Err(e) => panic!("{e}"),
},
);
Self { core }
}
The native branch reads bottom-to-top as a pipeline:
Core::<Counter>::new(): creates the core, which produces the app's fullEffectenum (including theRandomvariant)..handle_effects_using(RngMiddleware::new()): wraps the core with the RNG middleware.Randomeffects are intercepted and resolved here; everything else passes through..map_effect::<Effect>(): remaps to the FFI-facingEffectenum used by typegen and the bridge. In this example the FFIEffectmirrors the app's, so this is a 1:1 remap. This is also where you can narrow the effect type: drop variants that middleware fully consumes from the FFI enum and panic on them inFrom, so the shell never sees them. The counter example doesn't narrowRandombecause the WebAssembly shells handle it themselves..bridge::<BincodeFfiFormat>(...): creates the FFI bridge as usual.
On WebAssembly there is no middleware: the bridge wraps Core directly, so
Random effects flow straight through to the shell, which fulfills them itself.
The FFI effect type
The FFI module declares its own Effect enum, which is the one the bridge
serializes:
#[effect(facet_typegen)]
pub enum Effect {
Render(RenderOperation),
Http(HttpRequest),
ServerSentEvents(SseRequest),
Random(RandomNumberRequest),
}
A From implementation converts from the app's full effect type. In this example the
two enums have the same variants, so every arm remaps 1:1:
impl From<crate::app::Effect> for Effect {
fn from(effect: crate::app::Effect) -> Self {
match effect {
crate::Effect::Render(request) => Self::Render(request),
crate::Effect::Http(request) => Self::Http(request),
crate::Effect::ServerSentEvents(request) => Self::ServerSentEvents(request),
crate::Effect::Random(request) => Self::Random(request),
}
}
}
If a middleware fully consumes a variant on every target you build, you can
remove that variant from this enum and panic! on it in From, and the shell then
receives a narrower set of effects. The counter example keeps Random here
because on WebAssembly the middleware doesn't run, so the shell handles it.
Type generation doesn't see this enum: the codegen binary registers the app,
so the shell's types, and the generated EffectHandler, follow the app's
Effect. A native shell still implements a random method, then, even though
on its targets the middleware means the method is never called.
In the shell
On native targets the middleware resolves Random on its own thread, after
update has returned. Whatever the app asks for next (here, a Render and
the HTTP calls that update the server's count) can't come back as the return
value of update or resolve, so the bridge hands those requests to the
callback you gave .bridge(...). In this example that callback
calls CruxShell::process_effects, a trait the shell implements and passes to
CoreFfi::new. The bytes are the same serialized requests that update and
resolve return, and the shell handles them the same way.
The counter-middleware shells use the generated Core
(Who drives the loop), with an
EffectHandler that delegates http to the shell's own HTTP client and
implements serverSentEvents by hand. Setting the Core up differs in one
way. CoreFfi::new takes the shell's callback, but the generated FfiBridge
constructs CoreFfi with no arguments, so an app with middleware doesn't
configure .boltffi(...). Instead each shell writes the three-method
CoreBridge over its own CoreFfi. Here it is in Swift:
/// The generated `CoreBridge`, written by hand over this app's `CoreFfi`.
///
/// The codegen binary doesn't ask for the generated `FfiBridge`, because that
/// constructs `CoreFfi` with no arguments, and this app's `CoreFfi` takes the
/// `CruxShell` callback the middleware uses to deliver effects after `update`
/// or `resolve` has returned. So this bridge takes that callback and hands it
/// to `CoreFfi`; the three methods are bytes in, bytes out.
///
/// `@unchecked Sendable` because `CoreFfi` is a class Swift cannot prove
/// `Sendable`; its state is a handle into a mutex-guarded bridge on the Rust
/// side, so calling it from any task is safe.
struct MiddlewareBridge: CoreBridge, @unchecked Sendable {
private let ffi: CoreFfi
init(shell: CruxShell) {
ffi = CoreFfi(shell: shell)
}
func update(_ event: [UInt8]) -> [UInt8] {
[UInt8](ffi.update(data: Data(event)))
}
func resolve(_ id: UInt32, _ output: [UInt8]) -> [UInt8] {
[UInt8](ffi.resolve(effectId: id, data: Data(output)))
}
func view() -> [UInt8] {
[UInt8](ffi.view())
}
}
The callback hands its bytes to the generated Core's process(bytes:)
(process(bytes) in Kotlin, processBytes in TypeScript and Process(byte[])
in C#). Construction runs the other way: the bridge needs the CoreFfi, the
CoreFfi needs the callback, and the callback needs the Core, which is built
from the bridge. The Swift shell breaks that cycle by not giving the callback
the Core at all. The callback puts the bytes on an AsyncStream:
/// The `CruxShell` callback `CoreFfi` is constructed with.
///
/// The middleware calls `processEffects` from its own thread, with the
/// serialized requests the app made after the middleware resolved one of its
/// effects. The callback doesn't hold the `Core` (it can't, because the
/// `Core` is built from the bridge, which is built from this), so it puts the
/// bytes on a stream, in the order they arrive, for `makeCore` to forward.
final class MiddlewareEffects: CruxShell, Sendable {
let stream: AsyncStream<[UInt8]>
private let continuation: AsyncStream<[UInt8]>.Continuation
init() {
(stream, continuation) = AsyncStream.makeStream(of: [UInt8].self)
}
func processEffects(bytes: Data) {
continuation.yield([UInt8](bytes))
}
}
Once the Core exists, a task reads from the stream and passes each batch on.
The callback arrives on the middleware's thread, and the Swift Core is
@MainActor, so that task runs on the main actor. Because one task reads the
whole stream, the batches arrive in the order the middleware sent them:
/// Build the generated `Core` over the middleware bridge.
///
/// Construction runs one way (callback, then bridge, then `Core`), and the
/// stream carries the callback's bytes back the other way. One task on the
/// main actor reads it and passes each batch to `Core.process(bytes:)`, which
/// has to run there because `Core` is `@MainActor`. A single reader keeps the
/// batches in the order the middleware sent them.
@MainActor
func makeCore() -> Core {
let effects = MiddlewareEffects()
let core = Core(bridge: MiddlewareBridge(shell: effects), handler: CounterHandler())
let stream = effects.stream
Task { [weak core] in
for await bytes in stream {
core?.process(bytes: bytes)
}
}
return core
}
The app then builds the Core from makeCore() in place of
Core(handler:), and the rest of the shell is the same as any other. The
Kotlin shell sets the Core on its callback once it has been constructed, and
posts each batch to the main thread with Dispatchers.Main. The TypeScript
shell closes over a variable it assigns once the Core is built. In
WebAssembly there's no middleware, so its callback is never called.
Testing
The app can be tested exactly the same way as any other Crux app, because the middleware is not
involved in unit tests. You test the app's update function directly, treating Random
as a normal effect:
#[test]
fn random_change() {
let app = Counter;
let mut model = Model::default();
let mut cmd = app.update(Event::Random, &mut model);
// the app should request a random number from the web API
let mut request = cmd.effects().next().unwrap().expect_random();
assert_eq!(request.operation, RandomNumberRequest(-5, 5));
request.resolve(RandomNumber(-2)).unwrap();
// And start an UpdateBy the number
let event = cmd.events().next().unwrap();
assert_eq!(event, Event::UpdateBy(-2));
This is one of the nice properties of middleware: the app logic remains pure and testable, and the middleware is a separate concern that's composed at the FFI boundary.
Summary
To add a middleware to your app:
- Define an
Operation: a request type and output type, just like a capability protocol, ideally with#[derive(Operation)]so its kind is declared too. - Implement
EffectMiddleware: handle the operation and resolve the result, typically on a background thread. - Wire it up: use
.handle_effects_using()in your FFI setup to intercept the effects, and optionally.map_effect()to narrow the effect type for the shell.
For the full API reference, see the middleware module docs.