eclipse-gateway 0.13.4

The Eclipse gateway: the dashboard, the OpenAI-compatible API and the scheduled check, on one pid
//! The gateway's background work: the provider probe that keeps `/healthz` a read, and the
//! scheduled upgrade check that reports without installing.
//!
//! Both run inside the serving process. That is the point of the shape: cron keeps its own
//! timer so a wedged tick cannot take the dashboard with it, and nothing here may block a
//! request.

use eclipse_core::config::Config;
use eclipse_web::app::Shared;
use std::time::Duration;

/// Probe the provider once a minute and cache the answer on the state. `/healthz` reads the
/// cache, so a stopped model is reported as a fact rather than as a timeout inside a
/// conversation.
pub fn spawn_model_probe(state: Shared, cfg: Config) {
    let Some(agent) = state.agent.clone() else {
        return;
    };
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(Duration::from_secs(60));
        loop {
            interval.tick().await;
            let (model, endpoint) = match agent.route_infos().into_iter().next() {
                Some(r) => (r.model, r.endpoint),
                None => (cfg.provider.model.clone(), cfg.provider.base_url.clone()),
            };
            let reachable = eclipse_core::provider::advertised_context_window(
                &endpoint,
                cfg.provider.api_key.as_deref(),
                &model,
                Duration::from_secs(2),
            )
            .await
            .is_some();
            *state.model_probe.lock().unwrap_or_else(|e| e.into_inner()) =
                Some((std::time::Instant::now(), reachable));
        }
    });
}

/// Two unchecked multiplications became this: `#396`.
///
/// `hours * 3_600_000` and `hours * 3600` are `u64` arithmetic and the workspace sets no overflow
/// checks, so a release build wraps instead of refusing. A TTL large enough to wrap can land on
/// **zero** milliseconds — `2**57` hours does exactly that — which turns "keep forever" into "prune
/// everything" on the next tick. Saturating keeps a huge value meaning "never", which is what it
/// says, and needs no cap to be agreed on.
fn hours_as_secs(hours: u64) -> u64 {
    hours.saturating_mul(3600)
}

fn hours_as_ms(hours: u64) -> u64 {
    hours.saturating_mul(3_600_000)
}

/// The scheduled upgrade check: ask through the library, log the verdict, change nothing. A
/// version change is a decision, and the gateway is not the place to make it.
///
/// It writes the same `update.json` a CLI run reads, so whichever of them asked first spares the
/// other the request — which is what keeps three open dashboard tabs from counting as three
/// clients. `refresh` is what decides whether a question is due, so the first tick after a
/// restart costs a file read when the answer is still fresh, and catches a machine that has
/// been off instead of showing it nothing for a whole interval.
pub fn spawn_upgrade_check(cfg: Config, state: std::path::PathBuf) {
    if cfg.gateway.check_interval_hours == 0 {
        return;
    }
    let every = Duration::from_secs(hours_as_secs(cfg.gateway.check_interval_hours));
    tokio::spawn(async move {
        loop {
            log_outcome(eclipse_core::update::refresh(&state, &cfg.update).await);
            tokio::time::sleep(every).await;
        }
    });
}

/// One line per tick that did something. `NotDue` is the ordinary case once the answer is
/// cached, and saying so every six hours would be noise in a journal — so it is silent, and the
/// caller writes whatever this returns.
fn verdict_line(outcome: &eclipse_core::update::Outcome) -> Option<String> {
    use eclipse_core::update::Outcome;
    match outcome {
        Outcome::NotDue => None,
        Outcome::Current => Some("[upgrade] current".to_string()),
        Outcome::Behind(behind) => Some(format!(
            "[upgrade] behind: {} available, installed {}",
            behind.latest, behind.installed
        )),
        Outcome::Failed(why) => Some(format!("[upgrade] {why}")),
    }
}

fn log_outcome(outcome: eclipse_core::update::Outcome) {
    if let Some(line) = verdict_line(&outcome) {
        eprintln!("{line}");
    }
}

/// Sweep the sessions the API left behind.
///
/// `POST /v1/chat/completions` drives a real run, and the loop stores every turn — there is no
/// stateless path through it. So each call leaves a session, tagged `api`; this deletes the ones
/// older than `[gateway] api_session_ttl_hours`, once at startup and then hourly. A script polling
/// the endpoint therefore reaches a steady state instead of filling the store.
pub fn spawn_session_prune(state: Shared, cfg: Config) {
    let ttl = cfg.gateway.api_session_ttl_hours;
    if ttl == 0 {
        return;
    }
    let Some(agent) = state.agent.clone() else {
        return;
    };
    tokio::spawn(async move {
        // The first tick is immediate: a machine that was off for a week catches up on start.
        let mut interval = tokio::time::interval(Duration::from_secs(3600));
        loop {
            interval.tick().await;
            let cutoff = eclipse_core::session::now_ms().saturating_sub(hours_as_ms(ttl));
            match agent.store().prune_api_sessions(cutoff) {
                Ok(0) => {}
                Ok(n) => eprintln!("[sessions] pruned {n} API session(s) older than {ttl}h"),
                Err(e) => eprintln!("[sessions] could not prune API sessions: {e}"),
            }
        }
    });
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use eclipse_core::update::{Behind, Outcome};

    /// A tick that asked and found something newer says what it found, with both numbers. A tick
    /// that asked nothing (the ordinary case once the cache is fresh) says nothing at all: a
    /// journal line every six hours saying "still current" is noise, not information.
    #[test]
    fn a_tick_reports_what_it_found_and_stays_quiet_when_it_asked_nothing() {
        let behind = Outcome::Behind(Behind {
            installed: "0.7.0".into(),
            latest: "v0.8.0".into(),
        });
        let line = verdict_line(&behind).expect("a behind tick says so");
        assert!(
            line.contains("v0.8.0") && line.contains("0.7.0"),
            "both numbers, or the operator cannot tell what to do: {line}"
        );
        assert_eq!(verdict_line(&Outcome::NotDue), None);
        assert!(verdict_line(&Outcome::Failed("no route".into()))
            .expect("a failure is worth a line")
            .contains("no route"));
    }

    /// `#396`: a TTL big enough to overflow must saturate to "never", never wrap to a small number.
    /// `2**57` hours is the value that wraps to exactly zero: the cutoff then becomes *now* and the
    /// next tick deletes every API session. In a debug build the unreverted multiplication panics on
    /// overflow instead of wrapping, so this fails either way round.
    #[test]
    fn a_huge_ttl_means_never_and_does_not_wrap_into_pruning_everything() {
        let never = 1_u64 << 57;
        assert_eq!(hours_as_ms(never), u64::MAX, "2**57 hours is not zero ms");
        assert_eq!(hours_as_secs(never), u64::MAX, "2**57 hours is not zero s");

        // …and the cutoff that follows from it is the beginning of the clock: nothing is older.
        let now = 1_700_000_000_000_u64;
        assert_eq!(now.saturating_sub(hours_as_ms(never)), 0);

        // The audit's own exemplar is enormous rather than exactly wrapping: still "never".
        let exemplar = 10_249_152_000_000_u64;
        assert_eq!(now.saturating_sub(hours_as_ms(exemplar)), 0);

        // Ordinary values are untouched — this fix is not a cap.
        assert_eq!(hours_as_ms(24), 86_400_000);
        assert_eq!(hours_as_secs(6), 21_600);
    }
}