orch-cli 0.117.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! When the full sync of every project runs. With the GitHub App and the relay set up, a connected
//! relay delivers events, so the full sync only reconciles what events missed

use crate::engine::EngineConfig;
use crate::engine::service::relay::{Event, Signal};
use std::time::Instant;

/// What the engine does with a relay signal
#[derive(Debug)]
pub(crate) enum Reaction {
    None,
    /// Act on the one item the event names
    Item(Event),
    /// No App: wake the tick and the full sync, as for a webhook
    Wake,
}

#[derive(Debug)]
pub(crate) struct SyncSchedule {
    /// The App and the relay are both set up, so events name items
    items: bool,
    connected: bool,
    force: bool,
    last: Instant,
}

impl SyncSchedule {
    pub(crate) fn new(items: bool, now: Instant) -> Self {
        Self {
            items,
            connected: false,
            force: false,
            last: now,
        }
    }

    /// True while a connected relay delivers events, so the full sync only reconciles
    pub(crate) fn reconciling(&self) -> bool {
        self.items && self.connected
    }

    pub(crate) fn due(&self, config: &EngineConfig, now: Instant) -> bool {
        let every = if self.reconciling() {
            config.reconcile_interval
        } else {
            config.sync_interval
        };
        self.force || now.saturating_duration_since(self.last) >= every
    }

    /// The full sync was started at `now`
    pub(crate) fn ran(&mut self, now: Instant) {
        self.force = false;
        self.last = now;
    }

    /// Run one full sync on the next tick
    pub(crate) fn force(&mut self) {
        self.force = true;
    }

    pub(crate) fn on_signal(&mut self, signal: Signal) -> Reaction {
        if !self.items {
            // Without the App every event and gap wakes the full sync, as before events named items
            return match signal {
                Signal::Gap | Signal::Event(_) => Reaction::Wake,
                Signal::Connected | Signal::Disconnected => Reaction::None,
            };
        }

        match signal {
            Signal::Connected => {
                // Events sent while no session was open are replayed, but a sync covers a
                // change the relay never saw
                self.connected = true;
                self.force = true;
                Reaction::None
            }
            Signal::Disconnected => {
                if self.connected {
                    tracing::warn!("relay disconnected, syncing every project every sync_interval");
                    self.force = true;
                }
                self.connected = false;
                Reaction::None
            }
            Signal::Gap => {
                self.force = true;
                Reaction::None
            }
            Signal::Event(event) => Reaction::Item(event),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn config() -> EngineConfig {
        EngineConfig {
            sync_interval: Duration::from_secs(45),
            reconcile_interval: Duration::from_secs(600),
            ..EngineConfig::default()
        }
    }

    fn event() -> Signal {
        Signal::Event(Event {
            name: "issues".to_string(),
            action: "opened".to_string(),
            repo: "o/r".to_string(),
            payload: None,
        })
    }

    #[test]
    fn a_connected_relay_runs_the_full_sync_only_at_the_reconcile_interval() {
        let start = Instant::now();
        let mut schedule = SyncSchedule::new(true, start);
        schedule.on_signal(Signal::Connected);
        assert!(
            schedule.due(&config(), start),
            "a connect runs one full sync"
        );
        schedule.ran(start);

        assert!(!schedule.due(&config(), start + Duration::from_secs(46)));
        assert!(!schedule.due(&config(), start + Duration::from_secs(599)));
        assert!(schedule.due(&config(), start + Duration::from_secs(600)));
    }

    #[test]
    fn a_disconnect_runs_a_full_sync_at_once_and_returns_to_the_sync_interval() {
        let start = Instant::now();
        let mut schedule = SyncSchedule::new(true, start);
        schedule.on_signal(Signal::Connected);
        schedule.ran(start);

        schedule.on_signal(Signal::Disconnected);
        let at = start + Duration::from_secs(1);
        assert!(schedule.due(&config(), at));
        schedule.ran(at);

        assert!(!schedule.due(&config(), at + Duration::from_secs(44)));
        assert!(schedule.due(&config(), at + Duration::from_secs(45)));
    }

    #[test]
    fn a_gap_runs_one_full_sync() {
        let start = Instant::now();
        let mut schedule = SyncSchedule::new(true, start);
        schedule.on_signal(Signal::Connected);
        schedule.ran(start);

        assert!(matches!(schedule.on_signal(Signal::Gap), Reaction::None));
        assert!(schedule.due(&config(), start));
        schedule.ran(start);
        assert!(!schedule.due(&config(), start + Duration::from_secs(60)));
    }

    #[test]
    fn a_connected_relay_hands_events_to_the_item_handler() {
        let mut schedule = SyncSchedule::new(true, Instant::now());
        schedule.on_signal(Signal::Connected);

        assert!(matches!(schedule.on_signal(event()), Reaction::Item(_)));
    }

    #[test]
    fn without_the_app_the_schedule_is_unchanged_and_no_item_handler_runs() {
        let start = Instant::now();
        let mut schedule = SyncSchedule::new(false, start);

        assert!(matches!(
            schedule.on_signal(Signal::Connected),
            Reaction::None
        ));
        assert!(!schedule.due(&config(), start));
        assert!(schedule.due(&config(), start + Duration::from_secs(45)));
        assert!(matches!(schedule.on_signal(event()), Reaction::Wake));
        assert!(matches!(schedule.on_signal(Signal::Gap), Reaction::Wake));
        assert!(matches!(
            schedule.on_signal(Signal::Disconnected),
            Reaction::None
        ));
        assert!(!schedule.due(&config(), start + Duration::from_secs(44)));
    }

    #[test]
    fn a_disconnect_before_any_connect_changes_nothing() {
        let start = Instant::now();
        let mut schedule = SyncSchedule::new(true, start);
        schedule.on_signal(Signal::Disconnected);

        assert!(!schedule.due(&config(), start));
    }
}