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
| Attribute | Export invoked when | Payload |
|---|---|---|
#[init] | Once per incarnation: first deploy, and again on every respawn/restart | optional 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 published | the 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 —
sendcommands to a cell,publishevents to subscribers, reply viaCallback. - Storage (the datalayer, module
db) — typed handlesKv,Table,State, plus blob, time-series, and semantic stores. Private db state survives restarts and respawns. - Spawning & supervision —
declare!a child class, spawn it withClassHandle, getmonitorcallbacks when it dies,terminate_cell/stop_selfto tear down. - Timers —
delay,interval,interval_atschedule future invocations of a named command export. - Time —
now(swarm-synchronised wall clock),uptime(monotonic),wait. - Logging —
trace!…error!macros and their_strvariants. - Signal layer —
taps onto host-side signals,gpiopins,blecentrals/peripherals. - Bridges —
import!generates typed clients for HTTP APIs and MQTT brokers from YAML specs. - Gateway —
gatewaymounts 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
| Feature | Default | Enables |
|---|---|---|
alloc | yes | heap, codecs, everything payload-shaped |
cells | yes | messaging, spawning, timers, handler attributes |
db | yes | the datalayer APIs |
cell-init | yes | the allocator/panic-handler prelude a deployable cell needs |
eio | no | embedded-io codecs for the shared wire types |
types-web | no | myrmic-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, andtreewrappers over them. - gateway
- Declaring how the socket gateway should serve this cell.
- gpio
- GPIO Host functions
- monitor
- Everything a supervising parent needs: the
monitorhandler’s payload types andstop_selffor 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
ClassHandleto spawn it with. - define_
alloc_ heap - Emits the cell’s global allocator: an
embedded-allocheap of$heap_sizebytes, theinit_allocatorexport the host calls before running the module, and a no-opcritical-sectionbackend (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
Stringusing 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
Veccontaining 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
- Class
Handle - A reference to a child cell class, produced by
crate::declare!. - Command
- Represents a validated command identifier
- Discovered
Device - A device discovered during scanning, but potentially not yet connected to
- Discovery
Filter - Filter passed to
Ble::discover_with_filter. - Event
- Represents a validated event identifier
- Event
Publish Request - 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.
- Manufacturer
Data - 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.
- Service
Data - Service advertising data (AD type 0x16 / 0x21: Service Data)
- Spawn
Builder - A child spawn being filled out, produced by
ClassHandle::newand handed off byspawn. Clone one to reuse it as a template. - Spawn
Request - Used by cells to create and deploy other cells via the
spawn_cellhost 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.
- Timer
Handle - 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
Decoderthe#[cmd]/#[evt]macros use for a handler declared with only aMetadataparameter: 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.
- Class
Ref - A request to spawn a new cell instance at runtime.
- Command
Error - Why sending a command to a cell failed.
- Json
Value - Represents any valid JSON value.
- LogLevel
- Severity of a log line, mirroring the host’s log levels.
- Notify
Error - Characteristic Notify Errors
- Read
Error - Characteristic Read Errors
- Scan
Mode - Whether a scan requests scan responses in addition to primary advertisements.
- Spawn
Error - Errors that can occur when spawning a cell.
- TapKind
- Kind of a tap slot.
- Terminate
Error - Errors that can occur when terminating a cell.
- Uuid
- A BLE UUID
- Write
Error - 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§
- Cell
Event - Marker trait for event payload types.
- Codec
- A wire serialization format.
- Decoder
- Turns a raw payload buffer into
Self. - Encoder
- Turns
Selfinto a raw payload buffer. - Handler
- A handler that can be targeted by name.
- Wire
Type - A type that can live in a tap or outlet slot.
Functions§
- debug_
str - Logs a plain
&strat 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
&strat 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
&strat 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 intoname_buf. - list_
len - Returns the number of taps registered in the host’s tap registry.
- log
- Logs
msgon the host’s logger atlog_level. - log_
buffer - Logs the contents of a
RawBufatlog_level— for contexts that must not allocate, such as the panic and OOM handlers. - now
- Returns the current wall-clock time as a
DurationsinceUNIX_EPOCH, from the host’s swarm-synchronised hybrid logical clock. - publish
- Publish
valueas an event under an explicitname. - publish_
event - Hands a pre-built
EventPublishRequestto the host for delivery to every subscribed cell. Preferpublish, 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
valueas a fire-and-forget command tosriunder an explicitname. - 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
&strat 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
&strat 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/Encodertraits 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 theinit_cellWasm 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’son_cell_lostexport - 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-backedDecoder/Encoderimpls, usable as#[derive(myrmic_sdk::Message)]. Binds a wire codec to a message type: generatesDecoder+Encoder(myrmic_sdk) that delegate to themyrmic_sdk::Codecnamed in an optional#[codec(...)]attribute, defaulting tomyrmic_sdk::Jsonwhen omitted. The type should also deriveserde::{Serialize, Deserialize}.