dotfiles/agent/src/main.rs

108 lines
3.3 KiB
Rust
Raw Normal View History

2024-01-24 23:18:30 +00:00
use async_nats as nats;
use nats::{Client, ConnectOptions};
use tracing::Level;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("to set a tracing global subscriber");
let client = ConnectOptions::new()
.name("Prymn Agent demo_agent")
.custom_inbox_prefix("_INBOX_demo_agent")
.user_and_password("demo_agent".to_owned(), "demo_agent_password".to_owned())
.connect("localhost")
.await
.map_err(|err| err)?;
tracing::info!("connected to nats server");
wait_for_commands(client).await;
Ok(())
}
async fn wait_for_commands(_client: Client) {
// let mut sub = client
// .subscribe("agents.v1.demo_agent.cmd.*")
// .await
// .unwrap();
//
// let mut command_queue = CommandQueue::default();
//
// while let Some(msg) = sub.next().await {
// let suffix = msg.subject.trim_start_matches("agents.v1.demo_agent.cmd.");
//
// match suffix {
// "end" => {
// let key = std::str::from_utf8(&msg.payload).unwrap();
// command_queue.end_command(key);
// }
// key => {
// if let Some(mut receiver) = command_queue.add_command(key) {
// tokio::spawn(async move {
// while let Ok(()) = receiver.changed().await {
// let queue = receiver.borrow();
// while let Some(cmd) = queue.lock().unwrap().pop_back() {
// handle_command(cmd);
// }
// }
// });
// }
// }
// }
// }
}
//
// fn handle_command(cmd: Command) {
// println!("{cmd:?}");
// }
//
// #[derive(Default)]
// struct CommandQueue(HashMap<String, watch::Sender<Mutex<VecDeque<Command>>>>);
//
// impl CommandQueue {
// pub fn add_command(&mut self, key: &str) -> Option<watch::Receiver<Mutex<VecDeque<Command>>>> {
// match self.0.get_mut(key) {
// Some(sender) => {
// sender.send_modify(|q| q.lock().unwrap().push_back(Command::Foo));
// None
// }
// None => {
// let (sender, receiver) = watch::channel(Mutex::new(VecDeque::new()));
// sender.send_modify(|q| q.lock().unwrap().push_back(Command::Foo));
// Some(receiver)
// }
// }
// }
//
// pub fn end_command(&mut self, key: &str) {
// self.0.remove(key);
// }
// }
//
// mod cmd {
// // use std::borrow::Cow;
//
// #[derive(Debug, Clone)]
// pub enum Command {
// Foo,
// }
//
// #[derive(Debug)]
// pub struct UnknownCommand<'a>(&'a str);
//
// impl<'a> TryFrom<&'a str> for Command {
// type Error = UnknownCommand<'a>;
//
// fn try_from(cmd: &'a str) -> Result<Self, Self::Error> {
// match cmd {
// "foo" => Ok(Command::Foo),
// _ => Err(UnknownCommand(cmd)),
// }
// }
// }
// }