use super::policy::{NetworkPolicy, Thermal};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use troupekit_core::clock::{Clock, SystemClock};
const UNKNOWN: u8 = u8::MAX;
const OFFLINE: u8 = 0;
const ONLINE: u8 = 1;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RouteTags {
pub private: bool,
pub tier: Option<String>,
}
impl RouteTags {
pub fn with_private(mut self, private: bool) -> Self {
self.private = private;
self
}
pub fn with_tier(mut self, tier: impl Into<String>) -> Self {
self.tier = Some(tier.into());
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Signals {
pub online: Option<bool>,
pub battery_percent: Option<u8>,
pub thermal: Option<Thermal>,
pub cloud_spent_today_usd_micros: u64,
pub prompt_tokens: u64,
pub max_tokens: u64,
}
impl Signals {
pub fn with_online(mut self, online: Option<bool>) -> Self {
self.online = online;
self
}
pub fn with_battery_percent(mut self, percent: Option<u8>) -> Self {
self.battery_percent = percent.map(|p| p.min(100));
assert!(self.battery_percent.is_none_or(|p| p <= 100));
self
}
pub fn with_thermal(mut self, thermal: Option<Thermal>) -> Self {
self.thermal = thermal;
self
}
pub fn with_cloud_spent_today_usd_micros(mut self, spent: u64) -> Self {
self.cloud_spent_today_usd_micros = spent;
self
}
pub fn with_prompt_tokens(mut self, tokens: u64) -> Self {
self.prompt_tokens = tokens;
self
}
pub fn with_max_tokens(mut self, tokens: u64) -> Self {
self.max_tokens = tokens;
self
}
}
pub trait NetworkProbe: Send + Sync {
fn online(&self) -> Option<bool>;
fn record_remote(&self, network_failed: bool) {
let _ = network_failed;
}
}
#[derive(Debug, Clone)]
pub struct NetworkState(Arc<AtomicU8>);
impl Default for NetworkState {
fn default() -> Self {
Self::new()
}
}
impl NetworkState {
pub fn new() -> Self {
Self(Arc::new(AtomicU8::new(UNKNOWN)))
}
pub fn set(&self, online: Option<bool>) {
let raw = match online {
None => UNKNOWN,
Some(false) => OFFLINE,
Some(true) => ONLINE,
};
self.0.store(raw, Ordering::SeqCst);
}
}
impl NetworkProbe for NetworkState {
fn online(&self) -> Option<bool> {
match self.0.load(Ordering::SeqCst) {
UNKNOWN => None,
OFFLINE => Some(false),
ONLINE => Some(true),
raw => unreachable!("network state holds unknown value {raw}"),
}
}
}
#[derive(Debug, Default)]
struct ProbeState {
failures: u32,
offline_since_ms: Option<i64>,
}
pub struct PassiveProbe {
failures_max: u32,
retry_after_ms: i64,
clock: Arc<dyn Clock>,
state: Mutex<ProbeState>,
}
impl PassiveProbe {
pub fn new(network: &NetworkPolicy) -> Self {
let failures_max = network.offline_after_failures();
assert!(failures_max >= 1, "policy allows at least one failure");
let retry_after_ms =
i64::try_from(network.retry_online_after_ms()).expect("policy bounds the retry delay");
assert!(retry_after_ms >= 1, "policy retry delay is positive");
Self {
failures_max,
retry_after_ms,
clock: Arc::new(SystemClock),
state: Mutex::new(ProbeState::default()),
}
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
fn lock(&self) -> std::sync::MutexGuard<'_, ProbeState> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
}
impl NetworkProbe for PassiveProbe {
fn online(&self) -> Option<bool> {
let state = self.lock();
let since = state.offline_since_ms?;
assert!(
state.failures >= self.failures_max,
"offline needs the failures"
);
let waited = self.clock.now_ms().saturating_sub(since);
if waited >= self.retry_after_ms {
None
} else {
Some(false)
}
}
fn record_remote(&self, network_failed: bool) {
let now = self.clock.now_ms();
let mut state = self.lock();
if !network_failed {
*state = ProbeState::default();
return;
}
state.failures = state.failures.saturating_add(1);
if state.failures >= self.failures_max {
let since = state.offline_since_ms.map_or(now, |s| s.max(now));
state.offline_since_ms = Some(since);
}
assert!(
state.offline_since_ms.is_some() || state.failures < self.failures_max,
"enough failures always mark offline"
);
assert!(
state.offline_since_ms.is_none_or(|s| s >= now),
"an older failure never moves the offline start back"
);
}
}
#[derive(Debug, Clone)]
pub struct DeviceState(Arc<(AtomicU8, AtomicU8)>);
impl Default for DeviceState {
fn default() -> Self {
Self::new()
}
}
fn thermal_code(thermal: Thermal) -> u8 {
match thermal {
Thermal::Nominal => 0,
Thermal::Fair => 1,
Thermal::Serious => 2,
Thermal::Critical => 3,
}
}
impl DeviceState {
pub fn new() -> Self {
Self(Arc::new((AtomicU8::new(UNKNOWN), AtomicU8::new(UNKNOWN))))
}
pub fn set_battery_percent(&self, percent: Option<u8>) {
let stored = percent.map_or(UNKNOWN, |p| p.min(100));
assert!(stored <= 100 || stored == UNKNOWN);
self.0 .0.store(stored, Ordering::SeqCst);
}
pub fn set_thermal(&self, thermal: Option<Thermal>) {
self.0
.1
.store(thermal.map_or(UNKNOWN, thermal_code), Ordering::SeqCst);
}
pub fn battery_percent(&self) -> Option<u8> {
let raw = self.0 .0.load(Ordering::SeqCst);
assert!(raw <= 100 || raw == UNKNOWN, "battery holds {raw}");
(raw != UNKNOWN).then_some(raw)
}
pub fn thermal(&self) -> Option<Thermal> {
match self.0 .1.load(Ordering::SeqCst) {
UNKNOWN => None,
0 => Some(Thermal::Nominal),
1 => Some(Thermal::Fair),
2 => Some(Thermal::Serious),
3 => Some(Thermal::Critical),
raw => unreachable!("thermal state holds unknown value {raw}"),
}
}
}