Skip to content
Draft
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
74 changes: 66 additions & 8 deletions apps/piquelctl/src/deployments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
error::{CliCode, CliError, ErrorKind, Result},
output::{
Console,
reports::{AcceptedDeploymentReport, Named, OperationOutcomeReport},
reports::{AcceptedDeploymentReport, AttemptsReport, Named, OperationOutcomeReport},
},
support::{join_or, retry_transport},
};
Expand Down Expand Up @@ -165,13 +165,18 @@ async fn find_deployment(
client
.deployment(environment.id.as_str(), id)
.await
.map_err(|error| match error {
ClientError::Api { status, .. } if status.as_u16() == 404 => CliError::new(
ErrorKind::Input,
format!("deployment {id:?} of {} was not found", environment.name),
),
error => error.into(),
})
.map_err(not_found(environment, id))
}

/// Maps the API's 404 for deployment `id` of `environment` to an input error.
fn not_found(environment: &EnvironmentView, id: &str) -> impl FnOnce(ClientError) -> CliError {
move |error| match error {
ClientError::Api { status, .. } if status.as_u16() == 404 => CliError::new(
ErrorKind::Input,
format!("deployment {id:?} of {} was not found", environment.name),
),
error => error.into(),
}
}

/// `environment`'s latest deployment, if any: its latest operation unless
Expand Down Expand Up @@ -364,6 +369,59 @@ impl<T: Args + Target> HistoryArgs<T> {
}
}

// `attempts` arguments shared by `env attempts` and `preview attempts`.
#[derive(Debug, Args)]
pub(crate) struct AttemptsArgs<T: Args> {
#[command(flatten)]
target: T,
/// ID of the deployment, as `history` lists it. By default, the latest
/// deployment.
#[arg(long, value_name = "ID")]
deployment: Option<String>,
/// Cursor from the previous page; needs `--deployment`.
#[arg(long, requires = "deployment")]
cursor: Option<String>,
}

impl<T: Args + Target> AttemptsArgs<T> {
/// Emits one page of a deployment's attempts, newest first, 100 per
/// page. The first page leads with the attempt running now, until the
/// API retains its outcome.
pub(crate) async fn run(&self, console: &mut Console, client: &Client) -> Result<()> {
let environment = &self.target.environment(client).await?;
// The deployment's operation is read before its attempts, so the
// attempt it runs is newer than any retained outcome. `--cursor`
// needs `--deployment`, and a later page lists retained ones alone.
let (deployment, live) = match (&self.deployment, &self.cursor) {
(None, _) => {
let latest = latest_deployment(client, environment)
.await?
.ok_or_else(|| {
CliError::new(
ErrorKind::Input,
format!("{} has no deployments yet", environment.name),
)
})?;
(latest.id.clone(), Some(latest))
}
// Reading it reports an unknown deployment by name.
(Some(id), None) => {
let deployment = find_deployment(client, environment, id).await?;
(id.clone(), Some(deployment.operation))
}
(Some(id), Some(_)) => (id.clone(), None),
};
let mut page = client
.deployment_attempts(environment.id.as_str(), &deployment, self.cursor.as_deref())
.await
.map_err(not_found(environment, &deployment))?;
if let Some(live) = live {
page.items = live.attempts(&page.items);
}
console.emit(&AttemptsReport { deployment, page })
}
}

