Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tutorial

If you like to learn by doing, this tutorial will walk through how to build, compose, and run components through a calculator example. Calculators can conduct many operations: add, subtract, multiply, and so on.

In this example, each operation will be a component, that will be composed with an eval-expression component that will evaluate the expression using the expected operator. With one operation per component, this calculator is exaggeratedly granular to show how independent logic of an application can be contained in a component.

In production, components will likely have a larger scope than a simple mathematical operation.

Our eventual solution will involve three components:

  1. A calculator engine,
  2. An addition operation
  3. A command-line interface.

Once we have built these as separate Wasm components, we will compose them into a single runnable component, and test it using the wasmtime CLI.

The calculator interface

For tutorial purposes, we are going to put our “calculator engine” and “addition operation” interfaces into two separate WIT packages, each containing one WIT file.

This setup may seem excessive, but it illustrates a real-world use case where components come from different authors and packages.

These files can be found in the component book repository in the examples/tutorial/wit directory under wit/adder/world.wit and wit/calculator/world.wit:

// wit/adder/world.wit
package docs:adder@0.1.0;

interface add {
    add: func(x: u32, y: u32) -> u32;
}

world adder {
    export add;
}
  // wit/calculator/world.wit
  package docs:calculator@0.1.0;

  interface calculate {
      enum op {
          add,
      }
      eval-expression: func(op: op, x: u32, y: u32) -> u32;
  }

  world calculator {
      export calculate;
      import docs:adder/add@0.1.0;
  }

  world app {
      import calculate;
  }

These files define:

  • A world adder that exports the add interface. Again, components such as the calculator can call it when they need to add numbers.
  • A world calculator describing the calculator component. This world exports the calculator interface, meaning that other components can call it to perform calculations. It imports the operation interfaces (such as add), meaning it relies on other components to perform those operations.
  • An interface calculate that contains an evaluate function and an enum that delineates the operations that can be involved in a calculation. In this tutorial, the only operation is add.
  • A world app describing the “primary” app component, which imports the calculate interface. This component will take in command line arguments and pass them to the eval-expression function of the calculator component.

Create an add component

Reference the language guide to create a component that implements the adder world of adder/wit/world.wit.

For reference, see the completed example.

Create a calculator component

Reference the language guide to create a component that implements the calculator world of wit/calculator/world.wit.

For reference, see the completed example.

Once complete, the component should import the add function from the adder world and call it if the op enum matches add.

Target the CLI world with a reactor component

This Rust library builds a reactor component that targets the CLI world by implementing wasi:cli/run. A Rust binary crate can target the same world, with the toolchain providing wasi:cli/run and calling main.

See Creating Runnable Components (Rust) for more information on both approaches.

To scaffold a new runnable Wasm application:

cargo new --lib command
cd command

In Cargo.toml, configure this crate as a cdylib:

[lib]
crate-type = ["cdylib"]

Add wit-bindgen to generate the WIT bindings. The CLI uses clap to parse arguments and anyhow to report an unknown operator.

cargo add wit-bindgen anyhow
cargo add clap --features derive

This component will implement the app world, which imports the calculate interface.

Copy wit/calculator/world.wit to wit/world.wit in the new project. We’ll need to modify the world that imports the calculation function and makes use of it to be runnable, by exporting wasi:cli/run:

world app {
    import calculate;
+   export wasi:cli/run@0.2.7;
}

Since the calculator world imports the add interface, the command crate needs to pull in the adder WIT as a dependency, as well.

To do this, we can use wkg from wasm-pkg-tools. Configure wkg to resolve the docs packages from GHCR and the wasi packages from wasi.dev.

# $XDG_CONFIG_HOME/wasm-pkg/config.toml
[namespace_registries]
wasi = "wasi.dev"
# Tell wkg that the component-book WITs can be found at ghcr.io/bytecodealliance/docs
docs = { registry = "docs",  metadata = { preferredProtocol = "oci", "oci" = {registry = "ghcr.io", namespacePrefix = "bytecodealliance/" } } }

