Skip to main content

Crate myrmic_sdk

Crate myrmic_sdk 

Source
Expand description

The SDK for writing Myrmic cells: WebAssembly modules that deploy and self-organize across a swarm of devices.

Myrmic runs application logic as cells — portable, isolated Wasm units the runtime deploys, supervises, and connects across embedded, mobile, and server targets. This crate is what a cell links against: it turns plain Rust functions into the exports the runtime invokes, and wraps everything the host offers in safe Rust APIs.

§A minimal cell

A cell is a no_std library crate. There is no main and no allocator or panic-handler boilerplate — the default cell-init feature emits those via cell_prelude!. Handlers are free functions marked with the attributes below:

ⓘ
//! A minimal counter cell: `increment` bumps a stored count and publishes
//! the new value as an event.

#![no_std]

use myrmic_sdk::db::tree::Kv;
use myrmic_sdk::{Metadata, Result, publish};

/// Published when the counter value changes.
#[derive(serde::Serialize, serde::Deserialize, myrmic_sdk::Message)]
struct CountChanged {
    count: i32,
}

const KV: Kv<i32> = Kv::new("counter");

/// Runs once per incarnation, before any other handler.
#[myrmic_sdk::init]
fn init(_md: Metadata) -> Result<()> {
    if KV.get("count")?.is_none() {
        KV.put("count", &0)?;
    }
    Ok(())
}

/// Invocable by other cells (or the gateway) as the `increment` command.
#[myrmic_sdk::cmd]
fn increment(_md: Metadata, by: i32) -> Result<()> {
    let n = KV.get("count")?.unwrap_or(0) + by;
    KV.put("count", &n)?;
    publish("count_changed", &CountChanged { count: n })
}

The tests/fixtures/cell-* crates are complete working cells exercising each feature; they are the best starting templates.

§Handlers

AttributeExport invoked whenPayload
#[init]Once per incarnation: first deploy, and again on every respawn/restartoptional spawn argument
#[cmd]Another cell sends the command (or a timer tick / gateway call names it)any Decoder; replies go through a Callback parameter
#[evt]A subscribed event is publishedthe event’s payload
#[monitor]A child cell dies (crash, stop, termination, node loss)monitor::CellLost

