spinny:~/writing $ vim webassembly-wasm-complete-guide.md
1~2WebAssembly (WASM) ban dau duoc tao ra de chay C++ trong trinh duyet. Vao nam 2026, no chay o moi noi - trinh duyet, may chu, mang Edge, thiet bi nhung - va cung cap suc manh cho nhung ung dung doi hoi cao nhat tren web. Engine render cua Figma, Adobe Photoshop tren web, xu ly video cua Google Meet, va nen tang Edge Compute cua Cloudflare deu chay tren WebAssembly.3~4Chrome Platform Status cho thay WASM chiem khoang 5.5% tong so lan tai trang tren Chrome tinh den dau nam 2026, tang tu 4.5% nam truoc. Voi WASM 3.0 tro thanh chuan W3C va WASI chin muoi huong toi phien ban 1.0, he sinh thai da dat den diem chuyen doi.5~6Huong dan nay bao gom moi thu ban can biet de bat dau xay dung voi WebAssembly.7~8## WebAssembly la gi?9~10WebAssembly la mot dinh dang lenh nhi phan duoc thiet ke lam muc tieu bien dich. Ban viet code bang ngon ngu bac cao (Rust, C, C++, Go, Kotlin), bien dich thanh `.wasm`, va chay trong bat ky moi truong nao co WASM Runtime - trinh duyet, Node.js, Cloudflare Workers, Wasmtime, hoac Wasmer.11~12```mermaid13graph LR14 Rust[Rust / C / C++] --> Compiler[Compiler]15 Compiler --> WASM[.wasm Binary]16 WASM --> Browser[Browser V8/SpiderMonkey]17 WASM --> Server[Server Wasmtime]18 WASM --> Edge[Edge Cloudflare Workers]19 WASM --> Embedded[Embedded WAMR]20```21~22### Cach thuc hoat dong23~24WASM la mot **may ao dua tren stack**. Cac ham day va lay gia tri tren stack toan hang. Host Runtime (V8 trong Chrome, SpiderMonkey trong Firefox) bien dich JIT WASM Bytecode thanh ma may goc, do la ly do hieu suat gan voi Native.25~26Cac dac diem chinh:27~28- **Thuc thi trong Sandbox**: Cac module WASM chi co the truy cap tai nguyen ma Host cho phep mot cach ro rang. Khong co quyen truy cap he thong file, mang, hay OS tru khi duoc cap phep. Dieu nay khac biet co ban so voi Native Code.29- **Linear Memory**: mot `ArrayBuffer` lien tuc duy nhat duoc chia se giua WASM va Host. Du lieu phuc tap (chuoi, struct) duoc truyen bang cach ghi vao bo nho va chia se Pointer.30- **Han che ve kieu du lieu**: WASM chi ho tro bon kieu goc: `i32`, `i64`, `f32`, `f64`. Moi thu khac (chuoi, mang, object) can ma hoa thong qua Linear Memory hoac Component Model.31- **Di dong**: cung mot file nhi phan `.wasm` chay tren bat ky nen tang nao co WASM Runtime, khong can bien dich lai.32~33### WASM vs JavaScript34~35WASM khong thay the JavaScript. No bo sung cho JavaScript.36~37| Khia canh | JavaScript | WebAssembly |38|--------|-----------|-------------|39| **Phan tich cu phap** | Parse + Compile luc Runtime | Nhi phan da bien dich san, chi Decode |40| **Toc do thuc thi** | JIT-optimized, bien dong | Gan Native, on dinh |41| **Khoi dong** | Nhanh cho script nho | Decode nhanh, du doan duoc |42| **Truy cap DOM** | Truc tiep | Gian tiep (qua JS Glue) |43| **Phu hop nhat cho** | UI, thao tac DOM, xu ly su kien | Tinh toan su dung nhieu CPU |44| **Garbage Collection** | Co san | WasmGC (moi) hoac thu cong |45~46Su dung JavaScript cho UI va thao tac DOM. Su dung WASM cho tinh toan nang: xu ly anh, ma hoa video, mo phong vat ly, mat ma hoc, phan tich du lieu.47~48## WASM 3.0: Co gi moi49~50WebAssembly 3.0 tro thanh chuan W3C vao thang 9 nam 2025, chuan hoa chin tinh nang da duoc phat trien trong nhieu nam.51~52| Tinh nang | Kha nang mo ra |53|---------|----------------|54| **WasmGC** | Garbage Collection goc trong WASM. Cac ngon ngu co quan ly bo nho (Java, Kotlin, Dart) co the bien dich sang WASM ma khong can mang theo GC Runtime rieng. Ho tro tren Chrome 119+, Firefox 120+, Safari 18.2+. |55| **Exception Handling** | `try`/`catch` goc trong WASM. Truoc day, Exception can Roundtrip ton kem sang JavaScript. |56| **Tail Calls** | Cho phep de quy hieu qua ma khong bi tran stack. Rat quan trong cho ngon ngu Functional. |57| **Relaxed SIMD** | Lenh vector 128-bit de xu ly du lieu song song. Cho phep toi uu hoa dac thu phan cung. |58| **Memory64** | Vuot qua gioi han Linear Memory 4GB. Can thiet cho xu ly du lieu lon. |59| **Multi-memory** | Nhieu vung bo nho doc lap trong mot module. |60~61Co tac dong lon nhat la **WasmGC**. Truoc do, bien dich Java hoac Kotlin sang WASM dong nghia voi viec mang theo toan bo Garbage Collector nhu mot phan cua file nhi phan, lam phong kich thuoc file. Bay gio GC cua chinh trinh duyet xu ly quan ly bo nho cho cac module WASM, giong nhu cach no xu ly cho JavaScript.62~63## WASI: WebAssembly ngoai trinh duyet64~65WASM trong trinh duyet da manh me, nhung **WASI (WebAssembly System Interface)** la thu lam cho WASM tro thanh Runtime pho thong. WASI cung cap cac giao dien chuan hoa cho tai nguyen he thong - file, mang, dong ho, so ngau nhien - cho phep cac module WASM chay ben ngoai trinh duyet.66~67```mermaid68graph TD69 subgraph "Browser"70 B[WASM Module] --> Web[Web APIs\nDOM, Fetch, Canvas]71 end72~73 subgraph "Server / Edge / Embedded"74 S[WASM Module] --> WASI[WASI Interfaces]75 WASI --> FS[wasi:filesystem]76 WASI --> Net[wasi:sockets]77 WASI --> HTTP[wasi:http]78 WASI --> Clock[wasi:clocks]79 WASI --> Rand[wasi:random]80 end81```82~83WASI Preview 2 (ban phat hanh on dinh hien tai) dinh nghia cac giao dien sau:84~85- `wasi:filesystem` - thao tac file thong qua Capability Handle (khong phai File Descriptor truyen thong)86- `wasi:sockets` - mang TCP/UDP87- `wasi:http` - xu ly HTTP Request/Response88- `wasi:clocks` - Wall Clock, Monotonic Clock89- `wasi:random` - so ngau nhien mat ma hoc90- `wasi:cli` - doi so dong lenh, bien moi truong, Standard I/O91~92Nguyen tac chinh la **bao mat dua tren Capability**: mot module WASM khong the truy cap he thong file tru khi Host cap ro rang mot Handle den mot thu muc cu the. Dieu nay lam cho WASI an toan hon co ban so voi viec chay file thuc thi goc.93~94### Hanh trinh den WASI 1.095~96WASI 0.3.0 (them Async/Concurrency Primitive) du kien trong nam 2026, voi WASI 1.0 theo sau. Bo sung chinh la Async tich hop ngon ngu voi Zero-copy Streaming I/O.97~98## Component Model99~100Cac module WASM loi chi co the trao doi so. **Component Model** giai quyet han che nay bang cach them mot he thong kieu du lieu phong phu va lop Composability tren WASM.101~102### WIT (WebAssembly Interface Types)103~104WIT la mot Ngon ngu Dinh nghia Giao dien cho phep cac Component khai bao Import va Export voi cac kieu du lieu phong phu - chuoi, Record, danh sach, Variant, Enum - khong chi `i32` va `f64`.105~106```wit107// calculator.wit108package myorg:calculator@1.0.0;109~110interface operations {111 record calculation {112 expression: string,113 result: f64,114 timestamp: u64,115 }116~117 add: func(a: f64, b: f64) -> f64;118 multiply: func(a: f64, b: f64) -> f64;119 history: func() -> list<calculation>;120}121~122world calculator {123 export operations;124}125```126~127Cac Toolchain nhu `wit-bindgen` tao ra Binding dac thu ngon ngu tu cac file WIT. Mot Component Rust va mot Component Python co the trao doi chuoi, Record va danh sach thong qua WIT Contract ma khong can biet ngon ngu cua phia con lai.128~129## Xay dung module WASM dau tien voi Rust130~131Rust co bo cong cu WASM chin muoi nhat. Hay xay dung mot vi du thuc te: mot module xu ly anh chay trong trinh duyet.132~133### Thiet lap134~135```bash136# Install the WASM target for Rust137rustup target add wasm32-unknown-unknown138~139# Install wasm-pack (builds Rust to WASM + generates JS bindings)140cargo install wasm-pack141~142# Create a new library project143cargo new --lib image-processor144cd image-processor145```146~147### Cau hinh Cargo.toml148~149```toml150[package]151name = "image-processor"152version = "0.1.0"153edition = "2021"154~155[lib]156crate-type = ["cdylib"]157~158[dependencies]159wasm-bindgen = "0.2"160```161~162### Viet code Rust163~164```rust165// src/lib.rs166use wasm_bindgen::prelude::*;167~168/// Convert an image buffer to grayscale.169/// Input: RGBA pixel data as a flat u8 array (4 bytes per pixel).170/// Output: Modified in place for zero-copy performance.171#[wasm_bindgen]172pub fn grayscale(pixels: &mut [u8]) {173 for chunk in pixels.chunks_exact_mut(4) {174 let r = chunk[0] as f32;175 let g = chunk[1] as f32;176 let b = chunk[2] as f32;177 // ITU-R BT.709 luminance coefficients178 let gray = (0.2126 * r + 0.7152 * g + 0.0722 * b) as u8;179 chunk[0] = gray;180 chunk[1] = gray;181 chunk[2] = gray;182 // chunk[3] is alpha, leave unchanged183 }184}185~186/// Adjust brightness of an image.187/// factor > 1.0 brightens, < 1.0 darkens.188#[wasm_bindgen]189pub fn adjust_brightness(pixels: &mut [u8], factor: f32) {190 for chunk in pixels.chunks_exact_mut(4) {191 chunk[0] = ((chunk[0] as f32 * factor).min(255.0)) as u8;192 chunk[1] = ((chunk[1] as f32 * factor).min(255.0)) as u8;193 chunk[2] = ((chunk[2] as f32 * factor).min(255.0)) as u8;194 }195}196~197/// Invert all colors in the image.198#[wasm_bindgen]199pub fn invert(pixels: &mut [u8]) {200 for chunk in pixels.chunks_exact_mut(4) {201 chunk[0] = 255 - chunk[0];202 chunk[1] = 255 - chunk[1];203 chunk[2] = 255 - chunk[2];204 }205}206~207/// Calculate the average brightness of an image (0-255).208#[wasm_bindgen]209pub fn average_brightness(pixels: &[u8]) -> f32 {210 let mut total: f64 = 0.0;211 let pixel_count = pixels.len() / 4;212 for chunk in pixels.chunks_exact(4) {213 let luminance = 0.2126 * chunk[0] as f64214 + 0.7152 * chunk[1] as f64215 + 0.0722 * chunk[2] as f64;216 total += luminance;217 }218 (total / pixel_count as f64) as f32219}220```221~222### Build223~224```bash225wasm-pack build --target web226```227~228Lenh nay tao ra thu muc `pkg/` voi:229- `image_processor_bg.wasm` - file nhi phan WASM da bien dich230- `image_processor.js` - ma JavaScript Glue voi dinh nghia kieu TypeScript231- `package.json` - san sang xuat ban len npm232~233### Su dung trong JavaScript234~235```html236<!DOCTYPE html>237<html>238<head><title>WASM Image Processor</title></head>239<body>240 <canvas id="canvas" width="800" height="600"></canvas>241 <button onclick="applyGrayscale()">Grayscale</button>242 <button onclick="applyBrightness()">Brighten</button>243 <button onclick="applyInvert()">Invert</button>244~245 <script type="module">246 import init, { grayscale, adjust_brightness, invert } from "./pkg/image_processor.js";247~248 let ctx;249 let imageData;250~251 async function setup() {252 await init();253 const canvas = document.getElementById("canvas");254 ctx = canvas.getContext("2d");255~256 // Load an image onto the canvas257 const img = new Image();258 img.onload = () => {259 ctx.drawImage(img, 0, 0);260 imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);261 };262 img.src = "photo.jpg";263 }264~265 window.applyGrayscale = () => {266 grayscale(imageData.data);267 ctx.putImageData(imageData, 0, 0);268 };269~270 window.applyBrightness = () => {271 adjust_brightness(imageData.data, 1.3);272 ctx.putImageData(imageData, 0, 0);273 };274~275 window.applyInvert = () => {276 invert(imageData.data);277 ctx.putImageData(imageData, 0, 0);278 };279~280 setup();281 </script>282</body>283</html>284```285~286Diem mau chot: `imageData.data` la mot `Uint8ClampedArray` duoc ho tro boi `ArrayBuffer`. Khi truyen sang WASM, no chia se cung bo nho - khong sao chep. Ham Rust sua doi pixel tai cho, va phia JavaScript thay doi ngay lap tuc.287~288## Cap thap: Khoi tao WASM thu cong289~290Neu ban khong muon su dung `wasm-bindgen`, ban co the khoi tao module WASM truc tiep:291~292```javascript293const response = await fetch("calculator.wasm");294const { instance } = await WebAssembly.instantiateStreaming(response, {295 env: {296 // Functions the WASM module can call297 log_result: (value) => console.log("Result:", value),298 },299});300~301// Call exported functions302const { add, multiply } = instance.exports;303console.log(add(5, 3)); // 8304console.log(multiply(4, 7)); // 28305```306~307Dieu nay huu ich khi ban muon Overhead toi thieu va khong can Rich Type Interop.308~309## Hieu suat: WASM vs JavaScript310~311Benchmark thuc te cho thay tang toc dang ke cho cac tac vu su dung nhieu CPU:312~313| Tac vu | JavaScript | WASM | Tang toc |314|------|-----------|------|---------|315| Xu ly anh 4K | 180ms | 8ms (voi SIMD) | 22 lan |316| Thay doi kich thuoc anh (4K) | 250ms | 45ms | 5.5 lan |317| Mo phong vat ly (10K Entity) | Mat frame | 60fps muot ma | Khoang 10 lan |318| Phan tich JSON (Payload lon) | 12ms | 3ms | 4 lan |319| Hash mat ma hoc | 45ms | 6ms | 7.5 lan |320~321WASM chay o khoang 95% toc do Native Code. Loi ich lon nhat den tu:322- Hieu suat du doan duoc (khong co JIT Warmup, khong co GC Pause)323- Lenh SIMD cho xu ly du lieu song song324- Truy cap bo nho truc tiep khong bi Garbage Collector can thiep325~326Noi WASM khong nhanh hon: thao tac DOM, tinh toan nho, tac vu I/O-bound. JavaScript da duoc toi uu hoa cho nhung thu nay roi.327~328## Cac truong hop su dung trong Production329~330### Figma: Render vector thoi gian thuc331~332Engine render cot loi cua Figma la C++ bien dich sang WASM. Moi hinh dang, Gradient va hieu ung deu duoc tinh toan trong WASM va ve len Canvas Element. Dieu nay cho phep Figma xu ly cac thiet ke phuc tap voi hang ngan Layer o 60fps trong trinh duyet - hieu suat khong the dat duoc voi JavaScript thuan.333~334### Adobe Photoshop tren web335~336Adobe da chuyen cac bo loc va cong cu chinh cua Photoshop sang WASM bang Rust. Benchmark cua ho cho thay xu ly anh 4K trong 22ms voi WASM SIMD so voi 180ms trong JavaScript - cai thien 8 lan giup xem truoc bo loc thoi gian thuc tro nen kha thi.337~338### Cloudflare Workers339~340Cloudflare chay cac module WASM trong V8 Isolate tren hon 330 dia diem Edge. Cold Start mat 1-5ms (so voi 100-500ms cho Serverless dua tren Container). Vao thang 2 nam 2026, ho da trien khai Inference cua Llama-3-8b tren toan bo mang Edge bang WASM.341~342### Google Meet343~344Background Blur va Virtual Background trong Google Meet su dung WASM voi SIMD de xu ly video thoi gian thuc. Module WASM xu ly tung frame video du nhanh de duy tri video muot ma o 30fps.345~346## Ho tro trinh duyet (2026)347~348| Tinh nang | Chrome | Firefox | Safari | Edge |349|---------|--------|---------|--------|------|350| Core WASM | Day du | Day du | Day du | Day du |351| Threads | Co | Co | Co | Co |352| SIMD (128-bit) | Co | Co | Co | Co |353| WasmGC | 119+ | 120+ | 18.2+ | Co |354| Exception Handling | Co | Co | Co | Co |355| Memory64 | Co | Co | Mot phan | Co |356~357Tat ca cac trinh duyet chinh deu ho tro day du WASM. Cac tinh nang moi hon (WasmGC, Exception Handling) da dat duoc su ho tro rong rai.358~359## Tai lieu tham khao cong cu360~361| Cong cu | Muc dich | Cai dat |362|------|---------|---------|363| **wasm-pack** | Build Rust sang WASM, tao package npm | `cargo install wasm-pack` |364| **wasm-bindgen** | Rust/JS Interop Binding (su dung boi wasm-pack) | Dependency trong Cargo.toml |365| **wasm-opt** | Toi uu hoa kich thuoc nhi phan (giam 50%+) | Mot phan cua Binaryen: `brew install binaryen` |366| **wit-bindgen** | Tao Binding tu file WIT | `cargo install wit-bindgen-cli` |367| **Wasmtime** | WASM Runtime phia may chu (WASI Reference Implementation) | `brew install wasmtime` |368| **Wasmer** | WASM Runtime thay the ho tro WASI | `curl https://get.wasmer.io -sSfL \| sh` |369| **wasm-feature-detect** | Phat hien tinh nang trinh duyet luc Runtime | `npm install wasm-feature-detect` |370~371### Toi uu hoa kich thuoc nhi phan372~373File nhi phan WASM co the lon. Day la cach thu nho chung:374~375```toml376# Cargo.toml377[profile.release]378opt-level = "z" # Optimize for size379lto = true # Link-time optimization380codegen-units = 1 # Better optimization, slower compile381strip = true # Strip debug symbols382```383~384```bash385# Build in release mode386wasm-pack build --release --target web387~388# Further optimize with wasm-opt389wasm-opt -Oz pkg/image_processor_bg.wasm -o pkg/image_processor_bg.wasm390```391~392Mot module Rust WASM dien hinh giam tu 500KB xuong duoi 50KB voi nhung toi uu hoa nay.393~394## Lo trinh bat dau395~396```mermaid397flowchart TD398 A[Week 1: Basics] --> B[Week 2: Real Project]399 B --> C[Week 3: WASI and Server-side]400 C --> D[Month 2+: Production]401~402 A --> A1[Install Rust + wasm-pack]403 A --> A2[Build hello-world WASM module]404 A --> A3[Call WASM functions from JavaScript]405~406 B --> B1[Build image processor or game physics]407 B --> B2[Use wasm-bindgen for rich types]408 B --> B3[Benchmark against pure JS]409~410 C --> C1[Run WASM with Wasmtime]411 C --> C2[Explore WASI interfaces]412 C --> C3[Try Component Model with WIT]413~414 D --> D1[Optimize binary size]415 D --> D2[Use SIMD for parallelism]416 D --> D3[Deploy to Cloudflare Workers or browser]417```418~419## Ket luan420~421WebAssembly khong con la cong nghe thu nghiem. No la cong nghe Production duoc su dung boi nhung ung dung doi hoi cao nhat tren web. Hieu suat gan Native, bao mat Sandbox, va kha nang di dong pho thong - khong co Compilation Target nao khac mang lai ca ba dieu nay.422~423Ban khong can viet lai toan bo ung dung bang WASM. Bat dau voi mot ham su dung nhieu CPU - mot bo loc anh, mot trinh phan tich du lieu, mot phep tinh vat ly - bien dich sang WASM va goi tu JavaScript. Do su khac biet. Sau do quyet dinh WASM co the giup gi them.424~425Cong cu da chin muoi, ho tro trinh duyet la pho thong, va he sinh thai dang phat trien. Neu ban viet Rust, ban chi cach trinh duyet mot lenh duy nhat.426~427> **Danh sach kiem tra bat dau:**428>429> - [x] Da cai dat Rust va wasm-pack430> - [x] Build module WASM dau tien va chay trong trinh duyet431> - [x] Tuong tac JavaScript hoat dong (goi WASM tu JS)432> - [x] Build phat hanh voi toi uu hoa kich thuoc da ap dung433> - [x] Benchmark hieu suat so voi JavaScript thuan tuong duong434> - [x] Kham pha WASI voi Wasmtime cho cac truong hop su dung phia may chu435~
NORMAL · webassembly-wasm-complete-guide.md [readonly]435 lines · :q to close