Deploying Rust-Generated WASM on Cloudfare Serverless Workers
source link: https://www.tuicool.com/articles/hit/JbQZVzq
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Recently open-sourced by Cloudfare , Wrangler is a set of CLI tools to build, preview, and publish to Cloudfare Workers written in Rust and compiled to WebAssembly.
Wrangler aims to provide an end-to-end experience for developers to be able to write their serverless functions in Rust and deploy and run them on Workers after translating them into WebAssembly.
To experiment with Wrangler, you can install it using cargo executing cargo install wrangler
. The general structure of a project generated by Wrangler includes a src
directory where Rust code is stored, a worker
directory containing a worker.js
where the Rust-generated code can be pulled in, and a couple of metadata files. Wrangler has three main commands: build
, preview
, and publish
. The bbuild
command will compile all Rust code to WebAssembly. The preview
command will allow you to run your function on Cloudfare infrastructure without requiring you to own an account.
Your Rust code is written as usual: you can bring in any external dependencies specifying it in you Cargo.toml
file ans you use
wasm_bindgen
to improve the communication between wasm and JS by enabling the use of strings, objects, classes and so on. For example, you could have this simple Rust file:
use wasm_bindgen::prelude::*; extern "C" { fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) -> String{ &format!("Hello, {}!", name); }
This code can be imported and executed in the worker.js
file using the following syntax:
const { greet } = wasm_bindgen; await wasm_bindgen(wasm) const output = greet('Worker')
Cloudfare Workers are serverless functions written in JavaScript that can be run in any of Cloudfare’s edge locations that are scattered across the world. According to Cloudfare, thanks to the proximity of their edge locations to end users, Workers improve performance by reducing network latency. Cloudfare Workers use the V8 JavaScript engine to run your code, but they do not use Node.js, instead relying on their own implementation of a number of APIs to improve efficiency and safety.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK