Documentation / Internals
Async Work
How background results enter the UI thread, propagate through the graph, and follow mounted lifetimes.
Keep graph ownership on the UI thread
The attribute graph, mounted views, and host resources remain single-threaded. NativeHandle, State, Binding, and shared Rc models are not worker-thread handles. A background operation produces owned data; a locally registered callback applies it to the graph after the host wakes.
Runtime::channel connects these two sides without requiring the receive callback to implement Send. Its message type must be Send + 'static on both native and WASM targets. Application code can capture graph handles in the callback while sending only the result from the operation. See Channels for the public API and effect examples.
This is a delivery mechanism, not an executor. HTTP clients, file operations, task spawning, and cancellation belong to the application’s services or platform adapters. Effect setup and receive callbacks are synchronous and should finish quickly.
Separate the inbox from callbacks
Each Runtime owns a private Channels value. It contains the shared inbox, a UI-local callback registry, an identity counter, and a flag that suppresses recursive drains. Queue entries contain a channel identity and a type-erased Box<dyn Any + Send> payload; callbacks are never stored in the cross-thread queue.
The native inbox uses Arc<Mutex<Inbox>>. The browser implementation uses Rc<RefCell<Inbox>>, since delivery enters from the main thread. The callback registry uses Rc<RefCell<...>> on both targets. Registration creates a wrapper that downcasts the payload to the channel’s message type before invoking the typed callback.
| Piece | Ownership | Responsibility |
|---|---|---|
MessageSender<T> | Weak reference to the inbox and a channel identity. | Admit owned messages without retaining the app or callback. |
MessageSubscription | UI-local weak references to the inbox and callback registry. | Close admission, discard queued results, and remove the callback on drop. |
| Inbox | Owned by the runtime; synchronized on native. | Store pending messages, active channel identities, and the host notification. |
| Callback registry | Owned by the runtime on the UI thread. | Retain receive callbacks and their captured bindings or shared models until closure. |
These storage types describe the current implementation, not additional application APIs. The runtime owns callback storage; retaining a subscription controls how long its registration remains active.
Admit messages with bounded storage
try_send upgrades the weak inbox reference, checks that the channel is active, and checks the shared queue’s capacity. A missing or inactive channel returns SendError::Closed(value); a queue containing 1,024 pending messages returns SendError::Full(value). Both preserve ownership of the original value for the caller.
On native, the activity check and enqueue happen under the same mutex. Subscription closure uses that mutex too, so a concurrent send is either admitted before closure and then discarded if still pending, or rejected as closed. A successful send is an admission acknowledgment, not a delivery or presentation acknowledgment.
Messages are FIFO by admission order across the runtime’s channels. This does not impose an order on concurrent producers before admission, or a global order against input and existing host mutation queues. The limit bounds pending message count, not payload bytes; producers must handle saturation explicitly.
Wake before mutating the graph
The graph’s existing waker runs after propagation dirties observers. A background result arrives before any graph write, so the inbox has a separate notification installed with Runtime::set_message_waker. Native notifications must be Send + Sync; browser notifications may capture UI-local values.
Admission requests a wake when the queue transitions from empty to nonempty. Installing a waker also notifies if messages are already pending. A bounded drain re-notifies when work remains, so a producer that finds an already nonempty queue does not need to issue a wake for every message.
Native uses Winit’s EventLoopProxy to notify the UI event loop. Web uses the existing coalesced browser scheduler, which yields to a browser task after repeated microtask flushes. Both install the message waker before initial effect setup. The notification schedules future work; it must never invoke graph callbacks inline.
Drain into one graph mutation batch
Runtime::drain_messages extracts a snapshot of at most 128 entries and resolves their current callbacks on the UI thread. All callbacks in that snapshot execute inside one Runtime::batch. A callback can send more messages, register a channel, or close a subscription; no inbox lock or callback-registry borrow is held while application code executes.
Messages sent during delivery wait for a later drain, and recursive drains return zero. The registry is checked again for each extracted entry, so closing a subscription also suppresses its not-yet-executed messages already in the snapshot. The drain retains the original registry identity, preventing old entries from reaching newly registered callbacks if all channels are closed and reopened during delivery.
| Stage | Effect on the application |
|---|---|
| Receive callback | Write through ordinary State or Binding methods. A message alone does not invalidate anything. |
| Batch completion | Settle derived computations and mark affected observers dirty. Derived reads can remain stale until this point. |
App::prepare | Map dirty observers to mounted views, reevaluate affected bodies, and prepare semantic patches. |
Host apply and App::commit | Apply patches, accept the new tree and dependencies, then run effect cleanup and setup. Native presentation can happen later. |
set_if_changed suppresses equal writes. Derived::distinct can stop downstream propagation when a computed result stays equal. Channel delivery preserves both behaviors; it does not force a whole-tree rerender.
Tie delivery to an effect lifetime
Create view-owned channels in committed effect setup and return subscription.into_cleanup(). This consumes the subscription and returns a Box<dyn FnOnce()> compatible with the effect cleanup type. The closure owns the subscription until it runs or is dropped; use an explicit cleanup closure when you also need to cancel the producer. Discarded preparations then create no external work. Replacing effect dependencies or committing an unmount drops the previous subscription, closes admission, removes pending results, and releases callback captures.
A scope token only describes whether a mounted view is alive. An effect-owned subscription also distinguishes successive operations while the same view remains mounted: changing a request dependency closes the old channel before replacement setup. Results applied before that cleanup are not rolled back. Independent requests sharing one channel still need their own ordering or request-identity policy.
A root effect can own incoming delivery for an environment_object model. Its callback captures the model and updates its bindings. Deeper consumers subscribe by reading those bindings during view evaluation; they do not need channels of their own. Intermediate layouts can remain unevaluated when only a descendant’s dependency changes.
App::dispose closes all channels, including registrations whose subscriptions are held outside effects. Closing delivery does not stop the producer: cancel an HTTP request, terminate a Worker, or signal a cooperative computation separately. Senders stay weak so an unfinished producer cannot keep the app alive.
Share application logic across platforms
Request construction, decoding, domain logic, and receive callbacks can be shared. A small platform adapter supplies the transport and execution mechanism. Native threads or async tasks can own a MessageSender<T> directly; a browser async callback uses the local sender on the main thread.
A separate Web Worker communicates through postMessage. Decode or reconstruct its result on the main thread, then submit it to the Rust channel. The sender does not cross that boundary, and the bridge does not provide shared-memory WASM threading or automatic serialization. Running an async future on the browser’s main thread does not offload expensive CPU work.
Native local updates and timers continue through NativeHandle; browser callbacks can still use UpdateHandle. Channels provide the typed result path that lets shared application callbacks retain graph state without moving it into background work.
Failure handling and verification
Operational failures should be ordinary message data, such as Result<Data, Error>. Queue saturation and closure are admission errors, separate from the operation’s outcome. Receive callbacks should handle expected failures explicitly.
A callback panic follows Runtime::batch behavior: writes are not rolled back. The drain restores its recursion flag, discards undelivered entries from the extracted snapshot during unwind, re-notifies for later queued work, and resumes the panic. Hosts are not promised automatic recovery from application panics.
TestHost::flush drains one bounded batch before preparing views. Tests can synchronize producers and use has_pending_messages for subsequent drains. The return value of drain_messages counts invoked callbacks; the return value of TestHost::flush reports whether a view update committed.
| Source | What to inspect |
|---|---|
crates/graph/src/channel.rs | Admission, weak ownership, callback registration, wakeups, batched drains, and concurrency tests. |
crates/core/src/runtime/mod.rs | Effect setup and teardown, app disposal, and incremental view reconciliation. |
crates/native/src/app/mod.rs | Winit notification and draining before host preparation. |
crates/web/src/dom.rs | Browser scheduling, DOM flushes, and disposal. |
crates/test/tests/channels.rs | Shared environment models, dependency replacement, unmount, and disposal checks. |
crates/web/tests/browser | Browser fetch completion, actual Worker delivery, burst draining, and cleanup fixtures. |