Note

We have published the docs:adder WIT package to GHCR ahead of time, so it is easy to find/access via the configuration above.

To make your own custom WITs available, please use the wkg publish command.

Then, fetch the WIT dependencies (both docs:adder and the well-known wasi:cli package) into wit/deps:

wkg wit fetch

Replace src/lib.rs with the code below. The host calls wasi:cli/run, where Command::try_parse() reads the two operands and the operator. For a supported operator, Command::run passes all three values to the calculator component’s eval_expression function and prints the result.

#![allow(unused)]
fn main() {
mod bindings {
    //! This module contains generated code for implementing
    //! the `app` world in `wit/world.wit`.

    use super::Component;

    wit_bindgen::generate!({
        world: "app",
    });

    export!(Component);
}

use std::fmt;

use clap::Parser;

use bindings::docs::calculator::calculate::{self, Op};

fn parse_operator(op: &str) -> anyhow::Result<Op> {
    match op {
        "add" => Ok(Op::Add),
        _ => anyhow::bail!("Unknown operation: {}", op),
    }
}

impl fmt::Display for Op {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Op::Add => write!(f, "+"),
        }
    }
}

/// A CLI for executing mathematical expressions
/// using WebAssembly
#[derive(Parser)]
#[clap(name = "calculator", version = env!("CARGO_PKG_VERSION"))]
struct Command {
    /// The first operand
    x: u32,
    /// The second operand
    y: u32,
    /// Expression operator
    #[clap(value_parser = parse_operator)]
    op: Op,
}

impl Command {
    fn run(self) {
        let res = calculate::eval_expression(self.op, self.x, self.y);
        println!("{} {} {} = {res}", self.x, self.op, self.y);
    }
}

/// Struct off of which the implementation will hang
///
/// The name of this struct is not significant.
struct Component;

/// CLI entry point that the reactor exports through `wasi:cli/run`.
impl bindings::exports::wasi::cli::run::Guest for Component {
    fn run() -> Result<(), ()> {
        match Command::try_parse() {
            Ok(command) => {
                command.run();
                Ok(())
            }
            Err(err) => {
                // Printing can only fail if stdout/stderr are closed
                let _ = err.print();
                // clap reports `--help` and `--version` as "errors",
                // but they should not cause a failing exit code
                if err.use_stderr() { Err(()) } else { Ok(()) }
            }
        }
    }
}
}

Finally, build the component:

cargo build --target=wasm32-wasip2 --release

The resulting component can be found at target/wasm32-wasip2/release/command.wasm.

You can find the complete command project in the examples directory.

Composing the calculator

Now, we are ready to bring our components together into one runnable calculator component, using wac.

We will:

  1. Compose the calculator component with the add component to satisfy the calculator component’s adder import
  2. Compose that resolved calculator component once more with the command reactor to satisfy its calculate import.

The composed calculator exports wasi:cli/run. wasmtime supplies its WASI imports and calls run.

wac plug calculator.wasm --plug adder.wasm -o composed.wasm
wac plug command.wasm --plug composed.wasm -o final.wasm

Running the calculator

Now it all adds up! Run the final component with the wasmtime CLI, ensuring you are using a recent release (v14.0.0 or greater), as earlier releases of the wasmtime CLI do not include component model support.

$ wasmtime run final.wasm 1 2 add
1 + 2 = 3
$ wasmtime run final.wasm 8 5 add
8 + 5 = 13

To infinity and beyond!

To expand the exercise to add more components, modify calculator.wit to add another operator world and expand the op enum. Then, modify the command and calculator components to support the expanded enum.

Another extension of this tutorial could be to remove the op enum and instead modify eval-expression to take in a string that can then be parsed to determine which operator component to call. Maybe this parser is a component of its own?!