Call WASM

A lambda may bundle one or more associated WASM modules that will be deployed to the agent alongside the lambda. WASM modules may include functions like machine learning or tensor models that are easier to express in a language such as Rust.

Rust-based add_one() function

This Rust based WASM module exports an add_one() function.

add_one.yaml
add_one.lua
Cargo.toml
src/
  lib.rs

lib.rs:

#![allow(unused)]
fn main() {
#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
    x + 1
}
}

Cargo.toml:

[package]
name = "add-one"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib"]

Build the WASM module:

$ rustup target add wasm32-unknown-unknown
$ cargo build --target wasm32-unknown-unknown --release

Register the lambda

$ onprem generate xid
cmv805656a11vubtf6pg
# add_one.yaml
id: cmv805656a11vubtf6pg
kind: Lambda
name: add_one
description: >
  A lambda that calls a WASM function to add one.
runAt:
  deviceId: ci2fabp32ckvhk1g9qe0
fileInfoIds:
  - "@target/wasm32-unknown-unknown/release/add_one.wasm"
scriptContentType: text/x-lua
script: "@add_one.lua"
-- add_one.lua
local wasmer = require('wasmer')

local store = wasmer.Store:default()
local M={}

function M.handler(event, context)
  local path = context.path_for_filename('add_one.wasm') 
  local f = io.open(path, 'rb')
  local binary = f:read('*a')
  local module = wasmer.Module:from_binary(store, binary)
  local instance = wasmer.Instance:new(store, module)
  local add_one = instance.exports:get_function('add_one')
  return add_one:call(store, event)
end

return M
$ onprem apply add_one.yaml

If the agent is connected to the control plane, it will have downloaded its new config bundle containing the new lambda and associated files within a few seconds.

View Lambda in the Console

Notice the lambda now appears in the cloud console, and that it contains the associated WASM file add_one.wasm.

Console

Run the Lambda

$ onprem run lambda cmv805656a11vubtf6pg --event '123'
124