Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/api/computers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,60 @@ impl SteelClient {
.await
}

pub async fn stop_computer(
&self,
base_url: &str,
mode: ApiMode,
auth: &Auth,
id: &str,
) -> Result<Value, ApiError> {
self.request(
base_url,
mode,
reqwest::Method::POST,
&format!("{}/stop", computer_path(id)),
None,
auth,
)
.await
}

pub async fn start_computer(
&self,
base_url: &str,
mode: ApiMode,
auth: &Auth,
id: &str,
) -> Result<Value, ApiError> {
self.request(
base_url,
mode,
reqwest::Method::POST,
&format!("{}/start", computer_path(id)),
None,
auth,
)
.await
}

pub async fn restart_computer(
&self,
base_url: &str,
mode: ApiMode,
auth: &Auth,
id: &str,
) -> Result<Value, ApiError> {
self.request(
base_url,
mode,
reqwest::Method::POST,
&format!("{}/restart", computer_path(id)),
None,
auth,
)
.await
}

pub async fn exec_computer(
&self,
base_url: &str,
Expand Down
73 changes: 69 additions & 4 deletions src/commands/computer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,16 @@ pub enum Command {
Pause(IdArgs),

/// Resume a paused computer
Resume(ResumeArgs),
Resume(LifecycleArgs),

/// Stop a computer but keep its disk
Stop(LifecycleArgs),

/// Start a stopped computer
Start(LifecycleArgs),

/// Reboot a running computer
Restart(LifecycleArgs),

/// Remember a computer as the default for other commands
Use(UseArgs),
Expand All @@ -63,6 +72,9 @@ impl Command {
Self::Delete(_) => "delete",
Self::Pause(_) => "pause",
Self::Resume(_) => "resume",
Self::Stop(_) => "stop",
Self::Start(_) => "start",
Self::Restart(_) => "restart",
Self::Use(_) => "use",
Self::Exec(_) => "exec",
Self::Ssh(_) => "ssh",
Expand Down Expand Up @@ -110,11 +122,11 @@ pub struct IdArgs {
}

#[derive(Parser)]
pub struct ResumeArgs {
pub struct LifecycleArgs {
/// Computer ID (defaults to STEEL_COMPUTER_ID or `steel computer use`)
pub computer_id: Option<String>,

/// Wait until the computer is running
/// Wait until the computer reaches its new state
#[arg(long)]
pub wait: bool,
}
Expand Down Expand Up @@ -151,6 +163,9 @@ pub async fn run(command: Command) -> Result<()> {
Command::Delete(args) => run_delete(args).await,
Command::Pause(args) => run_pause(args).await,
Command::Resume(args) => run_resume(args).await,
Command::Stop(args) => run_stop(args).await,
Command::Start(args) => run_start(args).await,
Command::Restart(args) => run_restart(args).await,
Command::Use(args) => run_use(args),
Command::Exec(args) => exec::run(args).await,
Command::Ssh(args) => ssh::run(args).await,
Expand Down Expand Up @@ -287,7 +302,7 @@ async fn run_pause(args: IdArgs) -> Result<()> {
Ok(())
}

async fn run_resume(args: ResumeArgs) -> Result<()> {
async fn run_resume(args: LifecycleArgs) -> Result<()> {
let id = resolve_computer_id(args.computer_id.as_deref())?;
let (mode, base_url, auth) = api::resolve_with_auth();
let client = SteelClient::new()?;
Expand All @@ -305,6 +320,56 @@ async fn run_resume(args: ResumeArgs) -> Result<()> {
Ok(())
}

#[derive(Clone, Copy)]
enum Lifecycle {
Stop,
Start,
Restart,
}

impl Lifecycle {
const fn settled(self) -> &'static str {
match self {
Self::Stop => "stopped",
Self::Start | Self::Restart => "running",
}
}
}

async fn run_stop(args: LifecycleArgs) -> Result<()> {
run_lifecycle(args, Lifecycle::Stop).await
}

async fn run_start(args: LifecycleArgs) -> Result<()> {
run_lifecycle(args, Lifecycle::Start).await
}

async fn run_restart(args: LifecycleArgs) -> Result<()> {
run_lifecycle(args, Lifecycle::Restart).await
}

async fn run_lifecycle(args: LifecycleArgs, verb: Lifecycle) -> Result<()> {
let id = resolve_computer_id(args.computer_id.as_deref())?;
let (mode, base_url, auth) = api::resolve_with_auth();
let client = SteelClient::new()?;
let sent = match verb {
Lifecycle::Stop => client.stop_computer(&base_url, mode, &auth, &id).await?,
Lifecycle::Start => client.start_computer(&base_url, mode, &auth, &id).await?,
Lifecycle::Restart => client.restart_computer(&base_url, mode, &auth, &id).await?,
};
let data = if args.wait {
wait_for(&client, &base_url, mode, &auth, &id, verb.settled()).await?
} else {
sent
};
if output::is_json() {
output::success_data(data);
} else {
println!("{id} is {}.", status_of(&data));
}
Ok(())
}

async fn run_quota() -> Result<()> {
let (mode, base_url, auth) = api::resolve_with_auth();
let client = SteelClient::new()?;
Expand Down
82 changes: 82 additions & 0 deletions tests/computer_lifecycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! End-to-end tests for `steel computer stop|start|restart` against a fake API host.

use std::process::{Command, Output};

use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

async fn run_steel(server: &MockServer, args: &[&str]) -> Output {
let tmp = tempfile::tempdir().expect("temp dir");
let mut cmd = Command::new(env!("CARGO_BIN_EXE_steel"));
cmd.env("STEEL_CONFIG_DIR", tmp.path());
cmd.env("STEEL_API_URL", format!("{}/v1", server.uri()));
cmd.env("STEEL_API_KEY", "ste-test-key");
cmd.env("STEEL_TELEMETRY_DISABLED", "1");
cmd.env("STEEL_FORCE_TTY", "1");
cmd.arg("--no-update-check");
cmd.args(args);
tokio::task::spawn_blocking(move || {
let output = cmd.output().expect("failed to execute steel binary");
drop(tmp);
output
})
.await
.expect("steel process")
}

const ID: &str = "cmp_00x1492gqevd1nvs7vya5py3d0m33";

async fn mount(server: &MockServer, verb: &str, status: &str) {
Mock::given(method("POST"))
.and(path(format!("/v1/computers/{ID}/{verb}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": ID,
"status": status
})))
.expect(1)
.mount(server)
.await;
}

#[tokio::test(flavor = "multi_thread")]
async fn stop_reports_the_settled_status() {
let server = MockServer::start().await;
mount(&server, "stop", "stopped").await;

let output = run_steel(&server, &["computer", "stop", ID]).await;

assert!(output.status.success());
let text = String::from_utf8_lossy(&output.stdout).to_string();
assert!(text.contains(&format!("{ID} is stopped.")));
}

#[tokio::test(flavor = "multi_thread")]
async fn start_reports_the_settled_status() {
let server = MockServer::start().await;
mount(&server, "start", "running").await;

let output = run_steel(&server, &["computer", "start", ID]).await;

assert!(output.status.success());
let text = String::from_utf8_lossy(&output.stdout).to_string();
assert!(text.contains(&format!("{ID} is running.")));
}

#[tokio::test(flavor = "multi_thread")]
async fn restart_calls_restart_and_not_start() {
let server = MockServer::start().await;
mount(&server, "restart", "running").await;
Mock::given(method("POST"))
.and(path(format!("/v1/computers/{ID}/start")))
.respond_with(ResponseTemplate::new(500))
.expect(0)
.mount(&server)
.await;

let output = run_steel(&server, &["computer", "restart", ID]).await;

assert!(output.status.success());
let text = String::from_utf8_lossy(&output.stdout).to_string();
assert!(text.contains(&format!("{ID} is running.")));
}
Loading