Injecting Rust in the Frontend with WebAssembly
local graph
Chapter 8 — Injecting Rust in the Frontend with WebAssembly
Section titled “Chapter 8 — Injecting Rust in the Frontend with WebAssembly”8 Injecting Rust in the Frontend with WebAssembly
Section titled “8 Injecting Rust in the Frontend with WebAssembly”You have probably heard about WebAssembly (WASM). At the time of writing this book, the WASM ecosystem is still in the early rapid development phases, where APIs get outdated quickly, and groups trying out a new approach cease to exist but have remnants of their approach throughout the internet. This can lead to frustration as you burn hours trying to figure out what API does what. However, the promise of compile once and run anywhere, including the browser, is a clear advantage, so it makes sense to understand and get comfortable with WASM.
In this chapter, we are going to keep the interactions with APIs to a minimum and focus on concepts around serving WASM modules to the frontend to be loaded and used in the browser. We are also going to explore directly interacting with the raw memory addresses in WASM so we can transfer complex data types across the WASM boundary, and we are going to load WASM binaries using Rust to also interact with WASM binaries in the backend.
We cover the following topics in this chapter:
- What is WASM?
- Setting up our WASM build
- Loading WASM in the frontend
- Loading WASM on the local machine
By the end of this chapter, you will be comfortable enough with WASM to navigate the rapidly changing WASM landscape. However, if WASM is not for you, skipping this chapter will not affect the overall functionality of the app, as we will just be replacing the item status functionality with a WASM binary.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle. You will also need wasm-pack, which can be installed via the following link: https://drager.github.io/wasm-pack/installer/
You will also need the WebAssembly binary toolkit, which can be found in the link: https://github.com/WebAssembly/wabt.
This toolkit can also be installed with operating system package managers such as brew and apt-get.
What is WASM?
Section titled “What is WASM?”Generally, with compiled languages, we must compile the code for a specific chip architecture and operating system. This means that if you compile your Rust program on a Mac, that compiled binary will not run on a Linux or Windows machine, and vice versa. WASM, on the other hand, is compiled to bytecode. The standards for this bytecode are defined by the Bytecode Alliance. This is a binary format that is designed to be executed by a virtual machine or interpreter. So, when we compile our WASM, instead of compiling the code to a specific architecture or operating system, the code is compiled to an agreed-upon standard that all virtual machines support. This means that we can compile our WASM binary once and run this single WASM binary on any device that has a virtual machine. Java is an older language that has a similar approach. WASM is so flexible that we can even run WASM in the browser. This means that we can compile our Rust code into WASM and send that WASM over a network to a browser to be run. WASM is not just supported by Rust. Languages such as C, C++, Python, Golang, and Zig can also compile to WASM. However, it must be noted that there is a downside to WASM, which is binary size.
The frontend ecosystem has worked hard to reduce the size of code being sent to the browser. This is done by having JavaScript functionality in the browser, so not everything has to be sent over a network. WASM, on the other hand, must compile all instructions into the binary. This means some implementation of garbage collection if we are compiling Python into WASM. When we are compiling Rust, error handling and types must be included in the WASM binary. This results in much bigger payloads being sent over the network. Because of the larger payloads, combined with the rich frontend ecosystem of JavaScript, it is unlikely that Rust WASM is going to take over JavaScript for the frontend. Existing libraries, mature frameworks, and the talent pool have resulted in me building backend servers in Rust, but still reaching for the JavaScript ecosystem for the frontend. However, WASM is still a useful tool for solving problems. For instance, a part of our backend code could be sent over the network to run on the client’s computer through the browser. This reduces our workload without us having to rewrite the code in JavaScript. Another use case is WASM workers in the backend. WASM runs in a sandbox, meaning that it does not have any permissions to access files or network ports without the runner explicitly defining the permissions. Sandboxing enables us to allow users to write code in a range of languages, compile the code to WASM, and run that WASM on our servers. In the final chapter of this book, we build a queuing system that takes WASM tasks off a Redis queue and processes them. These WASM tasks also keep a state. This enables other developers in the team to write programs in other languages that can be processed on our Rust servers. To get to grips with the basics of WASM, we will start by setting up our WASM build for serving Rust WASM to the frontend.
Setting up our WASM build
Section titled “Setting up our WASM build”We must set up a Rust workspace in our frontend that can house the Rust code that we want to compile to a WASM target to be served. To set up our WASM build environment, we will carry out the following tasks:
- Define our WASM module
- Configure our NPM build WASM command
- Inspect our WASM binary
We will start by defining our WASM module.
Defining our WASM module
Section titled “Defining our WASM module”In our frontend directory, we can create a new Rust workspace with the following command:
cargo new rust-interface --libNow that we have a workspace, we must configure our [lib] of this workspace with the following code:
frontend/rust-interface/Cargo.toml
Section titled “frontend/rust-interface/Cargo.toml”[lib]crate-type = ["cdylib"]
[dependencies]wasm-bindgen = "0.2.99"Here, we can see that we are relying on the wasm-bindgen crate to make the WASM-to-JavaScript bindings and simplify our Rust functions that act as entry points to the WASM program. In the last section of this chapter, we will build our own code to enable us to pass complex data types over the WASM boundary. This is going to involve directly accessing raw, unsafe data pointers. Using unsafe pointers when coding in Rust might seem wrong. However, there is no other choice. If we are getting data by interacting directly with another program and language, there is no way the Rust compiler can check lifetimes to ensure that the memory allocation is safe. However, for our frontend example, the wasm-bindgen crate is going to do all the heavy lifting when it comes to passing over even simple data structures, such as strings.
We also see that the crate type of our Rust workspace is a cdylib. This stands for dynamic library. A dynamic library is linked to the main program when a program is compiling. The compiled program then loads the dynamic library at runtime as opposed to the library being compiled into the main program binary. There are pros and cons to this. For instance, you can reuse dynamic libraries in multiple programs, and these dynamic libraries are easier to update as they are not part of the build. Not being part of the build also results in reducing the compile times, as we do not need to recompile the dynamic library when we are compiling the main code. Dynamic libraries will also reduce your main program binary size. However, this does not come for free as the compiler cannot optimize the code in the dynamic library using the code of your main program. It also has additional overhead as the program needs to load the dynamic library, and deployment can be trickier due to more moving parts.
For many of your web development projects, you will not need to build dynamic libraries, as it is likely not worth the extra headache of linker errors and handling multiple moving parts. However, if you end up working on a massive code base, then dynamic libraries become essential, especially if there are interfaces from other languages, such as WASM. For instance, at the time of writing this book, I am currently doing research in the King’s College London Bioengineering department in surgical robotics. We need to interface with GPUs. A lot of hardware support is mainly written in C and C++ dynamic libraries. The ecosystem for Rust is maturing, but sometimes there is no getting around interacting with C and C++ libraries.
We need to compile our Rust binary in a WASM format and move it into our public directory. This will enable us to serve our WASM binary when needed. We can do this via the terminal, but there are a couple of commands pointing to specific directories. This is easy to get wrong, and we also do not want to bother other developers with learning how to build and package WASM, so we will just put our commands under the WASM key under the scripts section with the following code:
...,"wasm": "cd rust-interface && sudo wasm-pack build --target web && cp pkg/rust_interface_bg.wasm ../public/rust_interface_bg.wasm",Here, we can see that we carry out the following steps:
- Change directory to the rust-interface directory.
- Use wasm-pack to build the Rust program to target the web.
- Copy the WASM binary from the pkg to the public directory.
We will also want to trace our WASM binary to make sure that we are exporting the functions that we expect. We can do this with the wasm2wat command from the wasm toolkit we installed in the Technical requirements section of this chapter, with the following scripts command:
"wasm-trace": "cd public && wasm2wat rust_interface_bg.wasm > rust_interface_bg.wat"What happens here is that the wasm2wat command converts the WASM binary into WAT format, which is a human-readable text format. You can code in WAT and compile to WASM, giving you the freedom to do whatever you want. However, you will be directly coding to assembly, and it will take you a lot of time to code even the most basic Rust programs.
Before we run any commands, we must write some Rust code that can be compiled into WASM. For our example, we will be creating a basic function that takes in a string that is the status of the task and returns the text that should be displayed in the button for that task. This can be done with the following code:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]pub fn rust_generate_button_text(status: String) -> String { match status.to_uppercase().as_str() { "PENDING" => "edit".to_string(), "DONE" => "delete".to_string(), _ => "an error has occured".to_string(), }}While the code is straightforward enough, we can see that the function is annotated with the #[wasm_bindgen] macro. The #[wasm_bindgen] macro does the following:
- JavaScript integration: The macro exposes the annotated Rust function so it can be called from JavaScript. This is essential for creating WASM modules that can interact with web-based applications.
- Type conversion: It handles the automatic conversion of types between Rust and JavaScript. In our function, it manages the conversion of the Rust String type to a JavaScript string and vice versa. Due to the differences in data types between languages, we cannot always guarantee that data type conversions are possible. However, if you stick to the basics of integers, floats, bools, and strings, with basic collections, there should be no problems.
- Memory management: The macro manages memory for the types passed between Rust and JavaScript, ensuring that memory is allocated and freed appropriately to prevent leaks.
- Function wrapping: It wraps the Rust function in such a way that it can be imported into JavaScript as a regular function. This allows the function to be invoked from JavaScript just like any other JavaScript function.
We can now run our build with the following commands in the frontend directory:
npm run wasmnpm run wasm-traceThese commands might take a while to execute, depending on the computer. After running these commands, the WASM and WAT files should be in the public directory. We cannot really inspect the WASM binary because it’s a binary, but if we look at the bottom of the rust_interface_bg.wat file, we should see the following exports:
(export "memory" (memory 0))(export "update_status" (func 9))(export "__wbindgen_add_to_stack_pointer" (func 35))(export "__wbindgen_malloc" (func 19))(export "__wbindgen_realloc" (func 23))(export "__wbindgen_free" (func 27))Before we explain what the WAT code means, we need to understand that the WASM memory model is linear. This means that unlike Random-Access Memory (RAM), all the memory in the WASM program is contiguous, meaning that the memory is essentially one big array of memory. This makes WASM very fast compared to random access. However, it also makes WASM more vulnerable to attacks if there is no memory safety. For instance, if a hacker can access memory outside of the assigned buffer (the result of a buffer overflow), then the hacker has access to the entire memory stack of the program and can do what they want. Luckily, with Rust, we have memory safety. This is why Rust is at the bleeding edge of WASM. Rust has memory safety, but it doesn’t have a garbage collector, which simplifies the running and compiling of the WASM binary.
I always say to people, if they want to lead the charge of WASM, they need to learn Rust.
With the WASM memory model in mind, we can now look at (memory 0). This refers to the first memory instance defined in the module and is allocated at index 0 of the memory array. This memory instance is being exported with the function name “memory,” making it accessible for use outside the module. (func 9), (func 35), (func 19), (func 23), and (func 27) denote that they are functions that are allocated at certain indexes of the memory.
Now we can cover the function exports:
- (export “memory” (memory 0)): This exports the first memory instance defined in the WASM module. It allows external environments to access and manipulate the memory used by the WASM instance.
- (export “update_status” (func 9)): This is a function export. It exports a function labeled update_status. This is the function that we defined in our code, so it’s good to know that the code we wrote is available in the WASM binary as update_status.
-
(export “__wbindgen_add_to_stack_pointer” (func 35)): This is a stack pointer adjustment. It exports a function that adjusts the stack pointer. This is useful for managing the allocation of stack space, particularly during complex operations or recursive calls within the WebAssembly code.
-
(export “__wbindgen_malloc” (func 19)): This is memory allocation. It exports a function for allocating memory. This function is analogous to malloc in C/C++, providing a way to dynamically allocate a specified amount of memory. Later in the chapter, we will write our own malloc function.
-
(export “__wbindgen_realloc” (func 23)): This is memory reallocation. It exports a function that adjusts the size of a previously allocated memory block. This is like realloc in C/C++, which is used to either expand or contract a memory allocation while attempting to preserve the contents.
-
(export “__wbindgen_free” (func 27)): This is memory deallocation. It exports a function for freeing allocated memory. This function is like free in C/C++ and is used to release previously allocated memory back to the system, preventing memory leaks. Memory leaks are where the memory allocated to variables that are no longer used is not cleared up. Over time, the memory being used by the program continues to grow until the computer runs out of memory.
Our WASM program is now completed, and we are confident that we can interact with it like we intended. We can now move on to loading the WASM binary in our JavaScript code in the frontend.
Defining WASM modules cheatsheet
WASM libraries are dynamic C libraries due to the stable application binary interface, so there is a binary interface for the WASM runtime to interact with.
The wasm-bingen crate makes the creation of these binary interfaces easier, so you do not have to build the raw C interfaces yourself. This also means that the memory management for the C interfaces is also handled.
wasm-bingen also creates memory allocation functions that can be accessed as public functions by the code loading the WASM module.
We can use the wasm2wat command to convert the compiled WASM binary to WASM text format, so we can personally inspect what public functions are available in the WASM binary. This can help with general inspection of a WASM binary that you are interacting with, and can also help with debugging, so you can check that the functions are what you expect.
Loading WASM in the frontend
Section titled “Loading WASM in the frontend”When it comes to loading WASM in our frontend application, the program must carry out the steps shown in Figure 8.1:
Figure 8.1 – Steps to run a WASM function in the browser
Figure 8.1 depicts these steps:
- A React component makes a request to the file server for the WASM file.
- The file server gets the WASM binary.
- The file server then returns the WASM file back to the frontend for the requesting React component to load it.
- The WASM functions are then stored in the component state to be called as and when needed.
For us to understand and enable our frontend to load the WASM binary and execute it, we are going to carry out the following steps:
- Inspect the WASM interface.
- Integrate WASM loading in our React component.
- Pass WASM to subcomponents.
But before we carry out these steps, we should inspect the WASM interface, so we know what is going on.
[figure outside: Figure 8.1]
Inspecting a WASM interface
Section titled “Inspecting a WASM interface”Even though it might seem intuitive to handle the WASM loading and function in the task component, we would end up requesting a WASM file for every task in our to-do application. For our example project, this might be OK, as we will not notice any difficulties. However, as the application scales and more users use our application, we would really struggle to keep up with demand. We could reduce the number of calls by caching in the browser, and we can do this in the header of the response serving the WASM file. We should do this anyway, but to reduce the risk of excessive calls even more, we are going to load the WASM file in the main application. It must be noted that WASM-based apps will have a bigger initial load time, which will vary depending on how much we rely on WASM.
We can load our WASM in the src/index.tsx file with the following code:
import init, { rust_generate_button_text } from '../rust-interface/pkg/rust_interface.js';Here, we will use the init function to get the WASM binary. The init function handles the request to the server for the WASM binary. It also handles the initialization of the WASM module, which loads the WASM module into memory and imports functions needed for the WASM library to run.
We can see that we are loading the rust_generate_button_text function from a JavaScript file. If we look at the JavaScript file in the pkg directory of the WASM build and search for the rust_generate_button_text function, we get the following code. For now, this is just the outline of the function, but we will break down each section shortly. It must be noted that the code generation may change as the package changes, but the fundamental concepts will be the same:
let WASM_VECTOR_LEN = 0;...export function rust_generate_button_text(status) { let deferred2_0; let deferred2_1; try { ... } finally { ... }}deferred2_0 and deferred2_1 are pointers that are going to be used for deallocating memory. In the try section, the function initially adjusts the memory pointer to reserve space for the function’s execution with the following code:
try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); ...}It then uses the memory allocation that has been generated in the WASM program to allocate memory to the WASM library memory buffer, which is the length of the bytes of the string. This returns the pointer to where that memory allocation starts and the length of the memory buffer, with the following code:
const ptr0 = passStringToWasm0( status, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);const len0 = WASM_VECTOR_LEN;The interface function can then execute our WASM function, with the following code, and we get the result of our function:
wasm.rust_generate_button_text(retptr, ptr0, len0);var r0 = getInt32Memory0()[retptr / 4 + 0];var r1 = getInt32Memory0()[retptr / 4 + 1];deferred2_0 = r0;deferred2_1 = r1;return getStringFromWasm0(r0, r1);If you have done some JavaScript coding before, you may wonder why the generated code is using var instead of const or let. The var is used to expand the compatibility of the code. This is because const and let were introduced later and are not available in pre-2015 hosts. In the preceding code, we can see that we pass the pointer for our string buffer in memory, and the length of the buffer. This enables our WASM function to extract the string data from the memory and use it in the way that we intended. Our WASM function then puts the return string into the memory. The pointers for the return string are then extracted, and this is used to get the string from WASM. To get the string from WASM, you would access the bytes in the memory using the pointer and the length of the buffer, and then deserialize those bytes to a string. Finally, the function deallocates the memory, as we no longer need it, using the following code:
finally { wasm.__wbindgen_add_to_stack_pointer(16); wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); }Now that we understand how our WASM function interfaces with the application, we know that the interaction with the raw pointers to our WASM function will be bundled into our application. With this, we only need to worry about serving the WASM file, not serving or configuring any glue code, because the glue code is in our JavaScript bundle.
Integrating WASM loading into our React component
Section titled “Integrating WASM loading into our React component”Going back to our main app component, we now need to store the WASM function in our state and a Boolean flag on whether the WASM binary has been loaded or not. To have the whole app be aware of the WASM loading state, our App component should have the following hooks:
const [data, setData] = useState(null); const [error, setError] = useState(null); const [wasmReady, setWasmReady] = useState<boolean>(false); const [ RustGenerateButtonText, setRustGenerateButtonText ] = useState<(input: string) => string>(null);Here, we can see that we still house our to-do items in data, but we declare that the WASM is ready with wasmReady, and we house the Rust function that is compiled to WASM with RustGenerateButtonText.
We can now load our WASM binary and set the WASM ready flag by adding another useEffect alongside our existing one with the following code:
React.useEffect(() => { init().then(() => { setRustGenerateButtonText(() => rust_generate_button_text); setWasmReady(true); }).catch(e => console.error( "Error initializing WASM: ", e )); }, []);The fetching of the WASM binary might take some time. We do not want to run the risk of getting the items from the server before we get the WASM function because we need the WASM function to create the text for each to-do item. Therefore, we refactor our loading of the to-do items with the following code:
React.useEffect(() => { const fetchData = async () => { ... }; if (wasmReady) { fetchData(); }}, [wasmReady]);Here, we can see that useEffect will only fire when wasmReady changes based on the dependency declared by [wasmReady]. We do not know whether the future and wasmReady will change back to false later; therefore, even if wasmReady changes, we check that wasmReady is true before making calls to get the to-do items from the server. We now need to pass our WASM function output to our to-do item subcomponents so they can render the status of the item.
Passing our WASM output to subcomponents
Section titled “Passing our WASM output to subcomponents”To pass our WASM function to our item subcomponents, we can call the WASM function for the status of each to-do item in our return statement with the following code:
<h1>Pending Items</h1><div> {data.pending.map((item, index) => ( <<ToDoItem key={item.title + item.status} title={item.title} status={item.status} id={item.id} buttonMessage={ RustGenerateButtonText(item.status) } passBackResponse={reRenderItems}/> </> ))}</div><h1>Done Items</h1><div> {data.done.map((item, index) => (<><ToDoItem key={item.title + item.status} title={item.title} status={item.status} id={item.id} buttonMessage={ RustGenerateButtonText(item.status) } passBackResponse={reRenderItems}/> </>))}</div>You may have noticed a change in the parameters passed into the ToDoItem components. This is be-cause we have taken advantage of this WASM function refactor to simplify the ToDoItem component and get rid of the state of the ToDoItem component, which was never really needed.
In real life, as a project grows and deadlines loom, the best implementation does not always land straight away. Keeping on top of a degrading code base takes work. It’s just like gardening: you need to be constantly pruning.
Big refactors can introduce bugs, delay projects, cause breaking changes elsewhere in the system, and hold up other developers as they must review these big refactors. What’s more, the code is not static if other developers are also working on the same code base. If you have a big refactor, then chances are that your code changes will clash with other developers’ work.
A good way to prevent these issues, but not let the code slip into disorder, degrading over time to the point of it being a problem, is the philosophy of “leaving code better off than when you found it.” The refactor we’ve just done is a perfect example of this. We did a small simplification, and the scope of code that we changed is in the scope of where our WASM interactions are based. If you would like to, now would be a good time to try and refactor the ToDoItem component yourself.
If you attempted to refactor the ToDoItem component, hopefully, it resembles the following code:
interface ToDoItemProps { title: string; id: number; passBackResponse: (response: any) => void; buttonMessage: string;}export const ToDoItem: React.FC<ToDoItemProps> = ( { title, id, passBackResponse, buttonMessage }) => {const sendRequest = async () => { if (buttonMessage === "edit") { await updateToDoItemCall( title, TaskStatus.DONE ).then( response => { passBackResponse(response); } ) } else { await deleteToDoItemCall(title).then( response => { passBackResponse(response); } ) }};
return ( <div className="itemContainer" id={id}> {title} <button className="actionButton" onClick={sendRequest}>{buttonMessage}</button> </div>);Here, we can see that we got rid of the internal state of the to-do item, simplifying the component while maintaining the functionality as we now pass in the button message. We now have everything ready to integrate WASM into the frontend. If we run our server now, we should see the network calls shown in Figure 8.2:
| Name | Status | Type | Initiator | Size | Time |
|---|---|---|---|---|---|
| localhost | 200 | docum… | Other | 435 B | 1 ms |
| bundle.css | 200 | stylesh… | :8001/:8 | (memory … | 0 ms |
| bundle.js | 200 | script | :8001/:9 | (memory … | 0 ms |
| rust_interface_bg.wasm | 200 | wasm | rust_interfa… | (disk cac… | 0 ms |
| all | 200 | xhr | utils.ts:78 | 282 B | 1 ms |
Figure 8.2 – Frontend network calls with WASM
[figure outside: Figure 8.2]
In Figure 8.2, we can see that the bundles are loaded, then the WASM is loaded, then finally, the to-do items are loaded. The fact that our buttons are rendering proves that our WASM function works as we intended it to.
And there we have it, we now have WASM loading and running in the frontend of our application! We can execute Rust in the browser!
But what about Rust interfacing with WASM? Or WASM executing on the local machine? We will explore these ideas in the next section.
Loading WASM in the frontend cheatsheet
Section titled “Loading WASM in the frontend cheatsheet”The wasm-pack command generates JavaScript code that interfaces with the WASM module. You do not need to touch the generated interface; just import and call it in your frontend application.
The generated interface interacts with the memory allocation functions built by wasm-bingen to ensure that the memory is correctly allocated and cleaned up when interacting with a WASM module.
We use useEffect to load the WASM module as the frontend has to make a network call to the server to get the WASM binary and load it.
Because network calls to retrieve WASM binaries take time, we have a Boolean flag that is initially false and then switched to true when the WASM module is loaded. This gives us control to render different things until the WASM module is loaded.
Loading WASM on the local machine
Section titled “Loading WASM on the local machine”In this section, we are going to build a WASM module and have our own Rust code load the WASM file and interact with it. We are also going to build a kernel to pass complex data structures over the WASM boundary, as we saw in the JavaScript memory allocation code in the previous section. To carry out this exercise, we are going to need the following file layout:
[figure outside: Figure 8.2]
Injecting Rust in the Frontend with WebAssembly
These workspaces have the following purposes:
- kernel: To provide structs to both wasm-lib and wasm-client workspaces so that they can both compile the same structs for the serialization and deserialization of structs and bytes
- wasm-lib: To build a WASM binary with some functionality with the structs passed into the WASM binary
- wasm-client: To load the WASM binary and interact with it, passing data to the WASM program and extracting results
Seeing as both the WASM lib and WASM client rely on the kernel, we will start with the kernel.
Building a WASM kernel
There can be some confusion around the word “kernel,” with some assuming that it relates only to an operating system. The term is broader than that, however; in the realm of domain-driven design, it refers to a bounded context, shared across multiple other bounded contexts. This is the kind of kernel we will be building here. For our kernel, we simply need to build a data struct that both bounded contexts (client and lib) need to reference.
We could just build the same structs in both our WASM client and library, and these would technically work, as we are going to serialize our structs before sending them over the WASM boundary. However, maintaining consistency when there are multiple duplicates of a struct is harder, and if both client and lib end up being compiled into the same Rust program later, the compiler will acknowledge that the structs have the same name but are defined in different places. This will result in us needing to manually convert the struct from the client to the lib struct to satisfy the compiler.
The data struct in the kernel will be the single source of truth with its own workspace. Because the kernel is in its own workspace, we can then compile it into any program that needs to communicate with another that has also compiled the kernel, as seen in Figure 8.3:
Figure 8.3 - Kernel enables easy scaling of programs communicating
For our kernel workspace, we have the following dependency:
[figure outside: Figure 8.3]
[dependencies]serde = { version = "1.0.201", features = ["derive"] }Now, with our dependency defined, we can build out the basic data struct with the following code:
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]pub struct SomeDataStruct { pub name: String, pub names: Vec<String>,}If you recall, in the Loading WASM in the frontend section, the string was transferred over the WASM boundary when inspecting the JavaScript code that interacted with the WASM binary. We also need a pointer that will point to the serialized struct in memory. We need this pointer in our kernel too. Our pointer takes the following form:
#[repr(C)]pub struct ResultPointer { pub ptr: i32, pub len: i32}ptr is the pointer to the memory address of the start of where the serialized SomeDataStruct is stored in memory. Here, we can calculate the end of the memory address using the length.
The #[repr(c)] macro for the ResultPointer struct ensures that the ResultPointer layout is consistent with the C representation for ABI compatibility, field order, and padding/alignment, making the memory layout predictable from a C perspective.
What’s with all the C references?
At the time of writing this, Rust does not have a stable Application Binary Interface (ABI). C, on the other hand, does have a stable ABI due to its simplicity and years of maturity. At this point in time, Rust is still changing and trying to improve. If Rust established a stable ABI, it would make it harder to move forward with new improvements.
Seeing as the kernels in Windows, macOS, and Linux are written in C, C data types are universally accepted. Just Google “foreign function interface C …” and then whatever language you are interested in, and I’d be shocked if there isn’t an option of interacting with C data and functions in that language.
Our kernel is now ready, and we can move on to our WASM library. Building a WASM library
To build our WASM library, we are going to receive a pointer and length to the serialized struct in memory, and then we are going to carry out the following steps:
- Extract the bytes of the struct from memory.
- Deserialize the struct.
- Add a name to the struct.
- Serialize the updated struct to bytes.
- Put the serialized struct into memory.
- Return the pointer to the memory address of the updated serialized structs.
While these numbered steps help distill what we are carrying out, we will not break down the implementation of our WASM library into numbered steps, as the implementation of these numbered steps all comes at the end when the entry point function is built.
Before we write any code, our WASM library will need the following dependencies:
[dependencies]bincode = "1.3.3"kernel = { path = "../kernel" }serde = { version = "1.0.201", features = ["derive"] }
[lib]crate-type = ["cdylib"]We are going to be using bincode for the serialization. The crate bincode serializes Rust data types to raw bytes. This means other Rust programs will be able to accept the bytes and convert them back to Rust data types, but not other languages. As we are writing our WASM library in Rust and we will be using Rust to interact with our WASM library. If we had a different language interacting with the WASM library, we would need another serialization method, such as JSON, CBOR, or Protobuf, but for this example, bincode works. Also note that we are not using any WASM dependencies here; instead, we are just going to expose C interfaces and directly interact with them. Don’t worry, we will still be able to compile into WASM without WASM crates declared in this file.
We can now start writing our C interfaces. To do this, we need the following imports:
extern crate alloc;use core::alloc::Layout;use kernel::{ SomeDataStruct, ResultPointer};Here, we are basically importing the structs from the kernel, and then the struct (SomeDataStruct) and the library. With these imports, we can create our memory allocation function with the following code:
#[no_mangle]pub unsafe extern "C" fn ns_malloc( size: u32, alignment: u32 ) -> *mut u8 { let layout = Layout::from_size_align_unchecked( size as usize, alignment as usize ); alloc::alloc::alloc(layout) }Here, we are taking the size of memory needed, and the alignment of where that memory allocation starts in the memory. We then create a Layout struct from the core of the library of the Rust language. This Layout is essentially a slice of memory. Finally, we pass that slice of memory into the alloc func-tion, which allocates the memory for it. We then return a *mut u8, which is a raw pointer to a memory address. Note that the ns_malloc function is unsafe, as the from_size_align_unchecked function is unsafe. The from_size_align_unchecked function is unsafe because we are directly accessing mem-ory, so the Rust compiler cannot check and enforce memory-safe patterns. We are using an unsafe approach because we are going to pass data from the main Rust binary to the WASM binary. Because they are different binaries, the Rust compiler cannot ensure that the data inserted into the memory from one binary is safe, because the compiler does not have access to that other binary when compiling.
Now that we have our memory allocation, we must free up the memory when we no longer need it. If we do not free up the memory, the used memory will continue to grow. This is called a memory leak. If the program is not stopped, it will run out of memory, at which point the computer will terminate the program.
Our freeing-up function takes the following form:
#[no_mangle]pub unsafe extern "C" fn ns_free( ptr: *mut u8, size: u32, alignment: u32 ) { let layout = Layout::from_size_align_unchecked( size as usize, alignment as usize ); alloc::alloc::dealloc(ptr, layout); }Here, we can see that we get the layout struct again, but we apply a memory deallocation as opposed to an allocation. Now that all our memory management code is finally done, we can move on to our entry point, which takes the following outline:
#[no_mangle]pub extern "C" fn entry_point( ptr: *const u8, len: usize) -> *const ResultPointer { ...}Here, we accept the pointer and length, and then return the ResultPointer so the client code can try and extract the result.
Inside our entry point function, we get the bytes from the memory, deserialize the bytes to our SomeDataStruct struct, and then alter the deserialized struct with the following code:
let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };let mut data_struct: SomeDataStruct = bincode::deserialize( bytes).unwrap();data_struct.names.push("new name".to_string());That’s it, that’s the logic of our WASM program done, so now we must serialize the data and get the length and pointer to the serialized data with the following code:
let serialized_data = bincode::serialize( &data_struct).unwrap();let len = serialized_data.len();let out_ptr = serialized_data.leak().as_ptr();You can see that we are getting the pointer from the serialized struct. Here, the memory is not automatically cleaned up; otherwise, foreign function interfaces would be hard to implement as we need the memory allocation to hang around for the Rust program to access after the Rust program has interacted with the WASM binary. We can just return the pointer, and then manually clean up the memory later when we need to.
Now that we have our pointer and length of the memory buffer, we can return the pointer and length with the following code:
let result = Box::new(ResultPointer{ ptr: out_ptr as i32, len: len as i32}});Box::into_raw(result) as *const ResultPointerOur library is nearly done; all the Rust code is finished, but we need to build a Bash script to build the WASM binary, and copy over the WASM binary so we can ensure that the WASM binary is where we want it to be. Our Bash script just takes the following form:
File: wasm-lib/scripts/build.sh
Section titled “File: wasm-lib/scripts/build.sh”#!/bin/bash
navigate to directory
Section titled “navigate to directory”SCRIPTPATH=“(dirname “SCRIPTPATH cd ..
cargo build --release --target wasm32-wasi
cp target/wasm32-wasi/release/wasm_lib.wasm ./wasm_lib.wasmwasm2wat ./wasm_lib.wasm > ./wasm_lib.watThis script takes a similar form to our build Bash script in our frontend. With that done, we are now ready to build the client.
Building a WASM client
Section titled “Building a WASM client”For our client, we must serialize and deserialize data and load the WASM file. Because of this, we have the following dependencies:
[dependencies]serde = { version = "1.0.197", features = ["derive"] }tokio = { version = "1.37.0", features = ["full"] }bincode = "1.3.3"kernel = { path = "../kernel" }wasmtime-wasi = { version = "20.0.0", features = ["preview1"]}wasmtime = "20.0.0"The crate wasmtime is the runtime that is going to run and load the WASM binary. The wasmtime-wasi crate is the linker between the wasmtime runtime and the WASM binary. You may have noticed that there is also a preview1 in the features. This refers to the version of the API that we are targeting. For instance, if we want to write a file, print to the terminal, or access a port, our WASM code will need to call a function in the runtime to do this, like a syscall in an operating system. At the time of writing this, we are targeting preview1, but there will be later releases of the API as the ecosystem matures. Now that our dependencies are defined, we can start building the client with the following outline:
use wasmtime::{Result, Engine, Linker, Module, Store, Config};use wasmtime_wasi::preview1::{self, WasiP1Ctx};use wasmtime_wasi::WasiCtxBuilder;use std::mem::size_of;use std::slice::from_raw_parts;use kernel::{ SomeDataStruct, ResultPointer};
#[tokio::main]async fn main() -> Result<()> { ...}Inside our main function, we begin by starting a WASM engine and loading the WASM binary with the following code:
let mut config = Config::new();config.async_support(true);let engine = Engine::new(&config).unwrap();let module = Module::from_file( &engine, "../wasm-lib/wasm_lib.wasm").unwrap();Now that we have loaded our WASM library into our engine, we can link preview1 and configs with the following code, so if our WASM module is making any calls to the runtime, such as printing to the terminal, it can:
let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);preview1::add_to_linker_async(&mut linker, |t| t).unwrap();let pre = linker.instantiate_pre(&module)?;let wasi_ctx = WasiCtxBuilder::new() .inherit_stdio() .inherit_env() .build_p1();Here, we can see that we enable standard IO and environment variables. preview1 is essentially a version of WASM. For instance, at the time of writing this book, preview is currently being worked on for better support for sockets. Our runtime must enable the standard IO and environment variables because by itself, WASM is locked down and can’t access operating system interfaces. This makes sense as WASM can be loaded and run in the browser. Now that we have the wasmtime runtime built with our config, we can create a memory store and create an instance of our WASM module with that memory with the following code:
// File: wasm-client/src/main.rslet mut store = Store::new(&engine, wasi_ctx);let instance = pre.instantiate_async(&mut store).await.unwrap();With the instance being created, we are now at the stage where we can serialize our data struct. We do this with the following code:
// File: wasm-client/src/main.rslet data_struct = SomeDataStruct { names: vec!["name1".to_string(), "name2".to_string()], name: "name3".to_string()};let serialized = bincode::serialize(&data_struct).unwrap();With our serialized struct, we can assign our struct bytes to our WASM instance memory with the following code:
// File: wasm-client/src/main.rs// allocate the memory for the input datalet malloc = instance.get_typed_func::<(i32, i32), i32>( &mut store, "ns_malloc").unwrap();let input_data_ptr = malloc.call_async( &mut store, (serialized.len() as i32, 0)).await.unwrap();
// write the contract to the memorylet memory = instance.get_memory( &mut store, "memory").unwrap();memory.write( &mut store, input_data_ptr as usize, &serialized).unwrap();Now that our serialized struct is in the memory of the WASM instance, we can get our entry point function from the WASM module and then call the entry point function to get the pointer to the result. We do this with the following code:
// File: wasm-client/src/main.rslet entry_point = instance.get_typed_func::<(i32, i32), i32>( &mut store, "entry_point").unwrap();let ret = entry_point.call_async( &mut store, (input_data_ptr, serialized.len() as i32)).await.unwrap();We can now use the pointer to read the bytes from the memory. First, we get the result pointer from the memory with the following code:
let mut result_buffer = Vec::with_capacity( size_of::<ResultPointer>());for _ in 0..size_of::<ResultPointer>() { result_buffer.push(0);}memory.read( &mut store, ret as usize, &mut result_buffer).unwrap();
let result_struct = unsafe { &from_raw_parts::<ResultPointer>( result_buffer.as_ptr() as *const ResultPointer, 1 )[0]};Now that we have our result pointer, we use this to read the struct we want from memory with the following code:
let mut output_buffer: Vec<u8> = Vec::with_capacity( result_struct.len as usize);output_buffer.resize(result_struct.len as usize, 0);memory.read( &mut store, result_struct.ptr as usize, &mut output_buffer).unwrap();let output = bincode::deserialize::<SomeDataStruct>( &output_buffer).unwrap();println!("Output contract: {:?}", output);We now have the altered data that we want.
Before we finish our program, we should clean up the rest of the memory:
let free = instance.get_typed_func::<(i32, i32, i32), ()>(&mut store, "ns_free").unwrap();free.call_async( &mut store, (input_data_ptr, serialized.len() as i32, 0)).await.unwrap();free.call_async( &mut store, (result_struct.ptr, result_struct.len, 0)).await.unwrap();free.call_async( &mut store, (ret, size_of::<ResultPointer>() as i32, 0)).await.unwrap();Ok(())Now our program is finished. If we run it, we get the following printout:
Running target/debug/wasm-client
Output contract: SomeDataStruct {
name: "name3", names: ["name1", "name2", "new name"]}We can see that our struct was passed through to the WASM module, altered, and then passed back to the Rust host to be displayed. While this is not going to affect our to-do application, in Chapter 20, we will build a queuing system on top of Redis that will accept WASM binaries, put them on a Redis queue, and have Rust workers that will consume these WASM modules and execute them. We have now managed to directly interact with WASM without any helper crates creating the interfaces in the WASM library. As the features and support for WASM increase, you will be able to interact with these updates and feel confident to run whatever the bytecode alliance throws your way.
Loading WASM on a local machine cheatsheet We use the wasmtime crate to load the WASM binary as a module, initialize it with a state, and link it to the preview1 runtime API so our WASM module has access to functionality like. We can define a pointer in memory and how much memory is needed. We can then serialize data structures and put them in that slot of memory. Once the data structure is put in the memory, we pass the pointer over to the WASM module so the data structure can be accessed inside the WASM module. In our example, we were using Rust to run the WASM module, and we were using Rust to build the WASM module, so we used bincode for easy serialization. However, if you need the data serialization to be language-agnostic, using formats such as JSON, CBOR, or Protobuf will work when the client and WASM module are not built using the same language. Injecting Rust in the Frontend with WebAssembly
Summary
In this chapter, we got to grips with packaging WASM for the frontend and interacting with WASM using Rust. While we did not build anything substantial in WASM, we focused on developing foundational knowledge on how WASM is interacted with. At the time of writing this book, the APIs and features of WASM are rapidly changing. If we built a feature-rich WASM program using the current APIs, this book would age quickly, and you would have to Google the new APIs to figure out what you need to change to get your system running. Keeping an eye on WASM is a good idea. The advantage of compiling once and running anywhere, including the browser, is a strong one.
We are now at the stage where our basic application works in terms of creating, updating, and deleting to-do items. However, if we were to deploy it right now for multiple users, our data storage solution would slow down the number of requests and we would be held back by the lack of concurrency and networking capabilities our storage solution has. In the next chapter, we will upgrade our storage solution from a file to a Postgres database.
Questions
-
What is the WASM memory model and how is it different from the Random-Access Memory (RAM) model?
-
How can you send a complex data structure over the WASM boundary?
-
Let’s say you have a compiled WASM binary in your public folder. How do you load functions from that WASM file into your React application?
-
How do we check to see whether the functions that we defined in the WASM program are in the WASM binary?
-
What are the advantages of building a separate kernel in its own workspace?
Answers
-
WASM has a linear memory model, meaning that all the memory is next to each other in one block. This results in faster memory access as we can just increment our pointer to access the next segment of memory. However, the linear memory model is more dangerous than RAM due to a hacker potentially having access to the entire memory of the program by exploiting a buffer overflow. Luckily, Rust is memory-safe, so it is not much of an issue; however, be careful when implementing unsafe memory allocation functions, as we did in the chapter.
-
You can send a complex data structure over the WASM boundary by serializing the data structure, allocating the bytes of the serialized data structure in the WASM instance memory, and then passing the pointer and length of the byte buffer through to the WASM program. The WASM program can then access the bytes in the memory and deserialize it.
-
Your React component can use useEffect to fire init from wasm-pack to fetch the binary. Once the binary is served, we can update the state of the component to say that the WASM binary has been loaded. We can also use other useEffect statements to perform actions on the other parts of the component that depend on the WASM binary, with the useEffect statement having a dependency of a flag to say that WASM is loaded.
255
-
We use the wasm2wat command on the WASM file and write the output to a wat file. In the wat file, we can then scroll down to the bottom to see the export functions section. If our function is there, that means that it is accessible to users to interact with the WASM binary.
-
A kernel in its own workspace acts as a single source of truth; we just have to update it once and all modules and programs communicating through that kernel get that update. We can also scale the number of programs and libraries interacting with the program that has the kernel easily without having to write any more boilerplate code.
Learn more on Discord
Section titled “Learn more on Discord”To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow this QR code: https://packt.link/EaKXL
[blank page]