Every handler takes a leading Metadata (the cell’s own Sri and the sender’s) and returns Result. Payload types derive Message to pick their wire codec (Json by default, or any Codec via #[codec(...)]).

§What the host offers

  • Messaging — send commands to a cell, publish events to subscribers, reply via Callback.
  • Storage (the datalayer, module db) — typed handles Kv, Table, State, plus blob, time-series, and semantic stores. Private db state survives restarts and respawns.
  • Spawning & supervision — declare! a child class, spawn it with ClassHandle, get monitor callbacks when it dies, terminate_cell / stop_self to tear down.
  • Timers — delay, interval, interval_at schedule future invocations of a named command export.
  • Time — now (swarm-synchronised wall clock), uptime (monotonic), wait.
  • Logging — trace! … error! macros and their _str variants.
  • Signal layer — taps onto host-side signals, gpio pins, ble centrals/peripherals.
  • Bridges — import! generates typed clients for HTTP APIs and MQTT brokers from YAML specs.
  • Gateway — gateway mounts blob scopes as static assets and routes HTTP to commands.

§Execution model

Cells are single-threaded: the runtime invokes one export at a time, so handlers never race each other. A panic is logged with its location and traps the module; the parent (if any) hears about it through its monitor handler. Durable state belongs in the datalayer — volatile resources like timers die with the incarnation and are re-established in #[init].

§Feature flags

FeatureDefaultEnables
allocyesheap, codecs, everything payload-shaped
cellsyesmessaging, spawning, timers, handler attributes
dbyesthe datalayer APIs
cell-inityesthe allocator/panic-handler prelude a deployable cell needs
eionoembedded-io codecs for the shared wire types
types-webnomyrmic-common’s web wire types, for a build that takes that crate without its defaults

The default set is the only configuration that builds today: without alloc the mandatory serde_json dependency has no allocator, and myrmic-common is taken with its own defaults, so the shared cells, db and types-web items - types::web among them - are present no matter what is selected above.

§Further reading

The Myrmic book carries the quickstart, tutorials (observability, BLE), and architecture chapters; this crate’s docs are the API reference.

Re-exports§

pub use myrmic_common::signal_layer;
pub use serde;

Modules§

ble
BLE Host Functions
db
Datalayer access: the raw key-value, table, time-series, semantic, and blob APIs, plus the typed state, store, table, and tree wrappers over them.
gateway
Declaring how the socket gateway should serve this cell.
gpio
GPIO Host functions
monitor
Everything a supervising parent needs: the monitor handler’s payload types and stop_self for escalation.
outlet
Safe wrappers for the “outlet” host module — Signal Layer outlet discovery and writing.
tap
Safe wrappers for the “tap” host module — Signal Layer tap discovery and reading.
types
Wire and utility types shared across the swarm.
vec
A contiguous growable array type with heap-allocated contents, written Vec<T>.

Macros§

cell_prelude
Wires up the global allocator, panic handler, and OOM handler to minimise the amount of boilerplate required in cell crates.
debug
Logs a format!-style message at debug level via the host.
declare
Declares a reference to a child cell class by name, returning a ClassHandle to spawn it with.
define_alloc_heap
Emits the cell’s global allocator: an embedded-alloc heap of $heap_size bytes, the init_allocator export the host calls before running the module, and a no-op critical-section backend (Wasm cells are single-threaded).
define_panic_handlers
Emits the cell’s #[panic_handler]: it formats the panic message and location into a pre-allocated buffer (no heap use), logs them at error level, then traps to stop the module.
error
Logs a format!-style message at error level via the host.
format
Creates a String using interpolation of runtime expressions.
import
The handler-export attributes, usable as #[myrmic_sdk::cmd] etc. Generates a typed client for an external system from a YAML bridge spec.
info
Logs a format!-style message at info level via the host.
mac_addr_pub
Macro allowing the easy declaration of a BLE MAC Public Address
mac_addr_rand
Macro allowing the easy declaration of a BLE MAC Random Address
trace
Logs a format!-style message at trace level via the host.
uuid128
Macro allowing the easy declaration of a 128-bit UUID
vec
Creates a Vec containing the arguments.
warn
Logs a format!-style message at warn level via the host.

Structs§

Address
BLE MAC Address
Advertisement
Data parsed from a device’s BLE advertisement.
Callback
The command a caller wants a result returned to.
Characteristic
A GATT Characteristic
ClassHandle
A reference to a child cell class, produced by crate::declare!.
Command
Represents a validated command identifier
DiscoveredDevice
A device discovered during scanning, but potentially not yet connected to
DiscoveryFilter
Filter passed to Ble::discover_with_filter.
Event
Represents a validated event identifier
EventPublishRequest
Represents the request to publish an event
InMemory
Transient, cell-local storage for state that must not be persisted, such as host resource handles (sockets, subscriptions, scan sessions, …) held across handler invocations.
Json
JSON codec.
ManufacturerData
Manufacturer advertising data
Metadata
Metadata describing the context of a handler invocation.
Outlet
A resolved outlet handle — wraps the integer handle returned by the host.
Postcard
Postcard codec.
RawBuf
A fixed-capacity output buffer described by a raw pointer and capacity, written through core::fmt::Write; text past the capacity is truncated.
Service
A GATT Service: its discovered characteristics, keyed by characteristic UUID.
ServiceData
Service advertising data (AD type 0x16 / 0x21: Service Data)
SpawnBuilder
A child spawn being filled out, produced by ClassHandle::new and handed off by spawn. Clone one to reuse it as a template.
SpawnRequest
Used by cells to create and deploy other cells via the spawn_cell host function.
Sri
The UUID identity of a cell instance.
String
A UTF-8–encoded, growable string.
Tap
A resolved tap handle — wraps the integer handle returned by the host.
TimerHandle
Handle to an active interval or delay. Can be cancelled by calling .cancel().
Vec
A contiguous growable array type, written as Vec<T>, short for ‘vector’.
Void
The absence of a payload. This is the default Decoder the #[cmd] / #[evt] macros use for a handler declared with only a Metadata parameter: decoding succeeds only when the argument buffer is empty, so sending a payload to such a handler is rejected rather than silently ignored.

Enums§

ApiError
A structured error returned by the host across the FFI boundary.
ClassRef
A request to spawn a new cell instance at runtime.
CommandError
Why sending a command to a cell failed.
JsonValue
Represents any valid JSON value.
LogLevel
Severity of a log line, mirroring the host’s log levels.
NotifyError
Characteristic Notify Errors
ReadError
Characteristic Read Errors
ScanMode
Whether a scan requests scan responses in addition to primary advertisements.
SpawnError
Errors that can occur when spawning a cell.
TapKind
Kind of a tap slot.
TerminateError
Errors that can occur when terminating a cell.
Uuid
A BLE UUID
WriteError
Characteristic Write Errors

Constants§

EACCES
Permission denied (POSIX EACCES).
EAGAIN
Resource temporarily unavailable, try again (POSIX EAGAIN).
EINVAL
Invalid argument (POSIX EINVAL).
ENOMEM
Out of memory (POSIX ENOMEM): the guest-provided buffer is too small to hold the response. Query the required length and retry with a larger buffer.
EPERM
Operation not permitted (POSIX EPERM).
ESTALE
Stale handle (POSIX ESTALE): the handle is not — or is no longer — valid for this operation. Raised when the backing service is gone, the handle predates a reconnect, or it was never issued. Re-resolve to obtain a fresh handle; retrying with the same one cannot succeed.
ETIMEDOUT
Operation timed out (POSIX ETIMEDOUT).
GENERIC_ERROR
Generic, unspecified failure returned by a host function when no more specific error code applies.
SUCCESS
Return value indicating a host function completed successfully.

Traits§

CellEvent
Marker trait for event payload types.
Codec
A wire serialization format.
Decoder
Turns a raw payload buffer into Self.
Encoder
Turns Self into a raw payload buffer.
Handler
A handler that can be targeted by name.
WireType
A type that can live in a tap or outlet slot.

Functions§

debug_str
Logs a plain &str at debug level, with no formatting or allocation.
delay
Creates a one-shot delayed action that calls the named export after the delay.
error_str
Logs a plain &str at error level, with no formatting or allocation.
get_arguments
Copies the payload of the command/event that triggered this invocation into buffer, returning the number of bytes written.
info_str
Logs a plain &str at info level, with no formatting or allocation.
interval
Creates a periodic interval that calls the named export on each tick.
interval_at
Creates a periodic interval with an initial delay before the first tick.
list_entry
Returns the name and kind of the tap at index, writing the name into name_buf.
list_len
Returns the number of taps registered in the host’s tap registry.
log
Logs msg on the host’s logger at log_level.
log_buffer
Logs the contents of a RawBuf at log_level — for contexts that must not allocate, such as the panic and OOM handlers.
now
Returns the current wall-clock time as a Duration since UNIX_EPOCH, from the host’s swarm-synchronised hybrid logical clock.
publish
Publish value as an event under an explicit name.
publish_event
Hands a pre-built EventPublishRequest to the host for delivery to every subscribed cell. Prefer publish, which builds the request and encodes the payload for you.
report_error
Stores the provided string as an error message in the error queue of the calling module
runtime_id
Returns the id of the runtime hosting this cell (its Zenoh id) as a string.
runtime_tags
Returns the effective tag set of the runtime hosting this cell.
send
Send value as a fire-and-forget command to sri under an explicit name.
spawn_cell
Spawns a cell of the given class under request.local_name, returning the child’s SRI as assigned by the host (child_sri(own_sri, local_name)). The caller records this to address the child later.
stop_self
Deliberately stops this cell and everything it spawned (minus detached children). The parent — if any — is told stopped(code), letting a supervising parent distinguish clean completion (None) from giving up. Returns normally; the host reaps the cell moments later, so treat everything after this call as best-effort cleanup only.
terminate_cell
Requests the host terminate the cell identified by sri.
trace_str
Logs a plain &str at trace level, with no formatting or allocation.
uptime
Returns the host’s monotonic uptime: elapsed time since the host process started (edge) or since boot (embedded).
wait
Requests the host pause the module for dur.
warn_str
Logs a plain &str at warn level, with no formatting or allocation.

Type Aliases§

ApiResult
Result of a raw host-function call, erring with a structured ApiError.
Bytes
The raw payload buffer type the Decoder/Encoder traits work in terms of.
Result
The SDK’s general-purpose result; handlers and codecs err with a static message.

Attribute Macros§

cmd
The handler-export attributes, usable as #[myrmic_sdk::cmd] etc. Turns a free function into a Wasm command export.
evt
The handler-export attributes, usable as #[myrmic_sdk::cmd] etc. Turns a free function into a Wasm event-handler export.
init
The handler-export attributes, usable as #[myrmic_sdk::cmd] etc. Turns a free function into the init_cell Wasm export, run once per incarnation: on first deploy, and again each time the cell is respawned or restarted under the same SRI. Private db state survives incarnations, so after a restart init runs over the previous life’s data - seed it idempotently rather than assuming a blank slate. Volatile host resources (timers) die with the incarnation and are re-established here.
monitor
The handler-export attributes, usable as #[myrmic_sdk::cmd] etc. Turns a free function into the cell’s on_cell_lost export - the reserved handler the runtime invokes when one of this cell’s children dies (crash, deliberate stop, termination, or node loss).

Derive Macros§

Message
Derives for the Codec-backed Decoder/Encoder impls, usable as #[derive(myrmic_sdk::Message)]. Binds a wire codec to a message type: generates Decoder + Encoder (myrmic_sdk) that delegate to the myrmic_sdk::Codec named in an optional #[codec(...)] attribute, defaulting to myrmic_sdk::Json when omitted. The type should also derive serde::{Serialize, Deserialize}.