orch-cli 0.118.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Run a channel on the cluster leader only. Telegram lets one client poll a bot at a time, so
//! two nodes polling one bot split its messages, and each node would send every notification

use super::{Channel, IncomingMessage, OutgoingMessage};
use async_trait::async_trait;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::sync::Mutex as AsyncMutex;
use tokio::sync::mpsc;
use tokio::sync::mpsc::Receiver;
use tokio::task::JoinHandle;
use tokio::time;

/// How often a cluster node checks whether it leads
pub const LEADER_CHECK_INTERVAL: Duration = Duration::from_secs(1);

struct Gate {
    inner: Box<dyn Channel>,
    tx: mpsc::Sender<IncomingMessage>,
    rx: Mutex<Option<Receiver<IncomingMessage>>>,
    // Held while the channel starts or stops, so two checks cannot both start it
    forward: AsyncMutex<Option<JoinHandle<()>>>,
    active: AtomicBool,
}

/// A channel that listens and sends only while this node leads the cluster. The engine holds one
/// receiver for the life of the process, and the messages of each run reach it
#[derive(Clone)]
pub struct LeaderOnly(Arc<Gate>);

impl Debug for LeaderOnly {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("LeaderOnly")
            .field("channel", &self.0.inner.name())
            .field("active", &self.is_active())
            .finish()
    }
}

impl LeaderOnly {
    pub fn new(inner: Box<dyn Channel>) -> Self {
        let (tx, rx) = mpsc::channel(64);
        Self(Arc::new(Gate {
            inner,
            tx,
            rx: Mutex::new(Some(rx)),
            forward: AsyncMutex::new(None),
            active: AtomicBool::new(false),
        }))
    }

    /// Start the channel when `leads` and it is stopped, stop it when not and it runs
    pub async fn lead(&self, leads: bool) {
        let mut forward = self.0.forward.lock().await;
        if leads == forward.is_some() {
            return;
        }

        let name = self.0.inner.name();
        if !leads {
            self.0.active.store(false, Ordering::SeqCst);
            self.0.inner.stop().await;
            if let Some(task) = forward.take() {
                task.abort();
            }

            tracing::info!(channel = name, "channel stopped, this node no longer leads");
            return;
        }

        match self.0.inner.start().await {
            Ok(mut rx) => {
                let tx = self.0.tx.clone();
                *forward = Some(tokio::spawn(async move {
                    while let Some(msg) = rx.recv().await {
                        if tx.send(msg).await.is_err() {
                            return;
                        }
                    }
                }));
                self.0.active.store(true, Ordering::SeqCst);
                tracing::info!(channel = name, "channel started, this node leads");
            }
            Err(e) => {
                tracing::warn!(channel = name, ?e, "failed to start channel on the leader");
            }
        }
    }

    pub fn is_active(&self) -> bool {
        self.0.active.load(Ordering::SeqCst)
    }
}

#[async_trait]
impl Channel for LeaderOnly {
    fn name(&self) -> &str {
        self.0.inner.name()
    }

    /// The receiver for every run of the channel. `lead` starts the channel itself
    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
        self.0
            .rx
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
            .ok_or_else(|| anyhow::anyhow!("channel {} already started", self.name()))
    }

    /// Drops the message on a node that does not lead, since the leader sends its own
    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
        if !self.is_active() {
            tracing::debug!(
                channel = self.name(),
                thread = %msg.thread_id,
                "not the leader, message not sent"
            );
            return Ok(());
        }

        self.0.inner.send(msg).await
    }

    async fn ack_interaction(&self, callback_query_id: &str) -> anyhow::Result<()> {
        if !self.is_active() {
            return Ok(());
        }

        self.0.inner.ack_interaction(callback_query_id).await
    }

    async fn health_check(&self) -> anyhow::Result<()> {
        self.0.inner.health_check().await
    }

    async fn stop(&self) {
        self.lead(false).await;
    }
}

/// Wrap `channel` in `LeaderOnly` on a cluster node and add it to `gated`. A single machine always
/// leads, so its channel comes back as it is
pub fn gate(
    channel: Box<dyn Channel>,
    clustered: bool,
    gated: &mut Vec<LeaderOnly>,
) -> Box<dyn Channel> {
    if !clustered {
        return channel;
    }

    let gate = LeaderOnly::new(channel);
    gated.push(gate.clone());
    Box::new(gate)
}

