use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::fs;
use std::time::{Duration, Instant};
use super::*;
use crate::store::cluster::network::Hello;
const OLD: Version = Version(0, 110, 0);
const NEW: Version = Version(0, 111, 0);
#[derive(Default)]
struct Fake {
sessions: Cell<usize>,
results: RefCell<VecDeque<Result<Version, UpgradeError>>>,
calls: RefCell<Vec<String>>,
}
impl Host for Fake {
async fn live_sessions(&self) -> usize {
self.sessions.get()
}
async fn upgrade(&self, target: Version) -> Result<Version, UpgradeError> {
self.calls.borrow_mut().push(format!("upgrade {target}"));
self.results.borrow_mut().pop_front().unwrap_or(Ok(target))
}
async fn restart(&self) -> anyhow::Result<()> {
self.calls.borrow_mut().push("restart".into());
Ok(())
}
}
fn calls(u: &Upgrader<Fake>) -> Vec<String> {
u.host().calls.borrow().clone()
}
fn versions(mine: Version, peer: Version, on: bool) -> Versions {
let v = Versions::new(Some(mine)).with_auto_upgrade(on);
v.saw_peer(peer);
v
}
fn peer(id: NodeId, version: Version) -> Peer {
Peer {
id,
voter: true,
reachable: true,
version: Some(version),
auto_upgrade: true,
}
}
fn view(id: NodeId, v: &Versions, peers: Vec<Peer>) -> View {
View {
id,
voter: true,
mine: v.mine().unwrap(),
target: v.target(),
auto_upgrade: v.auto_upgrade(),
peers,
}
}
#[tokio::test]
async fn with_the_setting_off_an_outdated_node_never_upgrades() {
let v = versions(OLD, NEW, false);
let mut u = Upgrader::new(Fake::default());
let step = u
.step(&view(2, &v, vec![peer(1, NEW)]), &v, Instant::now())
.await;
assert_eq!(step, Step::Waited(Wait::Off));
assert!(calls(&u).is_empty());
}
#[tokio::test]
async fn with_no_sessions_it_upgrades_to_the_target_then_restarts() {
let v = versions(OLD, NEW, true);
let mut u = Upgrader::new(Fake::default());
let step = u
.step(&view(2, &v, vec![peer(1, NEW)]), &v, Instant::now())
.await;
assert_eq!(step, Step::Restarted);
assert_eq!(calls(&u), ["upgrade 0.111.0", "restart"]);
assert_eq!(v.upgrade_error(), None);
}
#[tokio::test]
async fn a_live_session_holds_the_upgrade_until_it_ends() {
let v = versions(OLD, NEW, true);
let mut u = Upgrader::new(Fake::default());
u.host().sessions.set(1);
let w = view(2, &v, vec![peer(1, NEW)]);
assert_eq!(
u.step(&w, &v, Instant::now()).await,
Step::Waited(Wait::Sessions(1))
);
assert!(calls(&u).is_empty());
u.host().sessions.set(0);
assert_eq!(u.step(&w, &v, Instant::now()).await, Step::Restarted);
assert_eq!(calls(&u), ["upgrade 0.111.0", "restart"]);
}
#[tokio::test]
async fn a_node_at_or_above_the_target_never_upgrades() {
let mut u = Upgrader::new(Fake::default());
for (mine, peer_version) in [(NEW, NEW), (NEW, OLD)] {
let v = versions(mine, peer_version, true);
assert_eq!(v.target(), None);
let step = u
.step(
&view(2, &v, vec![peer(1, peer_version)]),
&v,
Instant::now(),
)
.await;
assert_eq!(step, Step::Waited(Wait::Current));
}
assert!(calls(&u).is_empty());
}
#[tokio::test]
async fn of_two_outdated_nodes_the_lower_id_goes_first() {
let v = versions(OLD, NEW, true);
let leader = peer(3, NEW);
let mut low = Upgrader::new(Fake::default());
let mut high = Upgrader::new(Fake::default());
let now = Instant::now();
let high_view = view(2, &v, vec![peer(1, OLD), leader.clone()]);
assert_eq!(
high.step(&high_view, &v, now).await,
Step::Waited(Wait::Behind(1))
);
let low_view = view(1, &v, vec![peer(2, OLD), leader.clone()]);
assert_eq!(low.step(&low_view, &v, now).await, Step::Restarted);
assert!(calls(&high).is_empty());
let after = view(2, &v, vec![peer(1, NEW), leader]);
assert_eq!(high.step(&after, &v, now).await, Step::Restarted);
}
#[tokio::test]
async fn a_lower_node_that_does_not_upgrade_itself_does_not_hold_the_others() {
let v = versions(OLD, NEW, true);
let manual = Peer {
auto_upgrade: false,
..peer(1, OLD)
};
let mut u = Upgrader::new(Fake::default());
let step = u
.step(&view(2, &v, vec![manual, peer(3, NEW)]), &v, Instant::now())
.await;
assert_eq!(step, Step::Restarted);
}
#[tokio::test]
async fn a_voter_waits_while_another_voter_is_unreachable() {
let v = versions(OLD, NEW, true);
let down = Peer {
reachable: false,
version: None,
..peer(3, NEW)
};
let mut u = Upgrader::new(Fake::default());
let step = u
.step(
&view(2, &v, vec![peer(1, NEW), down.clone()]),
&v,
Instant::now(),
)
.await;
assert_eq!(step, Step::Waited(Wait::VoterUnreachable(3)));
assert!(calls(&u).is_empty());
let learner = View {
voter: false,
..view(2, &v, vec![peer(1, NEW), down])
};
assert_eq!(u.step(&learner, &v, Instant::now()).await, Step::Restarted);
}
#[test]
fn a_malformed_version_from_a_peer_is_rejected() {
for bad in [
"1.2",
"1.2.3.4",
"a.b.c",
"1.2.3;touch x",
"1.2.3 && rm -r ~",
"",
] {
assert!(bad.parse::<Version>().is_err(), "{bad:?} parsed");
}
let hello = serde_json::json!({
"name": "peer",
"id": 7,
"witness": false,
"version": "1.2.3;touch x",
});
assert!(serde_json::from_value::<Hello>(hello).is_err());
let v = Versions::new(Some(OLD));
if let Ok(parsed) = "9.9.9$(id)".parse::<Version>() {
v.saw_peer(parsed);
}
assert_eq!(v.highest_peer(), None);
let target: Version = "v0.111.0-rc1".parse().unwrap();
let args = binstall_args(Path::new("/bin"), target);
assert_eq!(args.last().unwrap(), "orch-cli@0.111.0");
}
#[tokio::test]
async fn a_failed_upgrade_shows_its_error_and_retries_later() {
let v = versions(OLD, NEW, true);
let mut u = Upgrader::new(Fake::default());
u.host()
.results
.borrow_mut()
.push_back(Err(UpgradeError::Failed("crates.io has no 0.111.0".into())));
let w = view(2, &v, vec![peer(1, NEW)]);
let now = Instant::now();
assert_eq!(u.step(&w, &v, now).await, Step::Failed);
assert_eq!(
v.upgrade_error().as_deref(),
Some("crates.io has no 0.111.0")
);
let soon = now + Duration::from_secs(60);
assert_eq!(u.step(&w, &v, soon).await, Step::Waited(Wait::Backoff));
assert_eq!(calls(&u), ["upgrade 0.111.0"]);
let later = now + FIRST_RETRY;
assert_eq!(u.step(&w, &v, later).await, Step::Restarted);
assert_eq!(calls(&u), ["upgrade 0.111.0", "upgrade 0.111.0", "restart"]);
assert_eq!(v.upgrade_error(), None);
}
#[tokio::test]
async fn an_upgrade_that_installs_nothing_newer_counts_as_failed() {
let v = versions(OLD, NEW, true);
let mut u = Upgrader::new(Fake::default());
u.host().results.borrow_mut().push_back(Ok(OLD));
let step = u
.step(&view(2, &v, vec![peer(1, NEW)]), &v, Instant::now())
.await;
assert_eq!(step, Step::Failed);
assert_eq!(calls(&u), ["upgrade 0.111.0"]);
assert!(v.upgrade_error().unwrap().contains("not newer"));
}
#[tokio::test]
async fn an_install_orch_cannot_upgrade_stays_in_needs_upgrade() {
let v = versions(OLD, NEW, true);
let mut u = Upgrader::new(Fake::default());
let unsupported = UpgradeError::Unsupported("no cargo-binstall".into());
u.host()
.results
.borrow_mut()
.extend([Err(unsupported.clone()), Err(unsupported)]);
let w = view(2, &v, vec![peer(1, NEW)]);
for _ in 0..2 {
assert_eq!(
u.step(&w, &v, Instant::now()).await,
Step::Waited(Wait::Unsupported)
);
}
assert!(!calls(&u).contains(&"restart".to_string()));
assert_eq!(v.upgrade_error().as_deref(), Some("no cargo-binstall"));
}
#[test]
fn retry_delay_grows_and_stops_at_the_cap() {
assert_eq!(retry_delay(1), FIRST_RETRY);
assert_eq!(retry_delay(2), FIRST_RETRY * 2);
assert_eq!(retry_delay(40), MAX_RETRY);
}
#[test]
fn detect_reads_the_install_from_the_binary_path() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let keg = root.join("brew/Cellar/orch/0.110.0/bin");
fs::create_dir_all(&keg).unwrap();
fs::write(keg.join("orch"), "").unwrap();
assert_eq!(
detect(&keg.join("orch"), None, None),
Install::Brew {
brew: root.join("brew/bin/brew"),
orch: root.join("brew/opt/orch/bin/orch"),
}
);
let home = root.join("home");
let bin = home.join(".cargo/bin");
fs::create_dir_all(&bin).unwrap();
fs::write(bin.join("orch"), "").unwrap();
assert_eq!(
detect(&bin.join("orch"), None, Some(&home)),
Install::Cargo {
dir: bin.clone(),
binstall: None,
}
);
fs::write(bin.join("cargo-binstall"), "").unwrap();
assert_eq!(
detect(&bin.join("orch"), None, Some(&home)),
Install::Cargo {
dir: bin.clone(),
binstall: Some(bin.join("cargo-binstall")),
}
);
let cargo_home = root.join("cargo");
fs::create_dir_all(cargo_home.join("bin")).unwrap();
fs::write(cargo_home.join("bin/orch"), "").unwrap();
assert_eq!(
detect(&cargo_home.join("bin/orch"), Some(&cargo_home), Some(&home)),
Install::Cargo {
dir: cargo_home.join("bin"),
binstall: Some(bin.join("cargo-binstall")),
}
);
let other = root.join("usr/local/bin");
fs::create_dir_all(&other).unwrap();
fs::write(other.join("orch"), "").unwrap();
assert_eq!(
detect(&other.join("orch"), Some(&cargo_home), Some(&home)),
Install::Other(other.join("orch"))
);
}