use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
use serde_json::Value;
#[derive(Debug, Clone, Default)]
pub struct FleetClientConfig {
pub base_url: String,
pub customer: String,
pub machine: String,
pub software: String,
pub token: Option<String>,
pub heartbeat_interval: Duration,
pub version: Option<String>,
pub group: Option<String>,
pub group_priority: Option<i64>,
pub sort_priority: Option<i64>,
pub location: Option<String>,
pub identity: DeviceIdentity,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeviceIdentity {
pub serial: Option<String>,
pub display_name: Option<String>,
pub inventory_no: Option<String>,
pub stream: Option<String>,
pub branding: Option<String>,
pub initial_password_scheme: Option<String>,
pub initial_password_changed: Option<bool>,
}
impl DeviceIdentity {
pub fn from_fleet_json(fm: &Value) -> Self {
let text = |key: &str| fm.get(key).and_then(|v| v.as_str()).map(String::from);
let serial_file = std::env::var("FLEET_SERIAL_FILE")
.ok()
.filter(|s| !s.is_empty())
.or_else(|| text("serial_file"));
let serial = match serial_file {
Some(path) => match std::fs::read_to_string(&path) {
Ok(content) => content
.lines()
.next()
.map(|l| l.trim().to_string())
.filter(|s| !s.is_empty()),
Err(e) => {
log::warn!("serial file {} not readable: {}", path, e);
None
}
},
None => text("serial")
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty()),
};
Self {
serial,
display_name: text("display_name"),
inventory_no: text("inventory_no"),
stream: text("stream"),
branding: None,
initial_password_scheme: text("initial_password_scheme"),
initial_password_changed: fm.get("initial_password_changed").and_then(|v| v.as_bool()),
}
}
fn apply_to(&self, payload: &mut Value) {
let strings = [
("serial", &self.serial),
("display_name", &self.display_name),
("inventory_no", &self.inventory_no),
("stream", &self.stream),
("branding", &self.branding),
("initial_password_scheme", &self.initial_password_scheme),
];
for (key, value) in strings {
if let Some(v) = value {
payload[key] = Value::String(v.clone());
}
}
if let Some(changed) = self.initial_password_changed {
payload["initial_password_changed"] = Value::Bool(changed);
}
}
}
impl FleetClientConfig {
pub fn from_legacy(
broker: &str,
port: Option<u16>,
use_tls: bool,
customer: &str,
machine: &str,
software: &str,
token: Option<String>,
) -> Self {
let proto = if use_tls { "https" } else { "http" };
let base_url = match port {
Some(p) if p != 80 && p != 443 => format!("{}://{}:{}", proto, broker, p),
_ => format!("{}://{}", proto, broker),
};
Self {
base_url,
customer: slugify(customer),
machine: slugify(machine),
software: slugify(software),
token,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
}
}
}
pub fn slugify(value: &str) -> String {
let lower = value.to_lowercase();
let slug: String = lower
.chars()
.map(|c| if c.is_alphanumeric() { c } else { '-' })
.collect();
slug.trim_matches('-').to_string()
}
fn now_iso() -> String {
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}
fn get_local_ips() -> Vec<String> {
if let Ok(env_ips) = std::env::var("FLEET_HOST_IPS") {
let ips: Vec<String> = env_ips
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if !ips.is_empty() {
return ips;
}
}
Vec::new()
}
type CommandCallback = Box<dyn Fn(Vec<Value>) + Send + Sync>;
pub const CHANNELS: [&str; 3] = ["nightly", "candidate", "stable"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelSource {
Fleet,
Delivery,
}
struct ClientState {
connected: bool,
last_send_attempt: Option<String>,
last_send_success: Option<String>,
last_connect_error: Option<String>,
}
pub struct FleetMonitorClient {
config: RwLock<FleetClientConfig>,
state: RwLock<ClientState>,
pub(crate) start_time: Mutex<Option<Instant>>,
pub(crate) stop_flag: Arc<std::sync::atomic::AtomicBool>,
on_commands: RwLock<Option<CommandCallback>>,
licence: RwLock<Option<Value>>,
hardware: RwLock<Option<Value>>,
fleet_channel: RwLock<Option<String>>,
build_channel: RwLock<Option<String>>,
http_client: reqwest::Client,
}
impl FleetMonitorClient {
pub fn set_branding(&self, branding: Option<String>) {
self.config.write().unwrap().identity.branding = branding;
}
pub fn set_licence(&self, report: Option<Value>) {
*self.licence.write().unwrap() = report;
}
pub fn set_hardware(&self, report: Option<Value>) {
*self.hardware.write().unwrap() = report;
}
pub fn set_build_channel(&self, channel: Option<String>) -> Result<(), String> {
if let Some(ref c) = channel {
if !CHANNELS.contains(&c.as_str()) {
return Err(format!("unknown release channel: {c:?}"));
}
}
*self.build_channel.write().unwrap() = channel;
Ok(())
}
pub fn channel(&self) -> Option<(String, ChannelSource)> {
if self.is_connected() {
if let Some(c) = self.fleet_channel.read().unwrap().clone() {
return Some((c, ChannelSource::Fleet));
}
}
self.build_channel
.read()
.unwrap()
.clone()
.map(|c| (c, ChannelSource::Delivery))
}
pub fn new(config: FleetClientConfig) -> Self {
Self {
config: RwLock::new(config),
state: RwLock::new(ClientState {
connected: false,
last_send_attempt: None,
last_send_success: None,
last_connect_error: None,
}),
start_time: Mutex::new(None),
stop_flag: Arc::new(std::sync::atomic::AtomicBool::new(false)),
on_commands: RwLock::new(None),
licence: RwLock::new(None),
hardware: RwLock::new(None),
fleet_channel: RwLock::new(None),
build_channel: RwLock::new(None),
http_client: reqwest::Client::new(),
}
}
pub fn start(&self) {
log::info!("Fleet Monitor starting");
*self.start_time.lock().unwrap() = Some(Instant::now());
self.stop_flag
.store(false, std::sync::atomic::Ordering::SeqCst);
}
pub fn stop(&self) {
log::info!("Fleet Monitor stopping");
self.stop_flag
.store(true, std::sync::atomic::Ordering::SeqCst);
}
pub fn is_connected(&self) -> bool {
self.state.read().unwrap().connected
}
pub fn last_connect_error(&self) -> Option<String> {
self.state.read().unwrap().last_connect_error.clone()
}
pub fn last_send_attempt(&self) -> Option<String> {
self.state.read().unwrap().last_send_attempt.clone()
}
pub fn last_send_success(&self) -> Option<String> {
self.state.read().unwrap().last_send_success.clone()
}
pub fn on_commands<F: Fn(Vec<Value>) + Send + Sync + 'static>(&self, callback: F) {
*self.on_commands.write().unwrap() = Some(Box::new(callback));
}
pub fn reconfigure(
&self,
base_url: &str,
customer: &str,
machine: &str,
token: Option<String>,
) {
let mut config = self.config.write().unwrap();
config.base_url = base_url.trim_end_matches('/').to_string();
config.customer = slugify(customer);
config.machine = slugify(machine);
config.token = token;
log::info!("Fleet Monitor reconfigured");
}
pub async fn send_heartbeat(&self) -> Result<(), String> {
let uptime = self
.start_time
.lock()
.unwrap()
.map(|t| t.elapsed().as_secs())
.unwrap_or(0);
let mut payload = serde_json::json!({
"ts": now_iso(),
"version": self.config.read().unwrap().version,
"uptime_seconds": uptime,
"pid": std::process::id(),
"ip_addresses": get_local_ips(),
});
{
let cfg = self.config.read().unwrap();
if let Some(ref g) = cfg.group {
payload["group"] = Value::String(g.clone());
}
if let Some(p) = cfg.group_priority {
payload["group_priority"] = Value::from(p);
}
if let Some(p) = cfg.sort_priority {
payload["sort_priority"] = Value::from(p);
}
if let Some(ref l) = cfg.location {
payload["location"] = Value::String(l.clone());
}
cfg.identity.apply_to(&mut payload);
}
if let Some(report) = self.licence.read().unwrap().clone() {
payload["licence"] = report;
}
if let Some(report) = self.hardware.read().unwrap().clone() {
payload["hardware"] = report;
}
let body = self.post_with_body("heartbeat", &payload).await?;
let channel = body
.as_ref()
.and_then(|b| b.get("channel"))
.and_then(|c| c.as_str())
.filter(|c| CHANNELS.contains(c))
.map(str::to_string);
*self.fleet_channel.write().unwrap() = channel;
Ok(())
}
pub async fn send_diagnostics(&self, diagnostics: &[(u16, String, u8)]) -> Result<(), String> {
let items: Vec<Value> = diagnostics
.iter()
.map(|(code, msg, sev)| {
serde_json::json!({
"code": code,
"message": msg,
"severity": sev,
})
})
.collect();
let payload = serde_json::json!({
"ts": now_iso(),
"items": items,
});
self.post("diagnostics", &payload).await
}
pub async fn send_status(&self, status: &str, message: Option<&str>) -> Result<(), String> {
let payload = serde_json::json!({
"ts": now_iso(),
"status": status,
"message": message,
});
self.post("status", &payload).await
}
pub async fn send_snapshot(
&self,
snapshot: &Value,
status: Option<&str>,
message: Option<&str>,
) -> Result<(), String> {
let mut payload = serde_json::json!({
"ts": now_iso(),
"snapshot": snapshot,
});
if let Some(s) = status {
payload["status"] = Value::String(s.to_string());
}
if let Some(m) = message {
payload["message"] = Value::String(m.to_string());
}
self.post("status", &payload).await
}
pub async fn send_command_ack(&self, acks: &[Value]) -> Result<(), String> {
let payload = serde_json::json!({
"ts": now_iso(),
"acks": acks,
});
self.post("command-ack", &payload).await
}
pub(crate) fn ingest_url(&self) -> String {
let config = self.config.read().unwrap();
format!(
"{}/api/ingest/{}/{}/{}",
config.base_url, config.customer, config.machine, config.software
)
}
async fn post(&self, msg_type: &str, payload: &Value) -> Result<(), String> {
self.post_with_body(msg_type, payload).await.map(|_| ())
}
async fn post_with_body(
&self,
msg_type: &str,
payload: &Value,
) -> Result<Option<Value>, String> {
let url = format!("{}/{}", self.ingest_url(), msg_type);
let token = self.config.read().unwrap().token.clone();
{
let mut state = self.state.write().unwrap();
state.last_send_attempt = Some(now_iso());
}
let mut req = self.http_client.post(&url).json(payload);
if let Some(ref t) = token {
req = req.bearer_auth(t);
}
match req.timeout(Duration::from_secs(10)).send().await {
Ok(resp) => {
let status_code = resp.status().as_u16();
let body = resp.json::<Value>().await.ok();
if (200..300).contains(&status_code) {
let mut state = self.state.write().unwrap();
state.last_send_success = Some(now_iso());
state.last_connect_error = None;
if !state.connected {
state.connected = true;
}
drop(state);
if let Some(ref body) = body {
if let Some(commands) =
body.get("commands").and_then(|c| c.as_array())
{
let cb = self.on_commands.read().unwrap();
if let Some(ref callback) = *cb {
callback(commands.clone());
}
}
}
Ok(body)
} else {
let err = format!("HTTP {}", status_code);
let mut state = self.state.write().unwrap();
state.last_connect_error = Some(err.clone());
if state.connected {
state.connected = false;
}
log::warn!("Ingest error: {}", err);
Err(err)
}
}
Err(e) => {
let err = e.to_string();
let mut state = self.state.write().unwrap();
state.last_connect_error = Some(err.clone());
if state.connected {
state.connected = false;
}
log::warn!("Ingest error: {}", err);
Err(err)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_config() -> FleetClientConfig {
FleetClientConfig {
base_url: "https://fleet.example.com".to_string(),
customer: "test-customer".to_string(),
machine: "test-machine".to_string(),
software: "test-software".to_string(),
token: Some("test-token".to_string()),
heartbeat_interval: Duration::from_secs(60),
version: Some("1.0.0".to_string()),
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
}
}
#[test]
fn test_slugify() {
assert_eq!(slugify("Hello World!"), "hello-world");
assert_eq!(slugify("test_software"), "test-software");
assert_eq!(slugify(" UPPER "), "upper");
assert_eq!(slugify("a--b"), "a--b");
}
#[test]
fn test_constructor_base_url() {
let config = test_config();
let client = FleetMonitorClient::new(config);
assert_eq!(
client.ingest_url(),
"https://fleet.example.com/api/ingest/test-customer/test-machine/test-software"
);
}
#[test]
fn test_constructor_legacy_broker() {
let config = FleetClientConfig::from_legacy(
"fleet.example.com",
Some(8883),
true,
"Customer A",
"Machine-1",
"my_software",
Some("token123".to_string()),
);
assert_eq!(config.base_url, "https://fleet.example.com:8883");
assert_eq!(config.customer, "customer-a");
assert_eq!(config.machine, "machine-1");
assert_eq!(config.software, "my-software");
}
#[test]
fn test_connection_state_tracking() {
let client = FleetMonitorClient::new(test_config());
assert!(!client.is_connected());
assert!(client.last_connect_error().is_none());
}
#[tokio::test]
async fn test_network_error_handling() {
let config = FleetClientConfig {
base_url: "https://127.0.0.1:1".to_string(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let result = client.send_status("running", None).await;
assert!(result.is_err());
assert!(!client.is_connected());
assert!(client.last_connect_error().is_some());
}
#[test]
fn test_reconfigure() {
let client = FleetMonitorClient::new(test_config());
client.reconfigure(
"https://new.example.com",
"new-customer",
"new-machine",
Some("new-token".to_string()),
);
assert_eq!(
client.ingest_url(),
"https://new.example.com/api/ingest/new-customer/new-machine/test-software"
);
}
#[tokio::test]
async fn test_send_heartbeat_with_mock() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path_regex(".*/heartbeat"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: Some("token".to_string()),
heartbeat_interval: Duration::from_secs(60),
version: Some("1.0.0".to_string()),
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
*client.start_time.lock().unwrap() = Some(Instant::now());
let result = client.send_heartbeat().await;
assert!(result.is_ok());
assert!(client.is_connected());
}
#[tokio::test]
async fn test_send_diagnostics_with_mock() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path_regex(".*/diagnostics"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let diags = vec![(100, "Test error".to_string(), 2u8)];
let result = client.send_diagnostics(&diags).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_send_status_with_mock() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path_regex(".*/status"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let result = client.send_status("running", Some("All OK")).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_send_snapshot_with_mock() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path_regex(".*/status"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let snapshot = serde_json::json!({"RunTimeTests": {"ok": true}});
let result = client
.send_snapshot(&snapshot, Some("running"), Some("All OK"))
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_bearer_token_header() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::header(
"Authorization",
"Bearer my-secret-token",
))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: Some("my-secret-token".to_string()),
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let result = client.send_status("running", None).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_http_error_handling() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(500))
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let result = client.send_status("running", None).await;
assert!(result.is_err());
assert!(!client.is_connected());
}
async fn channel_server(body: Value) -> wiremock::MockServer {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(body))
.mount(&mock_server)
.await;
mock_server
}
fn channel_client(base_url: String) -> FleetMonitorClient {
let mut config = test_config();
config.base_url = base_url;
FleetMonitorClient::new(config)
}
#[tokio::test]
async fn test_channel_from_heartbeat_response() {
let server = channel_server(serde_json::json!({"ok": true, "channel": "candidate"})).await;
let client = channel_client(server.uri());
assert_eq!(client.channel(), None);
client.set_build_channel(Some("nightly".to_string())).unwrap();
client.send_heartbeat().await.unwrap();
assert_eq!(
client.channel(),
Some(("candidate".to_string(), ChannelSource::Fleet))
);
}
#[tokio::test]
async fn test_channel_at_delivery_without_connection() {
let client = channel_client("http://127.0.0.1:1".to_string());
client.set_build_channel(Some("stable".to_string())).unwrap();
assert!(client.send_heartbeat().await.is_err());
assert_eq!(
client.channel(),
Some(("stable".to_string(), ChannelSource::Delivery))
);
}
#[tokio::test]
async fn test_channel_falls_back_while_offline_and_when_unnamed() {
let server = channel_server(serde_json::json!({"ok": true, "channel": "stable"})).await;
let client = channel_client(server.uri());
client.set_build_channel(Some("candidate".to_string())).unwrap();
client.send_heartbeat().await.unwrap();
client.reconfigure("http://127.0.0.1:1", "test", "test", None);
assert!(client.send_heartbeat().await.is_err());
assert_eq!(
client.channel(),
Some(("candidate".to_string(), ChannelSource::Delivery))
);
client.reconfigure(&server.uri(), "test", "test", None);
client.send_heartbeat().await.unwrap();
assert_eq!(
client.channel(),
Some(("stable".to_string(), ChannelSource::Fleet))
);
let silent = channel_server(serde_json::json!({"ok": true})).await;
client.reconfigure(&silent.uri(), "test", "test", None);
client.send_heartbeat().await.unwrap();
assert_eq!(
client.channel(),
Some(("candidate".to_string(), ChannelSource::Delivery))
);
}
#[tokio::test]
async fn test_channel_ignores_unknown_value_and_other_messages() {
let server = channel_server(serde_json::json!({"ok": true, "channel": "beta"})).await;
let client = channel_client(server.uri());
client.send_heartbeat().await.unwrap();
assert_eq!(client.channel(), None);
let stable = channel_server(serde_json::json!({"ok": true, "channel": "stable"})).await;
client.reconfigure(&stable.uri(), "test", "test", None);
client.send_status("running", None).await.unwrap();
assert_eq!(client.channel(), None);
}
#[test]
fn test_build_channel_refuses_unknown_value() {
let client = channel_client("http://127.0.0.1:1".to_string());
assert!(client.set_build_channel(Some("beta".to_string())).is_err());
assert_eq!(client.channel(), None);
}
#[tokio::test]
async fn test_on_commands_callback() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
"commands": [{"id": "cmd-1", "action": "restart"}]
})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "test".to_string(),
machine: "test".to_string(),
software: "test".to_string(),
token: None,
heartbeat_interval: Duration::from_secs(60),
version: None,
group: None,
group_priority: None,
sort_priority: None,
location: None,
identity: DeviceIdentity::default(),
};
let client = FleetMonitorClient::new(config);
let received = Arc::new(Mutex::new(Vec::new()));
let received_clone = received.clone();
client.on_commands(move |cmds| {
received_clone.lock().unwrap().extend(cmds);
});
let _ = client.send_status("running", None).await;
let cmds = received.lock().unwrap();
assert_eq!(cmds.len(), 1);
assert_eq!(cmds[0]["id"], "cmd-1");
}
#[test]
fn test_start_stop_lifecycle() {
let client = FleetMonitorClient::new(test_config());
client.start();
assert!(client.start_time.lock().unwrap().is_some());
client.stop();
assert!(
client
.stop_flag
.load(std::sync::atomic::Ordering::SeqCst)
);
}
#[tokio::test]
async fn test_heartbeat_includes_hierarchy_when_set() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "c".to_string(),
machine: "m".to_string(),
software: "s".to_string(),
group: Some("hall-3".to_string()),
group_priority: Some(5),
sort_priority: Some(2),
location: Some("Halle 1".to_string()),
identity: DeviceIdentity::default(),
..Default::default()
};
let client = FleetMonitorClient::new(config);
*client.start_time.lock().unwrap() = Some(Instant::now());
client.send_heartbeat().await.unwrap();
let reqs = mock_server.received_requests().await.unwrap();
let body: Value = serde_json::from_slice(&reqs[0].body).unwrap();
assert_eq!(body["group"], "hall-3");
assert_eq!(body["group_priority"], 5);
assert_eq!(body["sort_priority"], 2);
assert_eq!(body["location"], "Halle 1");
}
#[tokio::test]
async fn test_heartbeat_omits_hierarchy_when_unset() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "c".to_string(),
machine: "m".to_string(),
software: "s".to_string(),
..Default::default()
};
let client = FleetMonitorClient::new(config);
*client.start_time.lock().unwrap() = Some(Instant::now());
client.send_heartbeat().await.unwrap();
let reqs = mock_server.received_requests().await.unwrap();
let body: Value = serde_json::from_slice(&reqs[0].body).unwrap();
assert!(body.get("group").is_none());
assert!(body.get("group_priority").is_none());
assert!(body.get("sort_priority").is_none());
assert!(body.get("location").is_none());
assert!(body.get("serial").is_none());
assert!(body.get("branding").is_none());
assert!(body.get("initial_password_changed").is_none());
}
#[tokio::test]
async fn test_heartbeat_includes_device_identity_when_set() {
let mock_server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
)
.mount(&mock_server)
.await;
let config = FleetClientConfig {
base_url: mock_server.uri(),
customer: "c".to_string(),
machine: "sn00100".to_string(),
software: "s".to_string(),
identity: DeviceIdentity {
serial: Some("SN00100".to_string()),
display_name: Some("Drehmaschine 1".to_string()),
inventory_no: Some("INV-4711".to_string()),
stream: Some("brinkhaus".to_string()),
branding: None,
initial_password_scheme: Some("hmac-sn-v1".to_string()),
initial_password_changed: Some(false),
},
..Default::default()
};
let client = FleetMonitorClient::new(config);
client.set_branding(Some("uttec".to_string()));
*client.start_time.lock().unwrap() = Some(Instant::now());
client.send_heartbeat().await.unwrap();
let reqs = mock_server.received_requests().await.unwrap();
let body: Value = serde_json::from_slice(&reqs[0].body).unwrap();
assert_eq!(body["serial"], "SN00100");
assert_eq!(body["display_name"], "Drehmaschine 1");
assert_eq!(body["inventory_no"], "INV-4711");
assert_eq!(body["stream"], "brinkhaus");
assert_eq!(body["branding"], "uttec");
assert_eq!(body["initial_password_scheme"], "hmac-sn-v1");
assert_eq!(body["initial_password_changed"], false);
}
}