/// Start and stop `channels` as `leads` changes, checking every `interval`. Runs until aborted
pub async fn follow_leader(
    channels: Vec<LeaderOnly>,
    leads: impl Fn() -> bool + Send,
    interval: Duration,
) {
    let mut ticker = time::interval(interval);
    ticker.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
    loop {
        ticker.tick().await;
        let leads = leads();
        for channel in &channels {
            channel.lead(leads).await;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;

    #[derive(Default)]
    struct Counts {
        starts: AtomicUsize,
        stops: AtomicUsize,
        sends: AtomicUsize,
        inbox: Mutex<Option<mpsc::Sender<IncomingMessage>>>,
    }

    /// A channel that counts its calls and lets the test push incoming messages
    struct FakeChannel(Arc<Counts>);

    #[async_trait]
    impl Channel for FakeChannel {
        fn name(&self) -> &'static str {
            "fake"
        }

        async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
            self.0.starts.fetch_add(1, Ordering::SeqCst);
            let (tx, rx) = mpsc::channel(8);
            *self.0.inbox.lock().unwrap() = Some(tx);
            Ok(rx)
        }

        async fn send(&self, _msg: &OutgoingMessage) -> anyhow::Result<()> {
            self.0.sends.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

        async fn health_check(&self) -> anyhow::Result<()> {
            Ok(())
        }

        async fn stop(&self) {
            self.0.stops.fetch_add(1, Ordering::SeqCst);
            self.0.inbox.lock().unwrap().take();
        }
    }

    fn fake() -> (Arc<Counts>, Box<dyn Channel>) {
        let counts = Arc::new(Counts::default());
        (Arc::clone(&counts), Box::new(FakeChannel(counts)))
    }

    fn outgoing() -> OutgoingMessage {
        OutgoingMessage {
            thread_id: "1".to_string(),
            body: "done".to_string(),
            reply_to: None,
            metadata: serde_json::json!({}),
            topic_id: None,
        }
    }

    fn incoming(id: &str) -> IncomingMessage {
        IncomingMessage {
            channel: "fake".to_string(),
            id: id.to_string(),
            thread_id: "1".to_string(),
            author: "owner".to_string(),
            body: "status".to_string(),
            timestamp: chrono::Utc::now(),
            metadata: serde_json::json!({}),
            topic_id: None,
        }
    }

    async fn push(counts: &Counts, id: &str) {
        let tx = counts
            .inbox
            .lock()
            .unwrap()
            .clone()
            .expect("channel started");
        tx.send(incoming(id)).await.unwrap();
    }

    #[tokio::test]
    async fn a_follower_starts_no_poller_and_sends_nothing() {
        let (counts, inner) = fake();
        let mut gated = Vec::new();
        let channel = gate(inner, true, &mut gated);
        let _rx = channel.start().await.unwrap();
        gated[0].lead(false).await;

        channel.send(&outgoing()).await.unwrap();

        assert_eq!(counts.starts.load(Ordering::SeqCst), 0);
        assert_eq!(counts.sends.load(Ordering::SeqCst), 0);
        assert!(!gated[0].is_active());
    }

    #[tokio::test]
    async fn a_node_that_becomes_leader_starts_the_channel_once() {
        let (counts, inner) = fake();
        let gate = LeaderOnly::new(inner);
        let mut rx = gate.start().await.unwrap();

        gate.lead(true).await;
        gate.lead(true).await;
        push(&counts, "m1").await;
        gate.send(&outgoing()).await.unwrap();

        assert_eq!(counts.starts.load(Ordering::SeqCst), 1);
        assert_eq!(counts.sends.load(Ordering::SeqCst), 1);
        assert_eq!(rx.recv().await.unwrap().id, "m1");
    }

    #[tokio::test]
    async fn a_node_that_loses_the_lead_stops_the_channel() {
        let (counts, inner) = fake();
        let gate = LeaderOnly::new(inner);
        let mut rx = gate.start().await.unwrap();
        gate.lead(true).await;

        gate.lead(false).await;
        gate.lead(false).await;
        gate.send(&outgoing()).await.unwrap();

        assert_eq!(counts.stops.load(Ordering::SeqCst), 1);
        assert_eq!(counts.sends.load(Ordering::SeqCst), 0);
        assert!(counts.inbox.lock().unwrap().is_none());

        // Leading again starts a new run, and its messages reach the same receiver
        gate.lead(true).await;
        push(&counts, "m2").await;
        assert_eq!(counts.starts.load(Ordering::SeqCst), 2);
        assert_eq!(rx.recv().await.unwrap().id, "m2");
    }

    #[tokio::test]
    async fn a_single_machine_starts_the_channel_as_before() {
        let (counts, inner) = fake();
        let mut gated = Vec::new();
        let channel = gate(inner, false, &mut gated);

        let _rx = channel.start().await.unwrap();
        channel.send(&outgoing()).await.unwrap();

        assert!(gated.is_empty());
        assert_eq!(counts.starts.load(Ordering::SeqCst), 1);
        assert_eq!(counts.sends.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn follow_leader_starts_and_stops_with_the_lead() {
        let (counts, inner) = fake();
        let gate = LeaderOnly::new(inner);
        let leads = Arc::new(AtomicBool::new(false));
        let follow = tokio::spawn(follow_leader(
            vec![gate.clone()],
            {
                let leads = Arc::clone(&leads);
                move || leads.load(Ordering::SeqCst)
            },
            Duration::from_millis(5),
        ));

        time::sleep(Duration::from_millis(50)).await;
        assert_eq!(counts.starts.load(Ordering::SeqCst), 0);

        leads.store(true, Ordering::SeqCst);
        time::sleep(Duration::from_millis(50)).await;
        assert!(gate.is_active());
        assert_eq!(counts.starts.load(Ordering::SeqCst), 1);

        leads.store(false, Ordering::SeqCst);
        time::sleep(Duration::from_millis(50)).await;
        assert!(!gate.is_active());
        assert_eq!(counts.stops.load(Ordering::SeqCst), 1);

        follow.abort();
    }
}