use std::{num::NonZeroU32, path::PathBuf, sync::Mutex, time::Duration};
use base64::Engine as _;
use futures_util::FutureExt as _;
use pretty_assertions::assert_eq;
use rho_protocol::{HostStreamEnd, HostStreamReadParams};
use tokio::sync::mpsc;
use super::*;
use crate::{
daemon::Ending,
update::{Lookups, UpdateInfo},
};
enum Step {
Say(String),
End(anyhow::Result<Unattended>),
Panic,
}
struct Driven {
steps: Mutex<Option<mpsc::UnboundedReceiver<Step>>>,
replaced: Mutex<Option<Option<String>>>,
}
impl Install for Driven {
fn install<'a>(
&'a self,
_: ClientEnvironment,
replaced: Option<String>,
progress: &'a mut Progress,
) -> impl Future<Output = anyhow::Result<Unattended>> + Send + 'a {
*self.replaced.lock().unwrap() = Some(replaced);
let steps = self.steps.lock().unwrap().take();
async move {
let mut steps = steps.expect("the test drives one update");
while let Some(step) = steps.recv().await {
match step {
Step::Say(text) => text.lines().for_each(|line| progress.say(line)),
Step::End(done) => return done,
Step::Panic => panic!("the stand-in installer broke"),
}
}
anyhow::bail!("the test stopped driving the update")
}
}
}
struct Driving {
updates: Updates<Driven>,
steps: mpsc::UnboundedSender<Step>,
shutdown: Shutdown,
}
fn driving(in_progress: u64, replaced: Option<&str>) -> Driving {
let (steps, driven) = mpsc::unbounded_channel();
let shutdown = Shutdown::default();
let replaced = replaced.map(str::to_owned);
let daemon = Daemon {
in_progress: Arc::new(move || in_progress),
replaced: Arc::new(move || replaced.clone()),
shutdown: shutdown.clone(),
};
let install = Driven {
steps: Mutex::new(Some(driven)),
replaced: Mutex::default(),
};
Driving {
updates: Updates::new(install, daemon),
steps,
shutdown,
}
}
impl Driving {
fn send(&self, step: Step) {
self.steps.send(step).unwrap();
}
}
fn caller(connection: u64, name: &str) -> Caller {
Caller::new(
ConnectionId::new(connection),
ClientInfo {
name: name.to_owned(),
version: "0.4.0".to_owned(),
},
)
}
fn start(updates: &Updates<Driven>, caller: &Caller, restart: UpdateRestart) -> HostStreamId {
updates
.start(
caller.clone(),
DaemonUpdateParams::new(restart),
ClientEnvironment::default(),
)
.unwrap()
.progress
}
fn result_of(progress: &HostStreamId) -> DaemonUpdateResultParams {
DaemonUpdateResultParams::new(progress.clone())
}
fn installed(lands: Lands) -> Unattended {
Unattended::Installed {
to: "3.11.0".to_owned(),
method: InstallMethod::Script,
lands,
}
}
async fn read_to_end(
caller: &Caller,
progress: &HostStreamId,
offset: u64,
) -> (String, HostStreamEnd) {
let mut offset = offset;
let mut bytes = Vec::new();
loop {
let read = caller
.read_stream(HostStreamReadParams::new(
progress.clone(),
offset,
NonZeroU32::MAX,
))
.await
.unwrap();
let data = base64::engine::general_purpose::STANDARD
.decode(read.data)
.unwrap();
offset += data.len() as u64;
bytes.extend(data);
if let Some(end) = read.end {
return (String::from_utf8(bytes).unwrap(), end);
}
}
}
#[tokio::test]
async fn progress_streams_while_the_update_runs() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
let said = "downloading rho 3.11.0\n";
driving.send(Step::Say(said.to_owned()));
let read = asking
.read_stream(HostStreamReadParams::new(
progress.clone(),
0,
NonZeroU32::MAX,
))
.await
.unwrap();
let data = base64::engine::general_purpose::STANDARD
.decode(&read.data)
.unwrap();
driving.send(Step::End(Ok(Unattended::UpToDate)));
let answer = driving
.updates
.result(&asking, result_of(&progress))
.await
.unwrap();
assert_eq!(
(String::from_utf8(data).unwrap(), read.end),
(said.to_owned(), None)
);
assert_eq!(answer.outcome, UpdateOutcome::UpToDate);
assert_eq!(
read_to_end(&asking, &progress, said.len() as u64).await,
(String::new(), HostStreamEnd::Done)
);
}
#[tokio::test]
async fn a_second_update_meanwhile_is_refused_with_who_asked() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
let again = || {
driving
.updates
.start(
caller(2, "rho-cli"),
DaemonUpdateParams::new(UpdateRestart::Now),
ClientEnvironment::default(),
)
.unwrap_err()
};
let running = again();
driving.send(Step::End(Ok(Unattended::UpToDate)));
read_to_end(&asking, &progress, 0).await;
let over = again();
assert_eq!(
[(running.code, running.message), (over.code, over.message)],
[
(
ErrorCode::HostCallFailed.code(),
"an update is already running, asked for by rho-ui 0.4.0".to_owned()
),
(
ErrorCode::HostCallFailed.code(),
"an update is over and waits for its result, asked for by rho-ui 0.4.0".to_owned()
),
]
);
}
#[tokio::test]
async fn the_replacement_the_watch_probed_reaches_the_update() {
let driving = driving(0, Some("3.11.0"));
start(&driving.updates, &caller(1, "rho-ui"), UpdateRestart::Now);
driving.send(Step::End(Ok(Unattended::UpToDate)));
driving.steps.closed().await;
assert_eq!(
*driving.updates.install.replaced.lock().unwrap(),
Some(Some("3.11.0".to_owned()))
);
}
#[test]
fn the_move_follows_where_rho_landed_and_the_restart_asked() {
let at = PathBuf::from("/home/me/.local/share/mise/installs/rho/3.11.0/bin/rho");
let named = || HostPath::new(at.to_str().unwrap());
let another = || Lands::AtAnotherPath(at.clone());
let cases = [
(
Lands::AtItsPath,
UpdateRestart::Now,
2,
UpdateRestarting::Now,
Follow::RestartNow,
),
(
Lands::AtItsPath,
UpdateRestart::WhenIdle,
2,
UpdateRestarting::when_idle(2),
Follow::Watch,
),
(
Lands::AtItsPath,
UpdateRestart::WhenIdle,
0,
UpdateRestarting::when_idle(0),
Follow::Watch,
),
(
another(),
UpdateRestart::Now,
2,
UpdateRestarting::replaced(named(), None),
Follow::Replace { once_idle: false },
),
(
another(),
UpdateRestart::WhenIdle,
2,
UpdateRestarting::replaced(named(), Some(2)),
Follow::Replace { once_idle: true },
),
(
another(),
UpdateRestart::WhenIdle,
0,
UpdateRestarting::replaced(named(), None),
Follow::Replace { once_idle: true },
),
];
for (lands, restart, in_progress, restarting, follow) in cases {
let case = format!("{lands:?} {restart:?} {in_progress}");
assert_eq!(
next_move(lands, restart, in_progress),
(restarting, follow),
"{case}"
);
}
}
#[tokio::test]
async fn the_result_waits_for_the_update_and_holds_the_watch_until_then() {
let cases = [
(Unattended::UpToDate, UpdateOutcome::UpToDate, Follow::Watch),
(
Unattended::NeedsTerminal {
latest: "3.11.0".to_owned(),
command: "sudo pacman -Sy rho-coding-agent".to_owned(),
},
UpdateOutcome::needs_terminal("3.11.0", "sudo pacman -Sy rho-coding-agent"),
Follow::Watch,
),
(
installed(Lands::AtItsPath),
UpdateOutcome::installed("3.11.0", UpdateMethod::Script, UpdateRestarting::Now),
Follow::RestartNow,
),
];
for (done, outcome, follow) in cases {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
let mut result = std::pin::pin!(driving.updates.result(&asking, result_of(&progress)));
let waited = result.as_mut().now_or_never().is_none();
let held = driving.updates.follow();
driving.send(Step::End(Ok(done)));
let answer = result.await.unwrap();
assert_eq!(
(waited, held, answer.outcome, driving.updates.follow()),
(true, Follow::Held, outcome.clone(), follow),
"{outcome:?}"
);
}
}
#[tokio::test]
async fn a_failed_update_answers_why_with_the_end_of_its_output() {
let why = "install script update command exited with exit status: 1";
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
let output: String = (1..=100)
.map(|n| format!("line {n:03} {}\n", "x".repeat(40)))
.collect();
driving.send(Step::Say(output.clone()));
driving.send(Step::End(Err(anyhow::anyhow!(why))));
let error = driving
.updates
.result(&asking, result_of(&progress))
.await
.unwrap_err();
let kept = output[output.len() - 4096..].trim();
assert_eq!(
(error.code, error.message),
(
ErrorCode::HostCallFailed.code(),
format!(
"could not update rho: {why}\nthe end of its output, at most 4096 bytes:\n…{kept}"
)
)
);
assert_eq!(driving.updates.follow(), Follow::Watch);
assert_eq!(
read_to_end(&asking, &progress, 0).await,
(output, HostStreamEnd::failed(why))
);
}
#[tokio::test]
async fn a_stopping_daemon_starts_no_update_and_answers_results_so() {
let (running, over) = (driving(0, None), driving(0, None));
let (waits, asks) = (caller(1, "rho-ui"), caller(2, "rho-ui"));
let progress = start(&running.updates, &waits, UpdateRestart::Now);
let finished = start(&over.updates, &asks, UpdateRestart::Now);
over.send(Step::End(Ok(installed(Lands::AtItsPath))));
read_to_end(&asks, &finished, 0).await;
let mut waiting = std::pin::pin!(running.updates.result(&waits, result_of(&progress)));
assert!(waiting.as_mut().now_or_never().is_none());
running.shutdown.request(Ending::Stop, |_| {});
over.shutdown.request(Ending::Stop, |_| {});
let waited = waiting.await.unwrap_err();
let asked = over
.updates
.result(&asks, result_of(&finished))
.await
.unwrap_err();
let refused = running
.updates
.start(
caller(3, "rho-ui"),
DaemonUpdateParams::new(UpdateRestart::Now),
ClientEnvironment::default(),
)
.unwrap_err();
let stopping = |does: &str| {
(
ErrorCode::HostCallFailed.code(),
format!("the daemon is stopping, so it {does}; ask again once it runs"),
)
};
assert_eq!(
[
(waited.code, waited.message),
(asked.code, asked.message),
(refused.code, refused.message)
],
[
stopping("will not answer the update"),
stopping("will not answer the update"),
stopping("updates nothing"),
]
);
}
#[tokio::test]
async fn no_update_starts_once_the_watch_committed_to_a_move() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
let mut claims = 0;
let held = driving.updates.commit(Follow::Held, || {
claims += 1;
true
});
let while_running = driving.updates.commit(Follow::Watch, || {
claims += 1;
true
});
driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
driving
.updates
.result(&asking, result_of(&progress))
.await
.unwrap();
let stale = driving.updates.commit(Follow::Watch, || {
claims += 1;
true
});
let committed = driving.updates.commit(Follow::RestartNow, || {
claims += 1;
true
});
let refused = driving
.updates
.start(
caller(2, "rho-ui"),
DaemonUpdateParams::new(UpdateRestart::Now),
ClientEnvironment::default(),
)
.unwrap_err();
assert_eq!(
(held, while_running, stale, committed, claims),
(false, false, false, true, 1)
);
assert_eq!(
(refused.code, refused.message.as_str()),
(
ErrorCode::HostCallFailed.code(),
"the daemon is moving onto a new rho, so it starts no update; ask again once it runs"
)
);
}
#[tokio::test]
async fn an_update_whose_task_panics_answers_and_lets_go() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
let mut result = std::pin::pin!(driving.updates.result(&asking, result_of(&progress)));
assert!(result.as_mut().now_or_never().is_none());
driving.send(Step::Panic);
let error = result.await.unwrap_err();
assert_eq!(
(error.code, error.message.as_str()),
(
ErrorCode::HostCallFailed.code(),
"could not update rho: the update stopped unexpectedly"
)
);
assert_eq!(driving.updates.follow(), Follow::Watch);
}
#[tokio::test]
async fn the_daemon_moves_only_once_the_result_is_answered() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
let ended = read_to_end(&asking, &progress, 0).await;
let before = driving.updates.follow();
driving
.updates
.result(&asking, result_of(&progress))
.await
.unwrap();
assert_eq!(ended, (String::new(), HostStreamEnd::Done));
assert_eq!(
(before, driving.updates.follow()),
(Follow::Held, Follow::RestartNow)
);
}
#[tokio::test(start_paused = true)]
async fn the_daemon_moves_once_the_asking_connection_leaves() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
start(&driving.updates, &asking, UpdateRestart::Now);
drop(asking);
driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
tokio::time::sleep(Duration::from_secs(1)).await;
assert_eq!(driving.updates.follow(), Follow::RestartNow);
}
#[tokio::test(start_paused = true)]
async fn an_unasked_result_settles_after_the_grace() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::Now);
driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
tokio::time::sleep(UNASKED_RESULT_GRACE - Duration::from_secs(1)).await;
let within = driving.updates.follow();
tokio::time::sleep(Duration::from_secs(2)).await;
let after = driving.updates.follow();
let late = driving
.updates
.result(&asking, result_of(&progress))
.await
.unwrap_err();
assert_eq!((within, after), (Follow::Held, Follow::RestartNow));
assert_eq!(late.code, ErrorCode::InvalidParams.code());
}
#[tokio::test(start_paused = true)]
async fn unread_progress_past_the_buffer_ends_truncated_without_holding_the_update() {
let driving = driving(0, None);
let asking = caller(1, "rho-ui");
let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
let lines = vec!["x".repeat(1023); 1100].join("\n");
driving.send(Step::Say(lines));
driving.send(Step::End(Ok(Unattended::UpToDate)));
let answer = tokio::time::timeout(
Duration::from_secs(60),
driving.updates.result(&asking, result_of(&progress)),
)
.await
.expect("the update finishes while nobody reads its progress")
.unwrap();
let (text, end) = read_to_end(&asking, &progress, 0).await;
assert_eq!(answer.outcome, UpdateOutcome::UpToDate);
assert_eq!((text.len(), end), (1 << 20, HostStreamEnd::Truncated));
}
#[test]
fn a_check_answers_as_rho_update_check_json() {
let report = |current: &str, method| {
let update = UpdateInfo {
latest_tag: "rho-coding-agent-v3.12.0".to_owned(),
latest_version: "3.12.0".to_owned(),
current_version: current.to_owned(),
};
let lookups = Lookups::Found {
cargo_root: None,
mise_tool: Err("not looked up".to_owned()),
};
UpdateCheck::new(update, method, &lookups).expect("the command needs no lookup")
};
let cases = [
("3.12.0", InstallMethod::Script),
("3.11.0", InstallMethod::Script),
("3.11.0", InstallMethod::Pacman),
];
for (current, method) in cases {
let check = report(current, method);
let mut printed = serde_json::to_value(&check).expect("it serializes");
printed
.as_object_mut()
.expect("an object")
.retain(|_, value| !value.is_null());
assert_eq!(
serde_json::to_value(DaemonUpdateCheck::from(check)).expect("it serializes"),
printed,
"{current} {method:?}"
);
}
let failed = check_failed(anyhow::anyhow!("offline"));
assert_eq!(failed.error_code(), Some(ErrorCode::HostCallFailed));
}