use super::{apply_desired, load};
use crate::sandbox::HostResources;
use serde_json::Value;
use std::path::Path;
pub fn payload(home: &Path) -> Option<Value> {
match load(home) {
Ok(p) => Some(p.to_hub_json()),
Err(e) => {
eprintln!(" [POLICY] not reporting a policy to the hub: {e}");
None
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Applied {
None,
Ignored,
Saved(u64),
Refused(String),
}
pub fn apply_reply(home: &Path, body: &str, host: &HostResources) -> Applied {
let Some(v) = serde_json::from_str::<Value>(body).ok() else {
return Applied::None;
};
let Some(desired) = v.get("policy").filter(|p| p.is_object()) else {
return Applied::None;
};
match apply_desired(home, desired, host) {
Ok(None) => Applied::Ignored,
Ok(Some(p)) => Applied::Saved(p.revision),
Err(e) => Applied::Refused(e),
}
}
pub fn apply_reply_logged(home: &Path, body: &str) {
match apply_reply(home, body, &HostResources::detect()) {
Applied::Saved(rev) => {
println!(" [POLICY] applied the policy staged on the hub (revision {rev})")
}
Applied::Refused(e) => {
eprintln!(" [POLICY] ignoring the policy staged on the hub: {e}")
}
Applied::None | Applied::Ignored => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::policy::{test_home, MinPrice};
fn host() -> HostResources {
HostResources {
logical_cpus: 8,
memory_bytes: Some(16 << 30),
}
}
#[test]
fn the_payload_is_the_hub_object_with_the_revision() {
let home = test_home();
let v = payload(&home).unwrap();
assert_eq!(v["revision"], 1);
assert_eq!(v["sharing"]["squads"], serde_json::json!(["public"]));
}
#[test]
fn an_unreadable_policy_is_left_out_of_the_payload() {
let home = test_home();
std::fs::write(crate::policy::path(&home), "version = [").unwrap();
assert!(payload(&home).is_none());
}
#[test]
fn a_higher_staged_revision_is_applied_and_reported_back_on_the_next_register() {
let home = test_home();
load(&home).unwrap();
let body = r#"{"default_placement": null,
"policy": {"revision": 4, "sharing": {"min_price": 3.0}, "workloads": {"spaces": false}}}"#;
assert_eq!(apply_reply(&home, body, &host()), Applied::Saved(4));
let p = load(&home).unwrap();
assert_eq!(p.sharing.min_price, MinPrice::PerHour(3.0));
assert!(!p.workloads.spaces);
assert_eq!(payload(&home).unwrap()["revision"], 4);
assert_eq!(payload(&home).unwrap()["workloads"]["spaces"], false);
}
#[test]
fn an_equal_or_lower_revision_and_a_missing_policy_change_nothing() {
let home = test_home();
crate::policy::update(&home, None, None, |p| {
p.sharing.when = "always".into();
Ok(())
})
.unwrap(); for rev in [1, 2] {
let body =
format!(r#"{{"policy": {{"revision": {rev}, "sharing": {{"when": "idle"}}}}}}"#);
assert_eq!(apply_reply(&home, &body, &host()), Applied::Ignored);
}
assert_eq!(load(&home).unwrap().sharing.when, "always");
assert_eq!(
apply_reply(&home, r#"{"policy": null}"#, &host()),
Applied::None
);
assert_eq!(apply_reply(&home, "not json", &host()), Applied::None);
assert_eq!(apply_reply(&home, "{}", &host()), Applied::None);
}
#[test]
fn a_staged_policy_the_hardware_cannot_give_is_refused_and_the_local_one_kept() {
let home = test_home();
let before = load(&home).unwrap();
let body = r#"{"policy": {"revision": 9, "budget": {"cpu": "64"}}}"#;
match apply_reply(&home, body, &host()) {
Applied::Refused(e) => assert!(e.contains("budget.cpu"), "{e}"),
other => panic!("{other:?}"),
}
assert_eq!(load(&home).unwrap(), before);
}
}