Creating Web Assembly

Planetr Functions is powered by WebAssembly. We chose WebAssembly because it's an emerging technology that we believe lays the foundation for what function computing will become: a more performant and flexible place to deliver websites and applications.

Prerequisites

  • Basic understanding of Rust programming language
  • Rust and Cargo installed (steps below)
  • Planetr Gateway installed and running

Install Rust and Cargo

Follow this link to install Rust and Cargo.

Install cargo-generate

We will use a scaffolding tool to automate the project creation. It will build an entire directory structure based on current environment.

Install the cargo-generate by running the below command in a terminal:

$ cargo install cargo-generate

Install Web Assembly compile & build tool

Install wasm-pack to compile and build the web assembly.

$ cargo install wasm-pack

Or refer this link to install.

Create Planetr Functions Project

Using cargo generate we can create a new project. Please change the <project-name> to whatever you like (example: wasm-sum).

$ cargo generate --git https://github.com/planetrio/planetr-faas-waasm-template.git --name <project-name>
$ cd <project-name>

This will create a new folder with project name and will have toml file and src folder containing the rust code.

Folder Structure

Open and edit handler.rs file to implement the function logic in rust. The sample code below will take two parameter x, y and return the sum.


#![allow(unused)]
fn main() {
#[derive(Deserialize, Serialize)]
pub struct InputPayload {
    x: i32,
    y: i32,
}

#[derive(Deserialize, Serialize)]
pub struct OuputPayload {
    sum: i32,
}

pub fn handle_req(args: InputPayload, _ctx: Context) -> Result<OuputPayload, PlanetrError> {
    Ok(OuputPayload{
        sum: args.x + args.y,
    })
}
}

Build Web Assembly (WASM) file

Build the project using wasm-pack.

$ cd <project-name>
$ wasm-pack build

You should see something similar as build output.

[INFO]: 🎯  Checking for the Wasm target...
[INFO]: 🌀  Compiling to Wasm...
    Finished release [optimized] target(s) in 43.81s
[INFO]: ⬇️  Installing wasm-bindgen...
[INFO]: Optimizing wasm binaries with `wasm-opt`...
[INFO]: ✨   Done in 45.04s
[INFO]: 📦   Your wasm pkg is ready to publish at /.../wasm-sum/pkg.

Your compiled wasm library file is at: <project-name>/target/wasm32-unknown-unknown/release/<project-name>.wasm

Congratulations on your achievement! You've successfully developed the project, compiled it, and generated the wasm binary, which can now be deployed as a function to the Planetr gateway.