// `restore` arguments shared by `env restore` and `preview restore`.
#[derive(Debug, Args)]
pub(crate) struct RestoreArgs<T: Args> {
Expand Down
10 changes: 9 additions & 1 deletion apps/piquelctl/src/environments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use crate::{
Wait, finish_operation, resolve_application, wait_for_deletion, wait_for_operation,
},
deployments::{
HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs, latest_deployment, wait_for_accepted,
AttemptsArgs, HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs, latest_deployment,
wait_for_accepted,
},
editing::{EditFlags, on_off, visibility},
error::{CliError, ErrorKind, ErrorReport, Result},
Expand Down Expand Up @@ -182,6 +183,12 @@ pub(crate) enum EnvCommand {
/// List an environment's deployments, newest first: each one's outcome,
/// where it came from, and its release.
History(HistoryArgs<EnvironmentArgs>),
/// List the attempts of one of an environment's deployments, newest first: each
/// try at rolling it out, how it ended, and when it last changed.
///
/// The attempt running now leads until its outcome is recorded. Without
/// `--deployment`, it lists the latest deployment's attempts.
Attempts(AttemptsArgs<EnvironmentArgs>),
/// Deploy an earlier, succeeded deployment again exactly as it ran: its
/// rendered manifest, images and pinned secret versions. Jobs don't run,
/// and volume contents and migrations stay as they are.
Expand Down Expand Up @@ -304,6 +311,7 @@ impl EnvCommand {
logs(console, client, &target.resolve(client).await?.1, window).await
}
Self::History(args) => args.run(console, client).await,
Self::Attempts(args) => args.run(console, client).await,
Self::Restore(args) => args.run(console, client).await,
Self::Wait(args) => args.run(console, client).await,
Self::Url(args) => args.run(console, client).await,
Expand Down
24 changes: 24 additions & 0 deletions apps/piquelctl/src/output/reports/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ report!(Page<BuildRecord>, self, out, {
out.next_cursor(self.next_cursor.as_deref())
});

/// `attempts` result: one page of a deployment's attempts, newest first. Its
/// JSON is the page; every attempt's `id` is the deployment's.
pub(crate) struct AttemptsReport {
pub(crate) deployment: String,
pub(crate) page: Page<Operation>,
}
report!(AttemptsReport as Page<Operation> = page, self, out, {
out.label("Deployment", &self.deployment)?;
out.table(
&self.page.items,
"No attempts yet.",
["Attempt", "State", "Outcome", "Updated"],
|attempt| {
[
attempt.attempt.to_string(),
attempt.state.to_string(),
attempt.failure(),
Timestamp(attempt.updated_at_ms).to_string(),
]
},
)?;
out.next_cursor(self.page.next_cursor.as_deref())
});

/// Name of a deleted secret or notification destination.
#[derive(Serialize)]
pub(crate) struct NameDeletionReport<'a> {
Expand Down
10 changes: 9 additions & 1 deletion apps/piquelctl/src/previews.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use crate::{
cli::LogArgs,
commands::{resolve_application, wait_for_deletion, wait_for_operation},
deployments::{
Deployed, HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs, wait_for_accepted,
AttemptsArgs, Deployed, HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs,
wait_for_accepted,
},
environments::logs,
error::{CliError, ErrorKind, Result},
Expand Down Expand Up @@ -74,6 +75,12 @@ pub(crate) enum PreviewCommand {
/// List a preview's deployments, newest first: each one's outcome and
/// where it came from.
History(HistoryArgs<PreviewArgs>),
/// List the attempts of one of a preview's deployments, newest first: each
/// try at rolling it out, how it ended, and when it last changed.
///
/// The attempt running now leads until its outcome is recorded. Without
/// `--deployment`, it lists the latest deployment's attempts.
Attempts(AttemptsArgs<PreviewArgs>),
/// Deploy an earlier, succeeded deployment of a preview again exactly as
/// it ran, without running its jobs.
Restore(RestoreArgs<PreviewArgs>),
Expand Down Expand Up @@ -258,6 +265,7 @@ impl PreviewCommand {
logs(console, client, &preview, window).await
}
Self::History(args) => args.run(console, client).await,
Self::Attempts(args) => args.run(console, client).await,
Self::Restore(args) => args.run(console, client).await,
Self::Wait(args) => args.run(console, client).await,
Self::Url(args) => args.run(console, client).await,
Expand Down
107 changes: 106 additions & 1 deletion apps/piquelctl/tests/cli/environments.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Environment commands: targeting, promotion, rollback, history and waits.
//! Environment commands: targeting, promotion, rollback, history, attempts and waits.

use super::*;

Expand Down Expand Up @@ -441,6 +441,111 @@ fn history_lists_restores_and_restore_names_the_deployment() {
let _ = server.finish();
}

/// `env attempts` lists the latest deployment's attempts newest first, led
/// by the one running now, though the list shows only [`listed_first`], or
/// those of `--deployment`; `--cursor` pages them without it; and an
/// unknown deployment is an input error.
#[test]
fn attempts_list_a_deployments_tries_and_page() {
let attempt = |number: u64, state: &str| {
let mut attempt = operation(state);
attempt["attempt"] = json!(number);
attempt
};
let mut live = deployment("running");
live["operation"]["attempt"] = json!(3);
let mut detail = detail("operation-01", true, "ready");
detail["latest_operation"] = live["operation"].clone();
let server = start_server(false, usize::MAX, move |request| {
match request.path.as_str() {
"/api/v1/applications/app-notes-01" => Reply::json(app_view("app-notes-01", "notes")),
// Any page of the list leads with an older deployment.
path if path.starts_with("/api/v1/environments/app-notes-01/deployments?") => {
Reply::json(page(vec![listed_first()], Some("next")))
}
"/api/v1/environments/app-notes-01/detail" => Reply::json(detail.clone()),
DEPLOYMENT => Reply::json(live.clone()),
"/api/v1/environments/app-notes-01/deployments/operation-01/attempts" => {
Reply::json(page(vec![attempt(2, "failed")], Some("older")))
}
"/api/v1/environments/app-notes-01/deployments/operation-01/attempts?cursor=older" => {
Reply::json(page(vec![attempt(1, "succeeded")], None))
}
"/api/v1/environments/app-notes-01/deployments/operation-07" => Reply::status(
"404 Not Found",
&json!({"code": "not_found", "message": "not found"}),
),
path => panic!("unexpected path {path}"),
}
});

let output = run_human(&server, &["env", "attempts", "app-notes-01"]);
assert!(output.status.success(), "{output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
for line in [
"Deployment: operation-01",
"Attempt State Outcome",
"3 running",
"2 failed runtime_failed: runtime reconciliation failed",
"Next cursor: older",
] {
assert!(stdout.contains(line), "{line:?} missing from {stdout}");
}

let listed = |page: &Value| {
page["items"]
.as_array()
.unwrap()
.iter()
.map(|item| (item["attempt"].as_u64().unwrap(), item["state"].clone()))
.collect::<Vec<_>>()
};
for named in [&[][..], &["--deployment", "operation-01"]] {
let arguments = [&["env", "attempts", "app-notes-01"][..], named].concat();
let first = assert_json_success(&run(&server, &arguments));
assert_eq!(
listed(&first),
[(3, json!("running")), (2, json!("failed"))]
);
assert_eq!(first["next_cursor"], "older");
}

// A later page lists retained outcomes alone.
let older = assert_json_success(&run(
&server,
&[
"env",
"attempts",
"app-notes-01",
"--deployment",
"operation-01",
"--cursor",
"older",
],
));
assert_eq!(listed(&older), [(1, json!("succeeded"))]);
assert_eq!(older["next_cursor"], Value::Null);

let unknown = run(
&server,
&[
"env",
"attempts",
"app-notes-01",
"--deployment",
"operation-07",
],
);
assert_eq!(unknown.status.code(), Some(2));
let error = support::json_error(&unknown);
assert_eq!(error["code"], "invalid_input");
assert_eq!(
error["message"],
"deployment \"operation-07\" of production was not found"
);
server.stop();
}

/// Where `operation-01`, a deployment of `app-notes-01`, reads alone.
const DEPLOYMENT: &str = "/api/v1/environments/app-notes-01/deployments/operation-01";

Expand Down
7 changes: 1 addition & 6 deletions apps/piqueld-ui/src/browser/management/deployments/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,12 +498,7 @@ fn DeploymentAttempts(deployment: Signal<DeploymentView>) -> impl IntoView {
fn AttemptRow(attempt: Operation) -> impl IntoView {
let context = editor();
let history = operation_events(&attempt.id);
let outcome = match (attempt.error_code, attempt.error_message) {
(Some(code), Some(message)) => format!("{code}: {message}"),
(Some(code), None) => code,
(None, Some(message)) => message,
(None, None) => String::new(),
};
let outcome = attempt.failure();
view! {
<tr>
<td class="num">{attempt.attempt}</td>
Expand Down
Loading