Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/swarm-queue-client/src/agent_status.rs

53 lines
1.9 KiB
Rust

//! The connection side of the per-agent status KV bucket: opening it for
//! writing. The bucket's name, keys and stored type are
//! `swarm_wire::agent_status`.
/// Open the agent-status bucket, creating it if nothing has yet.
///
/// `history: 1`, same rationale as [`crate::status::open_or_create`]: a
/// consumer wants the last thing each agent said, not a log of everything
/// it has ever said.
#[cfg(feature = "kv")]
pub async fn open_or_create(
client: &async_nats::Client,
) -> Result<async_nats::jetstream::kv::Store, crate::Error> {
let js = async_nats::jetstream::new(client.clone());
crate::kv::open_or_create(
&js,
swarm_wire::agent_status::BUCKET,
"agent-status",
"Last status snapshot offered by each agent".to_owned(),
)
.await
}
/// The agents of the swarm: the agent names in the bucket's keys
/// (`<hive>.<agent>`), read from the stream's subject list. This is the
/// roster the notification router sends to.
///
/// # Errors
///
/// The bucket's stream cannot be opened or its subjects listed.
#[cfg(feature = "kv")]
pub async fn roster(
client: &async_nats::Client,
) -> Result<std::collections::BTreeSet<String>, Box<dyn std::error::Error + Send + Sync>> {
use futures_util::TryStreamExt as _;
let bucket = swarm_wire::agent_status::BUCKET;
let js = async_nats::jetstream::new(client.clone());
let stream = js.get_stream(format!("KV_{bucket}")).await?;
let subjects: Vec<(String, usize)> = stream
.info_with_subjects(format!("$KV.{bucket}.>"))
.await?
.try_collect()
.await?;
let prefix = format!("$KV.{bucket}.");
Ok(subjects
.into_iter()
.filter_map(|(subject, _)| {
let key = subject.strip_prefix(&prefix)?;
swarm_wire::agent_status::split_key(key).map(|(_, agent)| agent.to_owned())
})
.collect())
}