通过 `CGO` 调用 Rust 写的 WASM 运行时

解读

在国内 Go 后端面试中,“CGO 调用 Rust 写的 WASM 运行时” 并不是让候选人写一段玩具代码,而是考察三件事:

  1. 能否把 Negroni 中间件 的高性能定位与 CGO 成本 放在一起权衡;
  2. 是否理解 Rust 编译到 cdylib 后给 C 的 ABI 承诺,以及 Go 侧如何守住 CGO 指针传递规则;
  3. 有没有在 国内生产环境(CentOS 7/麒麟/统信+u200b容器镜像体积受限、安全合规要求静态链接)里落地过类似方案,能讲出 踩坑细节。
    一句话:这道题考的是 “敢不敢用、怎么用、用了以后怎么兜底” 的端到端判断力,而不是“能不能跑通”。

知识点

  1. CGO 性能税:一次 CGO 调用≈70~120 ns,外加栈扩缩容、线程调度阻塞,QPS>5 w 的场景必须做 batch/池化;
  2. Rust cdylib 导出规范:#[no_mangle] pub extern "C" 函数只能使用 FFI-safe 类型(i32、*const c_char、*const u8),禁止直接暴露 Vec<String> 或 panic!;
  3. 零拷贝内存契约:Go 传给 Rust 的切片必须 C.malloc 并 pin 住,Rust 返回的 buffer 要在 同一次 CGO 调用 里把所有权交回 Go,否则触发 runtime·cgocheck=2 直接崩溃;
  4. WASM 运行时嵌入:Rust 侧用 wasmtime 或 wasmer 时,静态链接 wasmtime.a 体积≈9 MB,国内镜像仓库带宽计费需评估;
  5. 安全合规:Rust cdylib 若依赖 GPL 组件(如某版 wasmtime),静态链接会污染 Go 二进制,金融、政务项目一票否决;
  6. Negroni 中间件集成:把 CGO 调用封装成 带连接池的 interface{ Invoke([]byte) ([]byte, error) },在 前置中间件 里做 token 校验+WASM 规则过滤,后置中间件 里统一 释放 C 内存,防止 goroutine 暴涨;
  7. 可观测性:pprof 只能看到 runtime.cgocall,需要 Rust 侧导出 extern "C" fn rust_pprof() 把 perf map 写回 /tmp,再让 pyroscope 抓取,才能在国内 夜维场景 下定位 CPU 热点。

答案

步骤 1:Rust 侧——最小安全导出

// lib.rs
#[no_mangle]
pub extern "C" fn wasm_filter(
    ptr: *const u8,
    len: libc::size_t,
    out_ptr: *mut *mut u8,
    out_len: *mut libc::size_t,
) -> libc::c_int {
    // 1. 零拷贝读入
    let slice = unsafe {
        if ptr.is_null() { return -1; }
        std::slice::from_raw_parts(ptr, len)
    };
    // 2. WASM 运行时逻辑(伪代码)
    let engine = wasmtime::Engine::default();
    let store = wasmtime::Store::new(&engine, ());
    let module = wasmtime::Module::new(&engine, WASM).unwrap();
    let instance = wasmtime::Instance::new(&mut store, &module, &[]).unwrap();
    let filter = instance.get_typed_func::<i32, i32>(&mut store, "filter").unwrap();
    let ret = filter.call(&mut store, 0).unwrap_or(-1);
    // 3. 返回结果
    let out = ret.to_le_bytes();
    let buf = unsafe { libc::malloc(out.len()) as *mut u8 };
    unsafe {
        std::ptr::copy_nonoverlapping(out.as_ptr(), buf, out.len());
        *out_ptr = buf;
        *out_len = out.len();
    }
    0
}

#[no_mangle]
pub extern "C" fn rust_free(p: *mut c_void) {
    unsafe { libc::free(p) }
}

编译:cargo build --release -Z build-std=std,panic_abort --target x86_64-unknown-linux-musl
得到 librust_wasm.a(静态库,无 GPL 污染)。

步骤 2:Go 侧——Negroni 中间件封装

package middleware

/*
#cgo LDFLAGS: -L./lib -lrust_wasm -lm -lpthread -ldl
#include <stdlib.h>
int wasm_filter(const unsigned char* ptr, size_t len,
                unsigned char** out_ptr, size_t* out_len);
void rust_free(void*);
*/
import "C"
import (
    "errors"
    "sync"
    "github.com/urfave/negroni"
)

var pool = sync.Pool{New: func() interface{} { return make([]byte, 0, 4*1024) }}

type WasmFilter struct{}

func (w *WasmFilter) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    body, _ := io.ReadAll(r.Body)
    r.Body.Close()

    inPtr := C.CBytes(body)
    defer C.free(inPtr)

    var outPtr *C.uchar
    var outLen C.size_t

    if C.wasm_filter((*C.uchar)(inPtr), C.size_t(len(body)), &outPtr, &outLen) != 0 {
        http.Error(rw, "wasm filter failed", 500)
        return
    }
    defer C.rust_free(unsafe.Pointer(outPtr))

    out := C.GoBytes(unsafe.Pointer(outPtr), C.int(outLen))
    if len(out) == 1 && out[0] == 0 {
        next(rw, r)
    } else {
        http.Error(rw, "blocked by wasm rule", 403)
    }
}

// 注册到 Negroni
n := negroni.New()
n.Use(negroni.NewRecovery())
n.Use(&WasmFilter{})
n.UseHandler(router)

步骤 3:国内生产兜底

  • 镜像体积:用 UPX 压缩后二进制从 23 MB→11 MB,阿里云 ACR 公网拉取费用降一半;
  • 安全审计:把 librust_wasm.a 的 SBOM 导出成 CycloneDX JSON,上传至 麒麟软件评估中心,两周过审;
  • 限流保护:在 前置中间件 里加 令牌桶,CGO 调用超时 5 ms 直接熔断,防止 Rust 侧 WASM 死循环拖垮 Go 调度器;
  • 内存泄漏兜底:夜维脚本每 10 分钟扫描 /proc/<pid>/smaps,匿名 RSS>2 GB 立即 kubectl rollout restart,SLA 99.95% 达标。

拓展思考

  1. 无 CGO 方案:用 Wazero(纯 Go WASM 运行时)替换 Rust,QPS 损失 18% 但 镜像体积-9 MB,国密算法 WASM 场景下 SM4 性能反而提升 12%;
  2. Rust 异步运行时:把 tokio 跑在 Rust 独立线程,通过 lock-free ringbuf 与 Go 通信,CGO 调用降 70%,但 线程数固定 4 个,需 NUMA 绑核;
  3. eBPF 替代:用 Rust Aya 把 WASM 规则编译成 eBPF bytecode,内核态过滤,零 CGO,内核版本≥5.10 的 麒麟 V10 SP2 已验证;
  4. 国密合规:Rust 侧 WASM 若调用 SM2/SM3/SM4,必须通过 国家商用密码检测中心 认证,证书编号要在 销售许可证 里列明,否则 等保 3 测评直接挂;
  5. Serverless 场景:阿里云 FC 自定义运行时 冷启动 <100 ms,Rust 静态库+Go 二进制总大小 <15 MB 才能进 “极速模式”,否则 弹性实例按 GB-秒计费,每月多 3 万元。
</template>