Wasm di Edge (Cloudflare Workers) — WebAssembly

Wasm di Edge: Cloudflare Workers Cloudflare Workers memungkinkan kamu menjalankan Wasm di 300+ edge locations worldwide. Kombinasi Wasm + edge = cold start…

Wasm di Edge: Cloudflare Workers

Cloudflare Workers memungkinkan kamu menjalankan Wasm di 300+ edge locations worldwide. Kombinasi Wasm + edge = cold start super cepat dan latency rendah untuk user di seluruh dunia.

Kenapa Wasm di Edge?

Setup

# Install wrangler CLI
npm install -g wrangler

# Login
wrangler login

# Buat project baru
wrangler init my-wasm-worker
cd my-wasm-worker

Contoh: Image Resize di Edge

// src/lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn resize_image(
    input: &[u8],
    src_width: u32,
    src_height: u32,
    dst_width: u32,
    dst_height: u32,
) -> Vec<u8> {
    let mut output = vec![0u8; (dst_width * dst_height * 4) as usize];

    // Bilinear interpolation
    for y in 0..dst_height {
        for x in 0..dst_width {
            let src_x = (x as f32 * src_width as f32) / dst_width as f32;
            let src_y = (y as f32 * src_height as f32) / dst_height as f32;

            let sx = src_x as u32;
            let sy = src_y as u32;
            let src_idx = ((sy * src_width + sx) * 4) as usize;
            let dst_idx = ((y * dst_width + x) * 4) as usize;

            output[dst_idx..dst_idx + 4]
                .copy_from_slice(&input[src_idx..src_idx + 4]);
        }
    }
    output
}
// worker.js
import init, { resize_image } from "./pkg/my_wasm.js";

export default {
  async fetch(request) {
    await init();

    const url = new URL(request.url);
    const imageUrl = url.searchParams.get("url");
    const width = parseInt(url.searchParams.get("w") || "200");

    // Fetch original image
    const response = await fetch(imageUrl);
    const buffer = await response.arrayBuffer();
    const pixels = new Uint8Array(buffer);

    // Resize dengan Wasm (sangat cepat di edge!)
    const resized = resize_image(pixels, 800, 600, width, width * 0.75);

    return new Response(resized, {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "public, max-age=86400",
      },
    });
  },
};

Deploy

# Build Wasm
wasm-pack build --target bundler

# Deploy ke Cloudflare edge (300+ locations)
wrangler deploy

# Test
curl https://my-wasm-worker.username.workers.dev/?url=image.jpg&w=400

Platform Lain

Yang akan kamu pelajari