use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
use crate::errors::CoreError;
use crate::paths;
pub const STARTUP_TTL_MINUTES: i64 = 5;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StartupStatus {
pub version: String,
pub migrations_applied_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider_ok_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cloud_ok_at: Option<DateTime<Utc>>,
}
impl StartupStatus {
fn is_fresh(&self, now: DateTime<Utc>) -> bool {
let ttl = Duration::minutes(STARTUP_TTL_MINUTES);
let migrations_fresh = (now - self.migrations_applied_at) < ttl;
let provider_fresh = self.provider_ok_at.is_none_or(|t| (now - t) < ttl);
let cloud_fresh = self.cloud_ok_at.is_none_or(|t| (now - t) < ttl);
migrations_fresh && provider_fresh && cloud_fresh
}
}
fn cache_path() -> Result<PathBuf, CoreError> {
let dir = paths::data_home().map_err(CoreError::Internal)?;
Ok(dir.join("startup-cache.json"))
}
async fn read_cache() -> Option<StartupStatus> {
let path = cache_path().ok()?;
let bytes = fs::read(&path).await.ok()?;
serde_json::from_slice(&bytes).ok()
}
async fn write_cache(status: &StartupStatus) -> Result<(), CoreError> {
let path = cache_path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await?;
}
let bytes = serde_json::to_vec_pretty(status)?;
fs::write(&path, bytes).await?;
Ok(())
}
static MEMORY_CACHE: tokio::sync::Mutex<Option<StartupStatus>> =
tokio::sync::Mutex::const_new(None);
async fn run_full_check() -> Result<StartupStatus, CoreError> {
let now = Utc::now();
let _pool = crate::db::init_db().await.map_err(CoreError::Internal)?;
if let Ok(pool) = crate::db::init_db().await {
let queue = crate::cloud::outbox::OutboxQueue::new(pool);
if let Err(e) = queue
.reset_stale(crate::cloud::outbox::DEFAULT_STALE_SECONDS)
.await
{
eprintln!("[difflore] cloud_outbox reset_stale skipped: {e}");
}
}
let db = crate::db::init_db().await.map_err(CoreError::Internal)?;
let provider_ok_at = match crate::providers::list(&db).await {
Ok(_) => Some(now),
Err(_) => None,
};
let cloud_ok_at = {
let client = crate::cloud::client::CloudClient::create().await;
if client.is_logged_in() {
let req = crate::cloud::api_types::RecallPastVerdictsRequest {
embedding: Vec::new(),
query_text: Some("_ping_".to_owned()),
repo_id: None,
scope: "personal".to_owned(),
team_id: None,
k: 1,
target_file: None,
};
match client.recall_past_verdicts(req).await {
Ok(_) => Some(now),
Err(_) => None,
}
} else {
None
}
};
let status = StartupStatus {
version: env!("CARGO_PKG_VERSION").to_owned(),
migrations_applied_at: now,
provider_ok_at,
cloud_ok_at,
};
write_cache(&status).await?;
Ok(status)
}
pub async fn ensure_ready(force: bool) -> Result<StartupStatus, CoreError> {
let now = Utc::now();
if !force {
if let Some(cached) = MEMORY_CACHE.lock().await.as_ref()
&& cached.is_fresh(now)
{
return Ok(cached.clone());
}
if let Some(cached) = read_cache().await
&& cached.is_fresh(now)
{
*MEMORY_CACHE.lock().await = Some(cached.clone());
return Ok(cached);
}
}
let status = run_full_check().await?;
*MEMORY_CACHE.lock().await = Some(status.clone());
Ok(status)
}
#[cfg(test)]
mod tests {
use super::*;
static CACHE_SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[test]
fn is_fresh_handles_missing_probes() {
let now = Utc::now();
let status = StartupStatus {
version: "0.1.0".into(),
migrations_applied_at: now,
provider_ok_at: None,
cloud_ok_at: None,
};
assert!(status.is_fresh(now));
}
#[test]
fn is_fresh_rejects_stale_migrations() {
let now = Utc::now();
let status = StartupStatus {
version: "0.1.0".into(),
migrations_applied_at: now - Duration::minutes(STARTUP_TTL_MINUTES + 1),
provider_ok_at: Some(now),
cloud_ok_at: Some(now),
};
assert!(!status.is_fresh(now));
}
#[test]
fn is_fresh_rejects_stale_cloud() {
let now = Utc::now();
let status = StartupStatus {
version: "0.1.0".into(),
migrations_applied_at: now,
provider_ok_at: Some(now),
cloud_ok_at: Some(now - Duration::minutes(STARTUP_TTL_MINUTES + 1)),
};
assert!(!status.is_fresh(now));
}
#[tokio::test]
async fn ensure_ready_caches_between_calls() {
let _guard = CACHE_SERIAL.lock().await;
let _home = crate::db::shared_test_home();
let first = ensure_ready(true).await.expect("first call");
let first_ts = first.migrations_applied_at;
let second = ensure_ready(false).await.expect("second call");
assert_eq!(
second.migrations_applied_at, first_ts,
"second call should come from cache, not re-run"
);
}
#[tokio::test]
async fn ensure_ready_force_refreshes_cache() {
let _guard = CACHE_SERIAL.lock().await;
let _home = crate::db::shared_test_home();
let first = ensure_ready(false).await.expect("first call");
let first_ts = first.migrations_applied_at;
tokio::time::sleep(std::time::Duration::from_millis(15)).await;
let second = ensure_ready(true).await.expect("force call");
assert!(
second.migrations_applied_at > first_ts,
"force=true must re-run the full check (got {} vs {first_ts})",
second.migrations_applied_at
);
}
}