Skip to content

This tutorial will walk through how to build, compose, and run WebAssembly components through a calculator example.

License

Notifications You must be signed in to change notification settings

mytechnotalent/webassembly-component-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WebAssembly Component Tutorial

License: MIT Rust WebAssembly

A comprehensive tutorial demonstrating the WebAssembly Component Model with Rust. This project builds a modular calculator using composable WASM components.


Overview

This tutorial walks you through building, composing, and running a component-model calculator example. The architecture demonstrates how WebAssembly components can be developed independently and composed together at deployment time.

Components

Component Description Exports Imports
adder Addition arithmetic docs:adder/add None
subtractor Subtraction arithmetic docs:subtractor/subtract None
calculator Expression evaluator docs:calculator/calculate adder, subtractor
command CLI interface wasi:cli/run calculator

Prerequisites

Install the following tools:

# Rust toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# cargo-component for building WASM components
cargo install cargo-component --locked

# wac CLI for component composition
cargo install wac-cli

# wasmtime runtime
curl https://wasmtime.dev/install.sh -sSf | bash

After installing wasmtime, restart your shell to ensure the binary is on your PATH.


Project Structure

webassembly-component-tutorial/
├── adder/                      # Addition component
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs              # Add implementation with tests
│       └── bindings.rs         # Auto-generated WIT bindings
├── subtractor/                 # Subtraction component
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs              # Subtract implementation with tests
│       └── bindings.rs
├── calculator/                 # Calculator component
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs              # Expression evaluator with tests
│       └── bindings.rs
├── command/                    # CLI component
│   ├── Cargo.toml
│   └── src/
│       ├── main.rs             # CLI entry point with tests
│       └── bindings.rs
├── wit/                        # WIT interface definitions
│   ├── adder/world.wit
│   ├── subtractor/world.wit
│   └── calculator/world.wit
├── README.md
└── LICENSE

WIT Interfaces

The WebAssembly Interface Types (WIT) define the contracts between components.

adder/world.wit

package docs:adder@0.1.0;

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

world adder {
    export add;
}

subtractor/world.wit

package docs:subtractor@0.1.0;

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

world subtractor {
    export subtract;
}

calculator/world.wit

package docs:calculator@0.1.0;

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

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

world app {
    import calculate;
}

Building Components

Build All Components

# Build each component for WebAssembly
cd adder && cargo component build --release && cd ..
cd subtractor && cargo component build --release && cd ..
cd calculator && cargo component build --release && cd ..
cd command && cargo component build --release && cd ..

Output Locations

Component Output Path
adder adder/target/wasm32-wasip1/release/adder.wasm
subtractor subtractor/target/wasm32-wasip1/release/subtractor.wasm
calculator calculator/target/wasm32-wasip1/release/calculator.wasm
command command/target/wasm32-wasip1/release/command.wasm

Component Composition

Use wac to compose components into a single executable:

# Step 1: Compose calculator with arithmetic components
wac plug calculator/target/wasm32-wasip1/release/calculator.wasm \
  --plug adder/target/wasm32-wasip1/release/adder.wasm \
  --plug subtractor/target/wasm32-wasip1/release/subtractor.wasm \
  -o composed.wasm

# Step 2: Compose command with the calculator
wac plug command/target/wasm32-wasip1/release/command.wasm \
  --plug composed.wasm \
  -o final.wasm

Running the Calculator

Execute the composed component with wasmtime:

# Addition
wasmtime run final.wasm -- 5 3 add
# Output: 5 + 3 = 8

# Subtraction
wasmtime run final.wasm -- 10 4 subtract
# Output: 10 - 4 = 6

Testing

Each component includes comprehensive unit tests.

Run All Tests

# Test all components
cargo test --manifest-path adder/Cargo.toml
cargo test --manifest-path subtractor/Cargo.toml
cargo test --manifest-path calculator/Cargo.toml
cargo test --manifest-path command/Cargo.toml

Test Summary

Component Tests Coverage
adder 6 Zero, basic, large numbers, commutative, identity, max boundary
subtractor 6 Zero, basic, equal, large numbers, max boundary, identity
calculator 7 Add/subtract operations, zeros, large numbers, commutativity
command 7 Operator parsing, display formatting, case sensitivity
Total 26

Architecture

┌─────────────────────────────────────────────────────────────┐
│                        command                               │
│                   (CLI Interface)                            │
│                 exports: wasi:cli/run                        │
└─────────────────────────┬───────────────────────────────────┘
                          │ imports
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      calculator                              │
│                 (Expression Evaluator)                       │
│              exports: docs:calculator/calculate              │
└──────────────┬─────────────────────────────┬────────────────┘
               │ imports                     │ imports
               ▼                             ▼
┌──────────────────────────┐   ┌──────────────────────────────┐
│          adder           │   │         subtractor           │
│    (Addition Logic)      │   │     (Subtraction Logic)      │
│ exports: docs:adder/add  │   │ exports: docs:subtractor/    │
│                          │   │          subtract            │
└──────────────────────────┘   └──────────────────────────────┘

Key Concepts

WebAssembly Component Model

The Component Model extends WebAssembly with:

  • Interface Types (WIT): Language-agnostic interface definitions
  • Composition: Linking components at deployment time
  • Isolation: Each component runs in its own sandbox

Design Patterns Used

  1. Separation of Concerns: Each arithmetic operation is its own component
  2. Dependency Injection: Calculator imports its dependencies via WIT
  3. Testability: Core logic separated from WASM bindings for unit testing

Documentation

All source files include comprehensive Rust documentation:

  • MIT License headers
  • Module-level //! documentation
  • Function docstrings with # Details, # Arguments, # Returns sections
  • Inline comments explaining logic
  • Test documentation

Generate documentation locally:

cargo doc --manifest-path adder/Cargo.toml --open

License

MIT License

Copyright (c) 2025 Kevin Thomas

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Releases

No releases published

Packages

No packages published

Languages