使用 Wasm 模块
Use WebAssembly in Edge Functions.
Edge Functions 支持运行 WebAssembly (Wasm) 模块。如果你想优化在 JavaScript 中运行较慢的代码,或需要进行底层操作,WebAssembly 会很有用。
🌐 Edge Functions supports running WebAssembly (Wasm) modules. WebAssembly is useful if you want to optimize code that's slower to run in JavaScript or require low-level manipulation.
这让你可以:
🌐 This allows you to:
- 优化性能关键的代码,超越 JavaScript 的能力
- 把其他语言(C、C++、Rust)的现有库移植到 JavaScript
- 访问 JavaScript 无法使用的低级系统操作
例如,像 magick-wasm 这样的库将现有的 C 库移植到 WebAssembly,用于复杂的图片处理。
🌐 For example, libraries like magick-wasm port existing C libraries to WebAssembly for complex image processing.
编写 Wasm 模块 #
🌐 Writing a Wasm module
你可以使用不同的语言和 SDK 来编写 Wasm 模块。在本教程中,我们将用 Rust 编写一个基本的 Wasm 模块,用来相加两个数字。
🌐 You can use different languages and SDKs to write Wasm modules. For this tutorial, we will write a basic Wasm module in Rust that adds two numbers.
按照这个用 Rust 编写 Wasm 模块的指南来设置你的开发环境。
🌐 Follow this guide on writing Wasm modules in Rust to setup your dev environment.
创建一个名为 wasm-add 的新 Edge 函数
1supabase functions new wasm-add在函数目录内为 Wasm 模块创建一个新的 Cargo 项目:
1cd supabase/functions/wasm-add2cargo new --lib add-wasm把下面的代码加到 add-wasm/src/lib.rs 里。
1use wasm_bindgen::prelude::*;23#[wasm_bindgen]4pub fn add(a: u32, b: u32) -> u32 {5 a + b6}把 add-wasm/Cargo.toml 更新一下,加入 wasm-bindgen 依赖。
1[package]2name = "add-wasm"3version = "0.1.0"4description = "A simple wasm module that adds two numbers"5license = "MIT/Apache-2.0"6edition = "2021"78[lib]9crate-type = ["cdylib"]1011[dependencies]12wasm-bindgen = "0.2"通过运行以下命令来构建这个包:
1wasm-pack build --target deno这将在 add-wasm/pkg 目录下生成一个 Wasm 二进制文件。
从 Edge Function 调用 Wasm 模块 #
🌐 Calling the Wasm module from the Edge Function
更新你的 Edge 函数以调用来自 Wasm 模块的 add 函数:
🌐 Update your Edge Function to call the add function from the Wasm module:
1import { withSupabase } from 'npm:@supabase/server@^1'23import { add } from './add-wasm/pkg/add_wasm.js'45// Authenticated endpoint, so deploy with verify_jwt = true.6export default {7 fetch: withSupabase({ auth: 'user' }, async (req) => {8 const { a, b } = await req.json()9 return Response.json({ result: add(a, b) })10 }),11}Supabase Edge 功能目前使用 Deno 1.46。从 Deno 2.1 开始,导入 Wasm 模块 将需要更少的样板代码。
🌐 Supabase Edge Functions currently use Deno 1.46. From Deno 2.1, importing Wasm modules will require even less boilerplate code.
打包和部署 #
🌐 Bundle and deploy
在部署之前,确保通过在 supabase/config.toml 中定义,将 Wasm 模块与你的函数打包在一起:
🌐 Before deploying, ensure the Wasm module is bundled with your function by defining it in supabase/config.toml:
- 你需要将 Supabase CLI 更新到 2.7.0 或更高版本,以支持
static_files。 - 静态文件不能使用
--use-apiAPI 标志部署。你需要用 命令行上的 Docker 来构建它们。
1[functions.wasm-add]2static_files = [ "./functions/wasm-add/add-wasm/pkg/*"]通过运行来部署函数:
🌐 Deploy the function by running:
1supabase functions deploy wasm-add