diff --git a/apps/piquelctl/src/deployments.rs b/apps/piquelctl/src/deployments.rs index 13199bb32..4aeec2cd7 100644 --- a/apps/piquelctl/src/deployments.rs +++ b/apps/piquelctl/src/deployments.rs @@ -174,6 +174,20 @@ async fn find_deployment( }) } +/// `environment`'s latest deployment, if any: its latest operation unless +/// that deletes it. The daemon picks it by creation time, so it need not be +/// the first row of the deployment list, which pages by ID: after a restart +/// with the clock behind, an older deployment can have the higher ID. +pub(crate) async fn latest_deployment( + client: &Client, + environment: &EnvironmentView, +) -> Result> { + let detail = client.environment_detail(environment.id.as_str()).await?; + Ok(detail + .latest_operation + .filter(|operation| operation.kind != OperationKind::Delete)) +} + /// Emits an accepted deployment as is with `no_wait`, otherwise waits for it /// and emits how it ended. pub(crate) async fn wait_for_accepted( @@ -305,14 +319,9 @@ impl WaitArgs { /// `environment`'s, or its latest one. async fn deployment(&self, client: &Client, environment: &EnvironmentView) -> Result { let Some(id) = &self.deployment else { - let page = client - .deployment_summaries(environment.id.as_str(), None, Some(1)) - .await?; - return page - .items - .into_iter() - .next() - .map(|deployment| deployment.operation.id) + return latest_deployment(client, environment) + .await? + .map(|operation| operation.id) .ok_or_else(|| { CliError::new( ErrorKind::Input, diff --git a/apps/piquelctl/src/environments.rs b/apps/piquelctl/src/environments.rs index f6b1b19f8..c90a36ec6 100644 --- a/apps/piquelctl/src/environments.rs +++ b/apps/piquelctl/src/environments.rs @@ -6,7 +6,9 @@ use crate::{ commands::{ Wait, finish_operation, resolve_application, wait_for_deletion, wait_for_operation, }, - deployments::{HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs, wait_for_accepted}, + deployments::{ + HistoryArgs, RestoreArgs, Target, UrlArgs, WaitArgs, latest_deployment, wait_for_accepted, + }, editing::{EditFlags, on_off, visibility}, error::{CliError, ErrorKind, ErrorReport, Result}, output::{ @@ -1041,7 +1043,7 @@ impl Lifecycle { .await?; let (id, expected) = (environment.id.as_str(), flags.expected_generation); let before = match self { - Self::Stop if !flags.no_wait => Baseline::latest(client, id).await?, + Self::Stop if !flags.no_wait => Baseline::latest(client, environment).await?, _ => None, }; let accepted = retry_transport(|| async move { @@ -1072,14 +1074,16 @@ struct Baseline { } impl Baseline { - /// The latest deployment's operation of environment `id`, if any. - async fn latest(client: &Client, id: &str) -> Result> { - let deployments = client.deployment_summaries(id, None, Some(1)).await?; - Ok(deployments.items.into_iter().next().map(|deployment| Self { - terminal: deployment.operation.state.terminal(), - attempt: deployment.operation.attempt, - operation: deployment.operation.id, - })) + /// The operation of `environment`'s latest deployment, if any (see + /// `latest_deployment`). + async fn latest(client: &Client, environment: &EnvironmentView) -> Result> { + Ok(latest_deployment(client, environment) + .await? + .map(|operation| Self { + terminal: operation.state.terminal(), + attempt: operation.attempt, + operation: operation.id, + })) } /// Whether `operation`'s outcome is news since this one: another diff --git a/apps/piquelctl/tests/cli/environments.rs b/apps/piquelctl/tests/cli/environments.rs index 985f0d14d..fcd7e2a87 100644 --- a/apps/piquelctl/tests/cli/environments.rs +++ b/apps/piquelctl/tests/cli/environments.rs @@ -458,22 +458,36 @@ fn deployment(state: &str) -> Value { }) } +/// A deployment of `app-notes-01` created before `operation-01` but listed +/// first, as the only row of a full page: after a restart with the clock +/// behind, older deployments can have higher IDs, so the newest one can be +/// off the first page. +fn listed_first() -> Value { + let mut older = deployment("succeeded"); + older["operation"]["id"] = json!("operation-09"); + older["operation"]["created_at_ms"] = json!(0); + older["current_target"] = json!(false); + older +} + /// Serves `env wait` for `app-notes-01`: its latest deployment is -/// `operation-01`, whose timeline streams as each of `states` in turn, and -/// its detail as each of `details` in turn (the last one repeats). +/// `operation-01`, which its detail names as the wait starts though the +/// list shows only [`listed_first`], whose timeline streams as each of +/// `states` in turn, and its detail then as each of `details` in turn (the +/// last one repeats). fn wait_server(states: Vec<&'static str>, details: Vec) -> TestServer { let state = *states.last().unwrap(); let timelines: Vec<_> = states .into_iter() .map(|state| timeline(&operation(state), &json!([]))) .collect(); - let mut details = details.into_iter(); + let mut details = std::iter::once(detail("operation-01", false, "pending")).chain(details); let mut current = None; start_server(false, usize::MAX, move |request| { match request.path.split('?').next().unwrap() { "/api/v1/applications/app-notes-01" => Reply::json(app_view("app-notes-01", "notes")), "/api/v1/environments/app-notes-01/deployments" => { - Reply::json(page(vec![deployment(state)], None)) + Reply::json(page(vec![listed_first()], Some("next"))) } DEPLOYMENT => Reply::json(deployment(state)), TIMELINE_STREAM => Reply::timelines(&timelines), @@ -681,15 +695,32 @@ fn deploy_output_carries_the_deployment_fields_agents_need() { /// `env stop` waits until the runtime reports its services stopped, fails /// when the deployment it ran again failed, even before its first poll, and -/// ends when the environment is started meanwhile. +/// ends when the environment is started meanwhile. A failed deployment it +/// left as is, the latest though the list shows only [`listed_first`], +/// doesn't fail the wait. #[test] fn env_stop_waits_until_stopped_unless_the_stop_fails_or_is_undone() { - // (attempt after the stop, run state, runtime health at each status - // read, exit code) - for (attempt, run_state, healths, code) in [ - (1, "stopped", &["ready", "stopped"][..], 0), - (2, "stopped", &["ready"][..], 5), - (1, "running", &["ready"][..], 0), + // (state before the stop, attempt and state after, run state, runtime + // health at each status read, exit code) + for (before, attempt, after, run_state, healths, code) in [ + ( + "succeeded", + 1, + "succeeded", + "stopped", + &["ready", "stopped"][..], + 0, + ), + ("succeeded", 2, "failed", "stopped", &["ready"][..], 5), + ("succeeded", 1, "succeeded", "running", &["ready"][..], 0), + ( + "failed", + 1, + "failed", + "stopped", + &["ready", "stopped"][..], + 0, + ), ] { let mut reads = healths.iter(); let server = start_server(false, usize::MAX, move |request| { @@ -698,7 +729,12 @@ fn env_stop_waits_until_stopped_unless_the_stop_fails_or_is_undone() { Reply::json(app_view("app-notes-01", "notes")) } "/api/v1/environments/app-notes-01/deployments" => { - Reply::json(page(vec![deployment("succeeded")], None)) + Reply::json(page(vec![listed_first()], Some("next"))) + } + "/api/v1/environments/app-notes-01/detail" => { + let mut detail = detail("operation-01", true, "ready"); + detail["latest_operation"] = operation(before); + Reply::json(detail) } "/api/v1/environments/app-notes-01/stop" => { Reply::accepted(accepted("app-notes-01")) @@ -714,7 +750,7 @@ fn env_stop_waits_until_stopped_unless_the_stop_fails_or_is_undone() { Reply::json(environment) } "/api/v1/operations/operation-01" => { - let mut operation = operation(if attempt > 1 { "failed" } else { "succeeded" }); + let mut operation = operation(after); operation["attempt"] = json!(attempt); Reply::json(operation) } diff --git a/apps/piqueld-ui/src/browser/management/deployments/history.rs b/apps/piqueld-ui/src/browser/management/deployments/history.rs index 57737754f..cf8ba8fd3 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/history.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/history.rs @@ -56,8 +56,8 @@ impl History { /// Polls the first page of `environment` every 2 seconds while the /// editor's Deployments tab is selected and the page is visible, and - /// right after the tab opens, following its newest deployment while it - /// runs (see `RunningDeployment`). Stops when the owning view unmounts. + /// right after the tab opens, following the deployment it lists running + /// (see `RunningDeployment`). Stops when the owning view unmounts. fn poll(self, context: EditorContext, environment: String) { let active = Alive::new(); let running = use_context::(); @@ -73,8 +73,16 @@ impl History { } match result { Ok(page) => { - if let (Some(newest), Some(running)) = (page.items.first(), running) { - running.saw(&newest.operation); + // Starting an operation supersedes the one in + // progress, so at most one row runs, whatever + // the page's order. + if let (Some(listed), Some(running)) = ( + page.items + .iter() + .find(|listed| !listed.operation.state.terminal()), + running, + ) { + running.saw(&listed.operation); } self.merge(page); self.error.set(None); diff --git a/apps/piqueld-ui/src/browser/management/deployments/page.rs b/apps/piqueld-ui/src/browser/management/deployments/page.rs index 89a0888c4..8afd88d32 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/page.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/page.rs @@ -24,9 +24,6 @@ use piqueld_client::{ #[derive(Clone, Copy)] struct ShownDeployment { deployment: RwSignal>, - /// Whether a newer deployment is listed: one that failed before - /// replacing the current target leaves Restore offered on it. - newer: RwSignal, error: RwSignal>, } @@ -34,32 +31,21 @@ impl ShownDeployment { fn new() -> Self { Self { deployment: RwSignal::new(None), - newer: RwSignal::new(false), error: RwSignal::new(None), } } - /// Reads deployment `operation` of `environment`, and whether a newer - /// deployment is listed. Abandoned when the calling owner is cleaned up. + /// Reads deployment `operation` of `environment`. Abandoned when the + /// calling owner is cleaned up. fn load(self, environment: String, operation: String) { let alive = Alive::new(); spawn_local(async move { - let client = Client::browser(); - let (deployment, newest) = futures_util::join!( - client.deployment(&environment, &operation), - client.deployment_summaries(&environment, None, Some(1)), - ); + let deployment = Client::browser().deployment(&environment, &operation).await; if !alive.get() { return; } - match deployment.and_then(|deployment| Ok((deployment, newest?))) { - Ok((deployment, newest)) => { - self.newer.set( - newest - .items - .first() - .is_some_and(|newest| newest.operation.id != operation), - ); + match deployment { + Ok(deployment) => { self.deployment.set(Some(deployment)); self.error.set(None); } @@ -169,7 +155,7 @@ pub(in crate::browser::management) fn DeploymentPage(operation: String) -> impl {move || progress.with(|p| p.as_ref().map(status_pill))}
- +
@@ -223,14 +209,13 @@ fn DeploymentSections(deployment: Signal) -> impl IntoView { } /// Restore, offered on a deployment the caller may restore that succeeded -/// and is not the current target, unless a `newer` deployment failed to -/// replace it. Opens the restoring deployment's page once accepted. +/// and is not the current target, or is but a newer deployment, the +/// environment's latest, failed to replace it. Opens the restoring +/// deployment's page once accepted. #[component] -fn RestoreDeployment( - deployment: Signal>, - newer: RwSignal, -) -> impl IntoView { +fn RestoreDeployment(deployment: Signal>) -> impl IntoView { let context = editor(); + let detail = context.signals().detail; let navigate = use_navigate(); move || { let id = deployment.with(|deployment| { @@ -238,7 +223,14 @@ fn RestoreDeployment( .as_ref() .filter(|deployment| { deployment.succeeded_at_ms.is_some() - && (!deployment.current_target || newer.get()) + && (!deployment.current_target + || detail.with(|detail| { + deployment.superseded_by( + detail + .as_ref() + .and_then(|detail| detail.latest_operation.as_ref()), + ) + })) }) .map(|deployment| deployment.operation.id.clone()) })?; diff --git a/apps/piqueld-ui/src/deployments.rs b/apps/piqueld-ui/src/deployments.rs index 7899dcec8..f8dd5c43c 100644 --- a/apps/piqueld-ui/src/deployments.rs +++ b/apps/piqueld-ui/src/deployments.rs @@ -3,8 +3,9 @@ //! attempt lists, promotion confirmation, and preview creation. use piqueld_client::{ - CreatePreviewRequest, DeploymentOrigin, DeploymentSummary, DeploymentView, Operation, Page, - PlanView, PromoteRequest, ReleaseAvailability, SystemVariable, sync::short_commit, + CreatePreviewRequest, DeploymentOrigin, DeploymentSummary, DeploymentView, Operation, + OperationKind, Page, PlanView, PromoteRequest, ReleaseAvailability, SystemVariable, + sync::short_commit, }; /// What a deployment's row in its environment's history, and its page, say @@ -35,6 +36,18 @@ pub trait DeploymentFacts { let started = operation.started_at_ms.unwrap_or(operation.created_at_ms); u64::try_from(operation.finished_at_ms? - started).ok() } + + /// Whether `latest`, its environment's latest operation, is a newer + /// deployment. The daemon picks the latest by creation time: the + /// deployment list, paged by ID, can list an older deployment first. + fn superseded_by(&self, latest: Option<&Operation>) -> bool { + let operation = self.operation(); + latest.is_some_and(|latest| { + latest.kind != OperationKind::Delete + && latest.environment_id == operation.environment_id + && latest.id != operation.id + }) + } } impl DeploymentFacts for DeploymentView { @@ -294,6 +307,27 @@ mod tests { assert_eq!(built.duration_ms(), Some(38_000)); } + /// Only another deployment, the environment's latest, supersedes one: not + /// the deployment itself, a deletion, or another environment's operation. + #[test] + fn only_the_latest_deployment_of_its_environment_supersedes_one() { + let current = deployment("operation-1", true, true); + assert!(!current.superseded_by(None)); + assert!(!current.superseded_by(Some(¤t.operation))); + let failed = operation("operation-0", 1, OperationState::Failed); + assert!(current.superseded_by(Some(&failed))); + let deletion = Operation { + kind: OperationKind::Delete, + ..failed.clone() + }; + assert!(!current.superseded_by(Some(&deletion))); + let elsewhere = Operation { + environment_id: "env-fedcba9876543210fedcba9876543210".parse().unwrap(), + ..failed + }; + assert!(!current.superseded_by(Some(&elsewhere))); + } + #[test] fn a_polled_newest_page_keeps_older_pages_and_moves_the_flags() { let mut list = vec![