WeaveDocs
Weave Swarm

Events and Priority

Event stream and priority handling in Weave Swarm — backpressure-aware event delivery with per-peer priority queues.

Purpose

Topic swarm for peer IDs, topic IDs, join/update options, events, priorities, connection state, and metrics.

This page follows the real source shape for Weave Swarm and explains the workflow a developer is likely to use first.

Developer workflow

Start from the smallest constructor or builder, perform one meaningful operation, inspect the returned state, then add the relevant policy, storage, or network integration. The examples below should be expanded whenever the crate API changes.

Warning

When the swarm's priority queue is saturated, older lower-priority events are dropped to keep up. Subscribers must be able to recover state from authoritative sources (Strands, DHT) rather than rely on the event stream as a durable log.

Primary types to know

  • BackoffConfig — network/weave-swarm/src/config.rs
  • Connection — network/weave-swarm/src/connection.rs
  • ConnectionStats — network/weave-swarm/src/connection.rs
  • JoinOptions — network/weave-swarm/src/topic.rs
  • LimitsConfig — network/weave-swarm/src/config.rs
  • NatConfig — network/weave-swarm/src/config.rs
  • PeerId — network/weave-swarm/src/connection.rs
  • Priority — network/weave-swarm/src/priority.rs
  • Swarm — network/weave-swarm/src/swarm.rs
  • SwarmConfig — network/weave-swarm/src/config.rs
  • SwarmMetrics — network/weave-swarm/src/metrics.rs
  • TelemetryConfig — network/weave-swarm/src/config.rs

Example shape

use tokio::time::{timeout, Duration};
use weave_swarm::{DisconnectReason, Priority, Swarm, SwarmConfig, SwarmEvent};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let swarm = Swarm::new(SwarmConfig::default()).await?;

    // events() returns a broadcast::Receiver over swarm-wide notifications.
    let mut rx = swarm.events();

    // Priority orders outbound frames; the swarm prefers higher-priority traffic
    // when bandwidth contends. Levels include Control, High, Normal, Low.
    let _control = Priority::Control;
    let _high = Priority::High;

    // Drive a quick join/leave to generate at least one event, then sample one.
    if let Ok(Ok(event)) = timeout(Duration::from_millis(100), rx.recv()).await {
        match event {
            SwarmEvent::PeerConnected { peer_id, .. } => println!("connected {peer_id:?}"),
            SwarmEvent::PeerDisconnected { peer_id, reason } => {
                println!("disconnected {peer_id:?}: {reason:?}");
                let _ = matches!(reason, DisconnectReason::ProtocolError(_));
            }
            other => println!("event: {other:?}"),
        }
    }
    Ok(())
}