standard-plugin-sdk 0.1.2

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
//! A daemon plugin: every thirty seconds it publishes a heartbeat as a live
//! message, and it answers its own `heartbeat.ping` events with a pong.
//! Everything stays in the plugin's own namespace, so it needs no grant.
//!
//! Manifest:
//!
//! ```json
//! {
//!   "apiVersion": 2, "kind": "daemon", "id": "heartbeat", "version": "0.1.0",
//!   "module": "heartbeat_daemon.wasm",
//!   "grants": {}
//! }
//! ```
#![no_std]

use core::cell::Cell;

use standard_plugin::daemon::{Context, DaemonPlugin};
use standard_plugin::prelude::{Event, Target};

#[standard_plugin::daemon]
struct Heartbeat {
    beats: Cell<u64>,
}

impl DaemonPlugin for Heartbeat {
    fn activate(_cx: &Context) -> Self {
        Self {
            beats: Cell::new(0),
        }
    }

    async fn run(&self, cx: Context) {
        let _ = cx.events().on("heartbeat.ping");
        // Answer pings beside the heartbeat loop.
        let events = cx.clone();
        cx.spawn(async move {
            loop {
                if let Event::Plugin { name, .. } = events.next_event().await
                    && name == "heartbeat.ping"
                {
                    let _ = events.events().emit("heartbeat.pong", &(), Target::All);
                }
            }
        });
        loop {
            self.beats.set(self.beats.get() + 1);
            let _ = cx.live().publish("heartbeat.beat", &self.beats.get());
            cx.sleep(30_000).await;
        }
    }
}