use std::time::Duration;
use serde::Deserialize;
use zeroize::Zeroizing;
const MAX_ANSWER: u64 = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Action {
Run,
Stop,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Tick {
pub action: Action,
pub state: String,
pub booked_minutes: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum TickError {
Refused(u16),
NotConfigured,
Status(u16),
Offline(String),
Protocol(String),
}
impl std::fmt::Display for TickError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TickError::Refused(code) => write!(f, "the cloud refused the meter token ({code})"),
TickError::NotConfigured => {
f.write_str("metering is not configured on this cloud (503)")
}
TickError::Status(code) => write!(f, "the cloud answered {code}"),
TickError::Offline(why) => write!(f, "the cloud is unreachable: {why}"),
TickError::Protocol(why) => write!(f, "unexpected tick answer: {why}"),
}
}
}
#[derive(Deserialize)]
struct Answer {
computer: AnswerComputer,
action: String,
booked: Option<Booked>,
}
#[derive(Deserialize)]
struct AnswerComputer {
state: String,
}
#[derive(Deserialize)]
struct Booked {
from_minute: i64,
to_minute: i64,
}
pub(crate) fn parse_tick(body: &[u8]) -> Result<Tick, TickError> {
let answer: Answer =
serde_json::from_slice(body).map_err(|e| TickError::Protocol(e.to_string()))?;
let action = match answer.action.as_str() {
"run" => Action::Run,
"stop" => Action::Stop,
_ => return Err(TickError::Protocol("action is neither run nor stop".into())),
};
let state: String = answer
.computer
.state
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.take(40)
.collect();
let booked_minutes = answer
.booked
.map_or(0, |b| b.to_minute.saturating_sub(b.from_minute).max(0));
Ok(Tick {
action,
state,
booked_minutes,
})
}
pub(crate) fn status_error(status: u16) -> TickError {
match status {
401 | 403 => TickError::Refused(status),
503 => TickError::NotConfigured,
_ => TickError::Status(status),
}
}
pub(crate) fn computer_url(origin: &str, computer_id: &str) -> String {
format!("{origin}/api/v1/computer-meter/computers/{computer_id}")
}
pub(crate) struct Meter {
agent: ureq::Agent,
url: String,
bearer: Zeroizing<String>,
}
impl Meter {
pub(crate) fn new(origin: &str, computer_id: &str, token: &str) -> Result<Self, String> {
if !origin.starts_with("https://") {
return Err("the meter talks to an https:// origin only".into());
}
let agent: ureq::Agent = ureq::config::Config::builder()
.tls_config(lean_ctx::core::http_client::platform_tls_config())
.http_status_as_error(false)
.max_redirects(0)
.https_only(true)
.timeout_resolve(Some(Duration::from_secs(5)))
.timeout_connect(Some(Duration::from_secs(10)))
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into();
Ok(Self {
agent,
url: computer_url(origin, computer_id),
bearer: Zeroizing::new(format!("Bearer {token}")),
})
}
pub(crate) fn tick(&self, active: bool) -> Result<Tick, TickError> {
let body = serde_json::json!({
"request_id": uuid::Uuid::new_v4().to_string(),
"active": active,
});
parse_tick(&self.post("tick", &body)?)
}
pub(crate) fn host_keys(&self, fingerprints: &[String]) -> Result<(), TickError> {
let body = serde_json::json!({ "fingerprints": fingerprints });
self.post("host-keys", &body).map(drop)
}
fn post(&self, route: &str, body: &serde_json::Value) -> Result<Vec<u8>, TickError> {
let response = self
.agent
.post(&format!("{}/{route}", self.url))
.header("Authorization", self.bearer.as_str())
.header("User-Agent", lean_ctx_cloud::transport::user_agent())
.header("Content-Type", "application/json")
.send(body.to_string().as_bytes())
.map_err(|e| TickError::Offline(e.to_string()))?;
let status = response.status().as_u16();
if status != 200 {
return Err(status_error(status));
}
response
.into_body()
.into_with_config()
.limit(MAX_ANSWER)
.read_to_vec()
.map_err(|e| TickError::Protocol(format!("body: {e}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_metered_tick_parses() {
let body = br#"{"computer":{"id":"0b7a3f4e-9c1d-4e2a-8f00-1234567890ab","org_id":"x","role":"weave_host",
"state":"running","stop_reason":null,"vcpu":2,"ram_gib":4,"usd_micros_per_hour":90000,
"run_id":"r","started_at":"2026-11-20T10:00:00Z","created_at":"2026-11-20T09:59:00Z"},
"action":"run","booked":{"from_minute":3,"to_minute":5,"allowance_minutes":2,"paid_minutes":0,
"cost_usd_micros":0,"topup_usd_micros":0}}"#;
let tick = parse_tick(body).unwrap();
assert_eq!(tick.action, Action::Run);
assert_eq!(tick.state, "running");
assert_eq!(tick.booked_minutes, 2);
}
#[test]
fn a_stop_and_an_unbooked_tick_parse() {
let body = br#"{"computer":{"state":"suspended_balance"},"action":"stop","booked":null}"#;
let tick = parse_tick(body).unwrap();
assert_eq!(tick.action, Action::Stop);
assert_eq!(tick.state, "suspended_balance");
assert_eq!(tick.booked_minutes, 0);
}
#[test]
fn anything_else_is_a_protocol_error() {
for body in [
&br#"{"computer":{"state":"running"},"action":"reboot","booked":null}"#[..],
br#"{"action":"run","booked":null}"#,
b"<html>",
b"",
] {
assert!(matches!(parse_tick(body), Err(TickError::Protocol(_))));
}
let odd = br#"{"computer":{"state":"run\u001b[31mning"},"action":"run","booked":null}"#;
assert_eq!(parse_tick(odd).unwrap().state, "run31mning");
}
#[test]
fn statuses_map_to_their_meaning_and_the_url_holds_no_token() {
assert_eq!(status_error(401), TickError::Refused(401));
assert_eq!(status_error(403), TickError::Refused(403));
assert_eq!(status_error(503), TickError::NotConfigured);
assert_eq!(status_error(500), TickError::Status(500));
assert_eq!(
computer_url(
"https://cloud.leanctx.com",
"0b7a3f4e-9c1d-4e2a-8f00-1234567890ab"
),
"https://cloud.leanctx.com/api/v1/computer-meter/computers/0b7a3f4e-9c1d-4e2a-8f00-1234567890ab"
);
assert!(Meter::new("http://cloud.leanctx.com", "x", "lcm_x").is_err());
}
}