Wasm Component Model
Component Model adalah evolusi WebAssembly yang memungkinkan modul dari berbagai bahasa saling berkomunikasi melalui high-level interface types — tanpa manual memory management atau glue code.
Masalah yang Diselesaikan
- Wasm saat ini — Hanya bisa passing angka (i32, i64, f32, f64)
- String, list, record? — Harus manual encode/decode lewat linear memory
- Composability — Dua Wasm module dari bahasa berbeda susah diintegrasikan
WIT (Wasm Interface Type)
// image-processor.wit — definisi interface
package my:image-processor;
interface types {
record pixel {
r: u8,
g: u8,
b: u8,
a: u8,
}
record image {
width: u32,
height: u32,
pixels: list<pixel>,
}
enum filter {
grayscale,
blur,
sharpen,
sepia,
}
}
world image-processor {
import types;
export apply-filter: func(img: image, f: filter) -> image;
export resize: func(img: image, w: u32, h: u32) -> image;
}
Implement di Rust
// Cargo.toml
[dependencies]
wit-bindgen = "0.25"
// src/lib.rs
wit_bindgen::generate!({
world: "image-processor",
});
struct MyImageProcessor;
impl Guest for MyImageProcessor {
fn apply_filter(img: Image, f: Filter) -> Image {
match f {
Filter::Grayscale => {
let pixels = img.pixels.iter().map(|p| {
let gray = (0.299 * p.r as f32
+ 0.587 * p.g as f32
+ 0.114 * p.b as f32) as u8;
Pixel { r: gray, g: gray, b: gray, a: p.a }
}).collect();
Image { pixels, ..img }
}
_ => img,
}
}
fn resize(img: Image, w: u32, h: u32) -> Image {
// resize implementation
todo!()
}
}
export!(MyImageProcessor);
Compose Components
# Install tooling
cargo install wasm-tools
# Compile ke component
cargo component build --release
# Compose dua components
wasm-tools compose \
--definitions image-processor.wasm \
--adapter cache-layer.wasm \
-o composed.wasm
# Inspect component
wasm-tools component wit composed.wasm
Keuntungan Component Model
- Rich types — String, list, record, variant, enum — bukan cuma angka
- Language agnostic — Component dari Rust bisa dipanggil oleh Go, Python, JS
- Composable — Gabungkan components seperti LEGO blocks
- Sandboxed — Setiap component punya memory terpisah
- Versioned interfaces — WIT package bisa di-version seperti npm package
Status
- Spec — Phase 2 di W3C WebAssembly CG
- Tooling — wasm-tools, wit-bindgen, cargo-component sudah usable
- Runtime — Wasmtime, WAMR support component model
- Browser — Belum native, tapi bisa polyfill dengan jco