use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use lean_ctx_time::UtcDateTime;
use super::CloudError;
use super::auth::Session;
use super::config::CloudConfig;
use super::state::CloudStore;
use lean_ctx_protocol::cloud::lease::LeaseState;
fn tick_every(config: &CloudConfig) -> Duration {
Duration::from_secs(u64::from(config.pull_interval()) * 60)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TickOutcome {
Idle,
Renewed,
Stop(String),
Retry(String),
}
pub fn tick(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
let outcome = tick_once(store, config);
if matches!(outcome, TickOutcome::Stop(_)) {
super::receipts::stop_local_recording(store.data_dir());
}
outcome
}
fn tick_once(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
if config.enabled == Some(false) {
return TickOutcome::Stop("disabled by [cloud] enabled = false".into());
}
let Ok(Some(instance)) = store.instance() else {
return TickOutcome::Stop("not connected".into());
};
match super::disconnect::retry_pending(store, config, &instance) {
None => {}
Some(Ok(done)) => return TickOutcome::Stop(done),
Some(Err(error)) if error.is_transient() => {
return TickOutcome::Retry(format!("pending disconnect: {error}"));
}
Some(Err(error)) => {
store.record_error(&format!("pending disconnect: {error}"));
return TickOutcome::Stop(format!("pending disconnect: {error}"));
}
}
if let Err(error) = super::migrate::run(store, config) {
store.record_error(&format!("upgrade: {error}"));
}
let session = super::root_cert::trust_root(store, config, &instance.url)
.and_then(|root| Session::load(store.clone(), root));
let mut session = match session {
Ok(session) => session,
Err(error) => {
store.record_error(&error.to_string());
return TickOutcome::Stop(error.to_string());
}
};
let now = UtcDateTime::now();
if session.lease.state_at(now) == LeaseState::Lapsed {
store.record_error(&CloudError::LeaseLapsed.to_string());
return TickOutcome::Stop(CloudError::LeaseLapsed.to_string());
}
let mut outcome = TickOutcome::Idle;
if session.lease.renew_due(now) {
match session.renew() {
Ok(_) => {
outcome = TickOutcome::Renewed;
if let Ok(client) = session.client() {
super::root_cert::refresh(store, &client, &instance.url);
}
}
Err(error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed)) => {
store.record_error(&error.to_string());
return TickOutcome::Stop(error.to_string());
}
Err(error) => {
store.record_error(&error.to_string());
store.record_renew_error(Some(&error.to_string()));
outcome = TickOutcome::Retry(error.to_string());
}
}
}
if let Err(error) = crate::resolution::load_current(store.data_dir(), None) {
store.record_error(&format!("vault map: {error}"));
}
let screen_problem = super::knowledge::screening::Screen::for_installation().problem();
if let Some(problem) = &screen_problem {
store.record_error(problem);
} else {
if due(store, config, "knowledge", now) {
crate::knowledge::pull::sync(&session, config, None);
}
for problem in crate::tasks::propose::drain(&session).problems {
store.record_error(&format!("tasks: {problem}"));
}
}
if due(store, config, "policy", now)
&& session
.lease
.lease
.grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
{
match crate::policy::pull(&session) {
Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Poll),
Err(error) => store.record_error(&format!("policy: {error}")),
}
}
use crate::metrics_v2::upload::{self as hours, MetricsV2Run};
match hours::run(&session, config, now, false) {
Ok(MetricsV2Run::Sent { .. } | MetricsV2Run::Empty) => store.record_success(
"metrics_v2",
&now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
),
Ok(_) => {}
Err(error) => store.record_error(&format!("instance metrics: {error}")),
}
match crate::receipts::run(&session, config, now) {
Ok(crate::receipts::ReceiptsRun::Sent { accepted, .. }) if accepted > 0 => {
store.record_success(
"receipts",
&now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
);
}
Ok(_) => {}
Err(error) => store.record_error(&format!("receipts: {error}")),
}
let _ = crate::team_stop::refresh_with(store, &session);
outcome
}
fn due(
store: &CloudStore,
config: &CloudConfig,
channel: &str,
now: lean_ctx_time::UtcDateTime,
) -> bool {
let interval = lean_ctx_time::Duration::minutes(i64::from(config.pull_interval()));
store
.activity()
.last_success
.get(channel)
.and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
.is_none_or(|last| now - last.to_utc() >= interval)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Nudge {
version: Option<u64>,
}
impl Nudge {
fn merge(self, other: Self) -> Self {
Self {
version: self.version.zip(other.version).map(|(a, b)| a.max(b)),
}
}
}
struct Nudges {
policy: Option<Nudge>,
last_run: Option<Instant>,
}
static NUDGES: Mutex<Nudges> = Mutex::new(Nudges {
policy: None,
last_run: None,
});
static NUDGE_WAKE: Condvar = Condvar::new();
const NUDGE_SPACING: Duration = Duration::from_secs(10);
fn nudges() -> MutexGuard<'static, Nudges> {
NUDGES.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn nudge_policy(version: Option<u64>) {
{
let mut pending = nudges();
let nudge = Nudge { version };
pending.policy = Some(pending.policy.map_or(nudge, |held| held.merge(nudge)));
}
NUDGE_WAKE.notify_all();
}
fn wait_nudge(deadline: Instant) -> Option<Nudge> {
let mut pending = nudges();
loop {
let now = Instant::now();
let until = match pending.policy {
Some(nudge) => {
let ready = pending.last_run.map_or(now, |last| last + NUDGE_SPACING);
if ready <= now {
pending.policy = None;
pending.last_run = Some(now);
return Some(nudge);
}
ready.min(deadline)
}
None => deadline,
};
if until <= now {
return None;
}
pending = NUDGE_WAKE
.wait_timeout(pending, until - now)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
}
fn nudge_needed(requested: Option<u64>, installed: Option<u64>) -> bool {
match requested {
None => true,
Some(version) => installed.is_none_or(|have| have < version),
}
}
pub(crate) fn connected_session(
store: &CloudStore,
config: &CloudConfig,
) -> Result<Session, CloudError> {
if config.enabled == Some(false) {
return Err(CloudError::NotConnected);
}
let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
let root = super::root_cert::trust_root(store, config, &instance.url)?;
let session = Session::load(store.clone(), root)?;
if session.lease.state_at(UtcDateTime::now()) == LeaseState::Lapsed {
return Err(CloudError::LeaseLapsed);
}
Ok(session)
}
fn policy_now(store: &CloudStore, config: &CloudConfig, requested: Option<u64>) {
let installed = crate::policy::load_state(store.data_dir())
.effective
.map(|effective| effective.version);
if config.enabled == Some(false) || !nudge_needed(requested, installed) {
return;
}
let session = match connected_session(store, config) {
Ok(session) => session,
Err(error) => {
store.record_error(&format!("policy nudge: {error}"));
return;
}
};
if !session
.lease
.lease
.grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
{
return;
}
match crate::policy::pull(&session) {
Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Nudge),
Err(error) => store.record_error(&format!("policy: {error}")),
}
}
pub(crate) const CONNECT_POLL: Duration = Duration::from_secs(15);
const STOPPED_BACKOFF_MAX: Duration = Duration::from_secs(3600);
pub(crate) fn is_connected(store: &CloudStore) -> bool {
matches!(store.instance(), Ok(Some(_)))
}
pub(crate) fn wait_until_connected(store: &CloudStore, poll: Duration) {
wait_until(poll, || is_connected(store).then_some(()));
}
fn wait_until<T>(poll: Duration, mut ready: impl FnMut() -> Option<T>) -> T {
loop {
if let Some(value) = ready() {
return value;
}
std::thread::sleep(poll);
}
}
pub fn spawn(config: &CloudConfig) -> Option<std::thread::JoinHandle<()>> {
let store = CloudStore::open().ok()?;
if config.enabled == Some(false) {
super::receipts::stop_local_recording(store.data_dir());
return None;
}
if connected_session(&store, config).is_err() {
super::receipts::stop_local_recording(store.data_dir());
}
std::thread::Builder::new()
.name("cloud-scheduler".into())
.spawn(move || {
serve(
CONNECT_POLL,
STOPPED_BACKOFF_MAX,
|| {
let config = lean_ctx::core::config::Config::load().cloud.clone();
connected_session(&store, &config).is_ok().then_some(config)
},
|config| run_passes(&store, config),
std::thread::sleep,
usize::MAX,
);
})
.ok()
}
fn serve<C>(
poll: Duration,
max: Duration,
mut ready: impl FnMut() -> Option<C>,
mut run: impl FnMut(C) -> bool,
mut sleep: impl FnMut(Duration),
rounds: usize,
) {
let mut backoff = poll;
for _ in 0..rounds {
let config = loop {
if let Some(config) = ready() {
break config;
}
sleep(poll);
};
if run(config) {
backoff = poll;
sleep(poll);
} else {
sleep(backoff);
backoff = backoff.saturating_mul(2).min(max);
}
}
}
fn run_passes(store: &CloudStore, mut config: CloudConfig) -> bool {
super::sync::auto::spawn(store.clone(), config.clone());
let mut ran = false;
loop {
if let TickOutcome::Stop(_) = tick(store, &config) {
super::sync::auto::stop();
return ran;
}
ran = true;
let next = Instant::now() + tick_every(&config);
while let Some(nudge) = wait_nudge(next) {
policy_now(store, &config, nudge.version);
}
config = lean_ctx::core::config::Config::load().cloud.clone();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_nudge_pulls_only_a_newer_version_or_after_a_reconnect() {
assert!(nudge_needed(None, Some(9)));
assert!(nudge_needed(Some(3), None));
assert!(nudge_needed(Some(4), Some(3)));
assert!(!nudge_needed(Some(3), Some(3)));
assert!(!nudge_needed(Some(2), Some(3)));
}
#[test]
fn a_pass_that_stops_at_once_backs_off() {
let poll = Duration::from_secs(15);
let max = Duration::from_secs(60);
let mut asked = 0;
let mut runs = 0;
let mut slept = Vec::new();
serve(
poll,
max,
|| {
asked += 1;
(asked != 2).then_some(())
},
|()| {
runs += 1;
runs == 4
},
|d| slept.push(d.as_secs()),
6,
);
assert_eq!(runs, 6);
assert_eq!(slept, [15, 15, 30, 60, 15, 15, 30]);
}
#[test]
fn the_wait_ends_once_the_machine_is_connected() {
let tmp = tempfile::tempdir().unwrap();
let store = CloudStore::at(tmp.path().join("config"), tmp.path().join("data"));
assert!(!is_connected(&store));
let waiting = {
let store = store.clone();
std::thread::spawn(move || wait_until_connected(&store, Duration::from_millis(5)))
};
std::thread::sleep(Duration::from_millis(30));
assert!(!waiting.is_finished(), "no instance record: still waiting");
let record = crate::state::InstanceRecord {
instance_id: "inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c".into(),
org_id: "org_ada".into(),
org_name: "ada".into(),
label: "laptop".into(),
url: "https://cloud.example".into(),
org_salt_id: "s".into(),
enrolled_at: "2026-11-26T10:00:00Z".into(),
web_url: None,
org_kind: None,
company_name: None,
};
store
.write_config(crate::state::INSTANCE_FILE, &record)
.unwrap();
waiting.join().unwrap();
assert!(is_connected(&store));
}
#[test]
fn nudges_coalesce_and_are_spaced() {
let soon = || Instant::now() + Duration::from_millis(50);
assert_eq!(wait_nudge(soon()), None, "no nudge: the deadline");
nudge_policy(Some(4));
nudge_policy(None);
nudge_policy(Some(6));
assert_eq!(
wait_nudge(soon()),
Some(Nudge { version: None }),
"one pull for the burst; the reconnect pulls regardless"
);
nudge_policy(Some(7));
assert_eq!(wait_nudge(soon()), None);
nudges().last_run = Instant::now().checked_sub(NUDGE_SPACING);
assert_eq!(wait_nudge(soon()), Some(Nudge { version: Some(7) }));
}
}