Guides / Compute

Write a program in Rust

If you write programs in Rust, use the SDK, etorm-guest. You implement the handlers on a Rust type, and the SDK provides the exports and a safe handle to the host. In this guide you build a small program, register it and run it.

What the SDK gives you

A program is a type that implements Program and Default. The program! macro keeps one value of it for the life of the instance and calls it for every wake-up, so in a resident process the value is the process's memory.

HandlerCalled
start(&mut self, cx, why: StartReason)Once per life. StartReason is Created, Resumed, Restarted or Restored.
frames(&mut self, cx, frames: &[Frame])Up to 64 frames, oldest first. A Frame has interface: u32 and data: Vec<u8>.
timer(&mut self, cx, id: u32)A timer you set is due.
scheduled(&mut self, cx, name: &str, due: u64, missed: u32)A schedule of the process ticked.
stop(&mut self, cx)The process is about to be suspended, stopped or replaced: save state, no more.

All five have empty defaults, so implement only the ones you need. Each handler gets a Cx, which reaches the host and is valid for that one call:

CallWhat it does
cx.send(interface, &frame)Queues one Ethernet frame. Errors: NoSuchInterface, TooLarge, BadSourceMac, QueueFull.
cx.interfaces()Index, name, MAC, MTU, link-local address and VPC prefix of each interface.
cx.now(), cx.unix_seconds()Monotonic nanoseconds; wall-clock seconds.
cx.set_timer(id, at), cx.cancel_timer(id)Wake timer(id) when now() reaches at. At most 16 timers.
cx.state(), cx.set_state(&bytes)Durable state, up to the process's stateMaxBytes.
cx.config(key)A value of spec.config.
cx.objects()get, put, put_new (create-only) and delete on the buckets in spec.buckets.
cx.report(key, value)Shows a value in status.reported.
cx.log_info(..), log_warn, log_errorLines in status.logs.
cx.random(&mut buf)Random bytes.

The rules from Write your first program still apply. A call that traps changes nothing, and a program never blocks. Do not use std::time, std::fs or std::net. There is no operating system underneath, so they would fail. Use cx.now() for time.

1. Create the crate

Cargo.toml:

[package]
name = "reflector"
version = "0.1.0"
edition = "2021"
build = "build.rs"

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

[dependencies]
etorm-guest = { path = "../etorm/crates/etorm-guest" }

[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true

Point the path at your checkout of the SDK. Then add a build.rs that passes the linker two things every program needs. The first is a declared memory maximum. A module without one is refused, and the maximum may not exceed 256 MiB. The second is a stack that fits the memory allowance.

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    // Only the WebAssembly build has these linker arguments.
    if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() != Ok("wasm32") {
        return;
    }
    println!("cargo:rustc-link-arg-cdylib=--max-memory=2097152");
    println!("cargo:rustc-link-arg-cdylib=-zstack-size=65536");
}

Here the maximum is 2 MiB (32 pages) and the stack 64 KiB. Choose a maximum at least as large as the memory you give the process.

2. Write the program

src/lib.rs answers every frame with the same frame, destination and source swapped, counts them in memory and reports the count:

use etorm_guest::{program, Cx, Frame, Program, StartReason};

#[derive(Default)]
struct Reflector {
    seen: u64,
}

impl Program for Reflector {
    fn start(&mut self, cx: &mut Cx, why: StartReason) {
        cx.log_info(&format!("start {why:?}, {} frames so far", self.seen));
    }

    fn frames(&mut self, cx: &mut Cx, frames: &[Frame]) {
        for f in frames {
            if f.data.len() < 14 {
                continue;
            }
            // The frame's destination is this interface's MAC when it was
            // addressed to us; it becomes the source of the reply.
            let mut reply = f.data.clone();
            reply[..6].copy_from_slice(&f.data[6..12]);
            reply[6..12].copy_from_slice(&f.data[..6]);
            if cx.send(f.interface, &reply).is_ok() {
                self.seen += 1;
            }
        }
        let _ = cx.report("frames", &self.seen.to_string());
    }
}

program!(Reflector);

A frame sent to a broadcast or multicast address is not answered. Its destination is not this interface's MAC, so the reply has the wrong source, send returns BadSourceMac, and the program ignores it. To always send from the right address, take mac from cx.interfaces().

You can test the program on your own machine without WebAssembly. On other targets the SDK uses etorm_guest::mock::MockHost, an in-memory host with a fake clock. Call the handlers through Slot with synthetic frames, then look at what was sent.

3. Build it

rustup target add wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown
ls -l target/wasm32-unknown-unknown/release/reflector.wasm
# about 25 KB

A program you register may be at most 256 KiB.

4. Register and run it

kubectl apply -f - <<EOF
apiVersion: compute.etorm.com/v1alpha1
kind: Program
metadata: {name: reflector}
spec:
  module: $(base64 < target/wasm32-unknown-unknown/release/reflector.wasm | tr -d '\n')
EOF
kubectl apply -f - <<EOF
apiVersion: compute.etorm.com/v1alpha1
kind: Process
metadata: {name: reflector}
spec:
  programRef: {name: reflector}
  interfaces:
    - {name: eth0, vpcRef: {name: lan}}
  residency: Resident
  resources: {memoryPower: 5}
EOF

The module is checked when you register it. A refusal names the reason, for example a missing memory maximum or an import that does not exist. memoryPower: 5 is 2 MiB, matching the linker maximum above. The program has to fit in its allowance when it starts. If it does not, the message names the power that fits. See Run a program as a process for the allowances.

The process is resident, so the counter lives in memory across wake-ups. Read what it reports:

kubectl get process reflector -o jsonpath='{.status.phase} {.status.reported}{"\n"}'
# Ready {"frames":"4"}

Reports refresh about every 30 seconds, like the other status counters. Keys are 1 to 64 characters of A-Z a-z 0-9 _ . -, and all keys and values together are at most 4 KiB.

Choose ephemeral or resident

An ephemeral process (the default) gets a fresh instance for every wake-up, so the value starts from Default each time. Anything it must keep goes through cx.set_state and is read back in start or on the first call. A resident process keeps the instance, so the value is kept, and it can be hibernated and moved. A resident process still loses its memory when it fails or its machine restarts, though its state survives. Keep anything you cannot rebuild in state or in a bucket.

Clean up

kubectl delete process reflector
kubectl delete program reflector

Next

Run a TCP service.