Skip to content
Edge Functions

使用 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.

1
Create a new Edge Function

创建一个名为 wasm-add 的新 Edge 函数

1
supabase functions new wasm-add
2
Create a new Cargo project

在函数目录内为 Wasm 模块创建一个新的 Cargo 项目:

1
cd supabase/functions/wasm-add
2
cargo new --lib add-wasm
3
Add the Wasm module code

把下面的代码加到 add-wasm/src/lib.rs 里。

1
use wasm_bindgen::prelude::*;
2
3
#[wasm_bindgen]
4
pub fn add(a: u32, b: u32) -> u32 {
5
a + b
6
}
View source
4
Update the Cargo.toml file

add-wasm/Cargo.toml 更新一下,加入 wasm-bindgen 依赖。

1
[package]
2
name = "add-wasm"
3
version = "0.1.0"
4
description = "A simple wasm module that adds two numbers"
5
license = "MIT/Apache-2.0"
6
edition = "2021"
7
8
[lib]
9
crate-type = ["cdylib"]
10
11
[dependencies]
12
wasm-bindgen = "0.2"
View source
5
Build the Wasm module

通过运行以下命令来构建这个包:

1
wasm-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:

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
import { add } from './add-wasm/pkg/add_wasm.js'
4
5
// Authenticated endpoint, so deploy with verify_jwt = true.
6
export 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
}
View source

打包和部署 #

🌐 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:

1
[functions.wasm-add]
2
static_files = [ "./functions/wasm-add/add-wasm/pkg/*"]

通过运行来部署函数:

🌐 Deploy the function by running:

1
supabase functions deploy wasm-add