From a1dd4182ab48f7a1933a09ad576f5619cbd253da Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 00:30:26 +0100 Subject: [PATCH 1/2] fix(ui): stop treating the first row of the deployment list as the newest deployment The deployment list pages by ID, but since PQD-130 the store picks an environment's latest and current deployment by creation time: after a restart with the clock behind, an older deployment can have the higher ID and list first. The deployment page, the history poll, and the CLI's `stop` and `wait` now pick the newest listed deployment by creation time, then ID, through `DeploymentSummary::newest`. Fixes PQD-149 --- apps/piquelctl/src/deployments.rs | 20 ++++--- apps/piquelctl/src/environments.rs | 27 ++++++---- apps/piquelctl/tests/cli/environments.rs | 52 ++++++++++++++----- .../browser/management/deployments/history.rs | 4 +- .../src/browser/management/deployments/mod.rs | 3 +- .../browser/management/deployments/page.rs | 16 +++--- apps/piqueld-ui/src/deployments.rs | 23 ++++++++ crates/piqueld-core/src/api/deployments.rs | 11 ++++ crates/piqueld-core/src/api/tests.rs | 38 +++++++++++++- crates/piqueld-core/src/operation.rs | 10 ++++ 10 files changed, 156 insertions(+), 48 deletions(-) diff --git a/apps/piquelctl/src/deployments.rs b/apps/piquelctl/src/deployments.rs index 13199bb32..9b166c389 100644 --- a/apps/piquelctl/src/deployments.rs +++ b/apps/piquelctl/src/deployments.rs @@ -9,14 +9,14 @@ use crate::{ Console, reports::{AcceptedDeploymentReport, Named, OperationOutcomeReport}, }, - support::{join_or, retry_transport}, + support::{PAGE_SIZE, join_or, retry_transport}, }; use clap::{Args, ValueEnum}; use piqueld_client::{ AcceptedOperation, ApplicationId, ApplicationView, Client, ClientError, DeploymentOrigin, - DeploymentView, EnvironmentDetailView, EnvironmentId, EnvironmentName, EnvironmentView, - LocalSnapshot, Operation, OperationKind, OperationState, ReleaseId, RouteUrl, SystemVariable, - UrlState, + DeploymentSummary, DeploymentView, EnvironmentDetailView, EnvironmentId, EnvironmentName, + EnvironmentView, LocalSnapshot, Operation, OperationKind, OperationState, ReleaseId, RouteUrl, + SystemVariable, UrlState, }; use serde::Serialize; use serde_json::json; @@ -302,17 +302,15 @@ impl WaitArgs { } /// The deployment to wait for: `--deployment`, checked to be one of - /// `environment`'s, or its latest one. + /// `environment`'s, or the newest one its first page lists (see + /// `DeploymentSummary::newest`). 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)) + .deployment_summaries(environment.id.as_str(), None, Some(PAGE_SIZE)) .await?; - return page - .items - .into_iter() - .next() - .map(|deployment| deployment.operation.id) + return DeploymentSummary::newest(&page.items) + .map(|deployment| deployment.operation.id.clone()) .ok_or_else(|| { CliError::new( ErrorKind::Input, diff --git a/apps/piquelctl/src/environments.rs b/apps/piquelctl/src/environments.rs index f6b1b19f8..bdbb984cf 100644 --- a/apps/piquelctl/src/environments.rs +++ b/apps/piquelctl/src/environments.rs @@ -13,13 +13,13 @@ use crate::{ Console, TaskOutcome, reports::{DeletionReport, EnvironmentRow, EnvironmentShowReport, Named, PromotionReport}, }, - support::{join_or, retry_transport}, + support::{PAGE_SIZE, join_or, retry_transport}, }; use clap::{Args, Subcommand, ValueEnum}; use piqueld_client::{ - ApplicationView, Client, ClientError, CreateEnvironmentRequest, EnvironmentBranchRequest, - EnvironmentRequest, EnvironmentSourceRequest, EnvironmentStatusView, EnvironmentView, - Operation, PromoteRequest, Rollback, Visibility, edit::ApplicationEdit, + ApplicationView, Client, ClientError, CreateEnvironmentRequest, DeploymentSummary, + EnvironmentBranchRequest, EnvironmentRequest, EnvironmentSourceRequest, EnvironmentStatusView, + EnvironmentView, Operation, PromoteRequest, Rollback, Visibility, edit::ApplicationEdit, }; // `env` subcommands; `///` on variants and fields is user-facing help. @@ -1072,14 +1072,19 @@ struct Baseline { } impl Baseline { - /// The latest deployment's operation of environment `id`, if any. + /// The latest deployment's operation of environment `id`, if any: the + /// newest one its first page lists (see `DeploymentSummary::newest`). 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, - })) + let deployments = client + .deployment_summaries(id, None, Some(PAGE_SIZE)) + .await?; + Ok( + DeploymentSummary::newest(&deployments.items).map(|deployment| Self { + terminal: deployment.operation.state.terminal(), + attempt: deployment.operation.attempt, + operation: deployment.operation.id.clone(), + }), + ) } /// 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..9a13274f5 100644 --- a/apps/piquelctl/tests/cli/environments.rs +++ b/apps/piquelctl/tests/cli/environments.rs @@ -458,9 +458,20 @@ fn deployment(state: &str) -> Value { }) } +/// A deployment of `app-notes-01` created before `operation-01` but listed +/// above it: after a restart with the clock behind, it has the higher ID. +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`, listed below [`listed_first`], whose timeline streams as +/// each of `states` in turn, and its detail 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 @@ -473,7 +484,7 @@ fn wait_server(states: Vec<&'static str>, details: Vec) -> TestServer { 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(), deployment(state)], None)) } DEPLOYMENT => Reply::json(deployment(state)), TIMELINE_STREAM => Reply::timelines(&timelines), @@ -681,15 +692,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 listed below [`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 +726,7 @@ 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(), deployment(before)], None)) } "/api/v1/environments/app-notes-01/stop" => { Reply::accepted(accepted("app-notes-01")) @@ -714,7 +742,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..5164ecc42 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/history.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/history.rs @@ -73,7 +73,9 @@ impl History { } match result { Ok(page) => { - if let (Some(newest), Some(running)) = (page.items.first(), running) { + if let (Some(newest), Some(running)) = + (DeploymentSummary::newest(&page.items), running) + { running.saw(&newest.operation); } self.merge(page); diff --git a/apps/piqueld-ui/src/browser/management/deployments/mod.rs b/apps/piqueld-ui/src/browser/management/deployments/mod.rs index 15375bcf5..13a14765c 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/mod.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/mod.rs @@ -15,7 +15,8 @@ use crate::browser::ui::key_values; use leptos::prelude::*; use std::fmt::Display; -/// Deployments the history asks for per page. +/// Deployments the history asks for per page, and a deployment's page reads +/// to tell whether a newer one is listed. const PAGE: u16 = 20; /// Definition list of the values of `${{ vars. }}` references. diff --git a/apps/piqueld-ui/src/browser/management/deployments/page.rs b/apps/piqueld-ui/src/browser/management/deployments/page.rs index 89a0888c4..1e6c3b725 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/page.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/page.rs @@ -1,5 +1,6 @@ //! One deployment's page: its progress and timeline, details, snapshot and //! attempts, and Restore. +use super::PAGE; use super::snapshot::DeploymentSnapshot; use crate::application::DEPLOYMENT_TABS; use crate::browser::format::timestamp; @@ -45,21 +46,16 @@ impl ShownDeployment { let alive = Alive::new(); spawn_local(async move { let client = Client::browser(); - let (deployment, newest) = futures_util::join!( + let (deployment, listed) = futures_util::join!( client.deployment(&environment, &operation), - client.deployment_summaries(&environment, None, Some(1)), + client.deployment_summaries(&environment, None, Some(PAGE)), ); 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.and_then(|deployment| Ok((deployment, listed?))) { + Ok((deployment, listed)) => { + self.newer.set(deployment.superseded_in(&listed.items)); self.deployment.set(Some(deployment)); self.error.set(None); } diff --git a/apps/piqueld-ui/src/deployments.rs b/apps/piqueld-ui/src/deployments.rs index 7899dcec8..8e73b5495 100644 --- a/apps/piqueld-ui/src/deployments.rs +++ b/apps/piqueld-ui/src/deployments.rs @@ -35,6 +35,13 @@ 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 `listed` holds a deployment created after it (see + /// `DeploymentSummary::newest`), whatever their order. + fn superseded_in(&self, listed: &[DeploymentSummary]) -> bool { + DeploymentSummary::newest(listed) + .is_some_and(|newest| newest.operation.recency() > self.operation().recency()) + } } impl DeploymentFacts for DeploymentView { @@ -294,6 +301,22 @@ mod tests { assert_eq!(built.duration_ms(), Some(38_000)); } + /// After a restart with the clock behind, the current deployment can + /// list below an older one with a higher ID: that one isn't newer, so + /// Restore isn't offered on the current deployment. + #[test] + fn only_a_deployment_created_later_supersedes_one() { + let mut current = deployment("operation-1", true, true); + current.operation.created_at_ms = 2_000; + let mut older = summary("operation-9", false, false); + older.operation.created_at_ms = 1_000; + let listed = vec![older, current.clone().into()]; + assert!(!current.superseded_in(&listed)); + let mut failed = summary("operation-0", false, false); + failed.operation.created_at_ms = 3_000; + assert!(current.superseded_in(&[listed, vec![failed]].concat())); + } + #[test] fn a_polled_newest_page_keeps_older_pages_and_moves_the_flags() { let mut list = vec![ diff --git a/crates/piqueld-core/src/api/deployments.rs b/crates/piqueld-core/src/api/deployments.rs index a415981e5..793e9cf05 100644 --- a/crates/piqueld-core/src/api/deployments.rs +++ b/crates/piqueld-core/src/api/deployments.rs @@ -113,6 +113,17 @@ impl From for DeploymentSummary { } } +impl DeploymentSummary { + /// The newest of `deployments` by [`Operation::recency`], which need not + /// be the first one a page lists. + #[must_use] + pub fn newest(deployments: &[Self]) -> Option<&Self> { + deployments + .iter() + .max_by(|a, b| a.operation.recency().cmp(&b.operation.recency())) + } +} + /// A page of an environment's deployments, newest first, in the /// [`DeploymentListView`] asked for. #[derive(Clone, Debug, Deserialize, Serialize)] diff --git a/crates/piqueld-core/src/api/tests.rs b/crates/piqueld-core/src/api/tests.rs index 7e4029bff..d5cb46cff 100644 --- a/crates/piqueld-core/src/api/tests.rs +++ b/crates/piqueld-core/src/api/tests.rs @@ -1,6 +1,6 @@ use super::{ - ApplicationView, BuildLogChunk, DeploymentPage, EnvironmentAccess, EnvironmentView, LogRecord, - MountedSecret, SecretAccess, SecretMetadata, StoredSecret, + ApplicationView, BuildLogChunk, DeploymentPage, DeploymentSummary, EnvironmentAccess, + EnvironmentView, LogRecord, MountedSecret, SecretAccess, SecretMetadata, StoredSecret, }; use crate::{ApplicationId, EnvironmentId, EnvironmentName, EnvironmentSource}; @@ -139,3 +139,37 @@ fn deployment_pages_are_documented_as_any_of() { assert!(schema.get("oneOf").is_none()); assert_eq!(schema["anyOf"].as_array().map(Vec::len), Some(2)); } + +/// Deployment `id`'s summary, created at `created_at_ms`. +fn summary(id: &str, created_at_ms: i64) -> DeploymentSummary { + serde_json::from_value(serde_json::json!({ + "operation": { + "id": id, "environment_id": "app-notes-01", "kind": "apply", + "generation": 1, "attempt": 1, "state": "succeeded", + "created_at_ms": created_at_ms, "updated_at_ms": created_at_ms, + }, + "succeeded_at_ms": created_at_ms, + "current_target": false, + "last_successful": false, + })) + .expect("deployment summary") +} + +/// After a restart with the clock behind, an older deployment can have the +/// higher ID and list first: the newest is the latest created, and of two +/// created in the same millisecond, the higher ID. +#[test] +fn the_newest_deployment_is_the_latest_created_not_the_first_listed() { + let newest = |listed: &[DeploymentSummary]| { + DeploymentSummary::newest(listed).map(|newest| newest.operation.id.clone()) + }; + let skewed = [ + summary("operation-f", 1), + summary("operation-a", 3), + summary("operation-b", 2), + ]; + assert_eq!(newest(&skewed).as_deref(), Some("operation-a")); + let tied = [summary("operation-a", 3), summary("operation-b", 3)]; + assert_eq!(newest(&tied).as_deref(), Some("operation-b")); + assert_eq!(newest(&[]), None); +} diff --git a/crates/piqueld-core/src/operation.rs b/crates/piqueld-core/src/operation.rs index 121dbccea..3c4952c2e 100644 --- a/crates/piqueld-core/src/operation.rs +++ b/crates/piqueld-core/src/operation.rs @@ -135,6 +135,16 @@ impl Operation { attempt > self.attempt || (attempt == self.attempt && self.state != OperationState::Requested) } + + /// How recent it is, as the store orders an environment's operations to + /// pick its latest: by creation time, then ID. IDs alone order only the + /// pages of a list, because they are monotonic within one daemon process: + /// after a restart with the clock behind, an older operation can have the + /// higher ID. + #[must_use] + pub fn recency(&self) -> (i64, &str) { + (self.created_at_ms, &self.id) + } } string_enum! { From 49387a0c53a9c4453193e3354beebe541c05f62d Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 13:10:41 +0100 Subject: [PATCH 2/2] fix(ui): find the latest deployment from the environment's latest operation The newest of the deployment list's first page still misses a newer deployment listed past it, since the list pages by ID. Use the latest operation the environment's detail reports instead, which the store picks by creation time, unless it is a deletion: `latest_deployment` in the CLI for `stop` and `wait`, and `DeploymentFacts::superseded_by` for the deployment page's Restore. The history poll follows the row it lists running, as at most one operation runs at a time. Part of PQD-149 --- apps/piquelctl/src/deployments.rs | 33 ++++++++---- apps/piquelctl/src/environments.rs | 37 +++++++------- apps/piquelctl/tests/cli/environments.rs | 26 ++++++---- .../browser/management/deployments/history.rs | 18 ++++--- .../src/browser/management/deployments/mod.rs | 3 +- .../browser/management/deployments/page.rs | 42 +++++++-------- apps/piqueld-ui/src/deployments.rs | 51 +++++++++++-------- crates/piqueld-core/src/api/deployments.rs | 11 ---- crates/piqueld-core/src/api/tests.rs | 38 +------------- crates/piqueld-core/src/operation.rs | 10 ---- 10 files changed, 122 insertions(+), 147 deletions(-) diff --git a/apps/piquelctl/src/deployments.rs b/apps/piquelctl/src/deployments.rs index 9b166c389..4aeec2cd7 100644 --- a/apps/piquelctl/src/deployments.rs +++ b/apps/piquelctl/src/deployments.rs @@ -9,14 +9,14 @@ use crate::{ Console, reports::{AcceptedDeploymentReport, Named, OperationOutcomeReport}, }, - support::{PAGE_SIZE, join_or, retry_transport}, + support::{join_or, retry_transport}, }; use clap::{Args, ValueEnum}; use piqueld_client::{ AcceptedOperation, ApplicationId, ApplicationView, Client, ClientError, DeploymentOrigin, - DeploymentSummary, DeploymentView, EnvironmentDetailView, EnvironmentId, EnvironmentName, - EnvironmentView, LocalSnapshot, Operation, OperationKind, OperationState, ReleaseId, RouteUrl, - SystemVariable, UrlState, + DeploymentView, EnvironmentDetailView, EnvironmentId, EnvironmentName, EnvironmentView, + LocalSnapshot, Operation, OperationKind, OperationState, ReleaseId, RouteUrl, SystemVariable, + UrlState, }; use serde::Serialize; use serde_json::json; @@ -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( @@ -302,15 +316,12 @@ impl WaitArgs { } /// The deployment to wait for: `--deployment`, checked to be one of - /// `environment`'s, or the newest one its first page lists (see - /// `DeploymentSummary::newest`). + /// `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(PAGE_SIZE)) - .await?; - return DeploymentSummary::newest(&page.items) - .map(|deployment| deployment.operation.id.clone()) + 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 bdbb984cf..c90a36ec6 100644 --- a/apps/piquelctl/src/environments.rs +++ b/apps/piquelctl/src/environments.rs @@ -6,20 +6,22 @@ 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::{ Console, TaskOutcome, reports::{DeletionReport, EnvironmentRow, EnvironmentShowReport, Named, PromotionReport}, }, - support::{PAGE_SIZE, join_or, retry_transport}, + support::{join_or, retry_transport}, }; use clap::{Args, Subcommand, ValueEnum}; use piqueld_client::{ - ApplicationView, Client, ClientError, CreateEnvironmentRequest, DeploymentSummary, - EnvironmentBranchRequest, EnvironmentRequest, EnvironmentSourceRequest, EnvironmentStatusView, - EnvironmentView, Operation, PromoteRequest, Rollback, Visibility, edit::ApplicationEdit, + ApplicationView, Client, ClientError, CreateEnvironmentRequest, EnvironmentBranchRequest, + EnvironmentRequest, EnvironmentSourceRequest, EnvironmentStatusView, EnvironmentView, + Operation, PromoteRequest, Rollback, Visibility, edit::ApplicationEdit, }; // `env` subcommands; `///` on variants and fields is user-facing help. @@ -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,19 +1074,16 @@ struct Baseline { } impl Baseline { - /// The latest deployment's operation of environment `id`, if any: the - /// newest one its first page lists (see `DeploymentSummary::newest`). - async fn latest(client: &Client, id: &str) -> Result> { - let deployments = client - .deployment_summaries(id, None, Some(PAGE_SIZE)) - .await?; - Ok( - DeploymentSummary::newest(&deployments.items).map(|deployment| Self { - terminal: deployment.operation.state.terminal(), - attempt: deployment.operation.attempt, - operation: deployment.operation.id.clone(), - }), - ) + /// 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 9a13274f5..fcd7e2a87 100644 --- a/apps/piquelctl/tests/cli/environments.rs +++ b/apps/piquelctl/tests/cli/environments.rs @@ -459,7 +459,9 @@ fn deployment(state: &str) -> Value { } /// A deployment of `app-notes-01` created before `operation-01` but listed -/// above it: after a restart with the clock behind, it has the higher ID. +/// 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"); @@ -469,22 +471,23 @@ fn listed_first() -> Value { } /// Serves `env wait` for `app-notes-01`: its latest deployment is -/// `operation-01`, listed below [`listed_first`], 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![listed_first(), deployment(state)], None)) + Reply::json(page(vec![listed_first()], Some("next"))) } DEPLOYMENT => Reply::json(deployment(state)), TIMELINE_STREAM => Reply::timelines(&timelines), @@ -693,8 +696,8 @@ 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. A failed deployment it -/// left as is, the latest though listed below [`listed_first`], doesn't fail -/// the wait. +/// 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() { // (state before the stop, attempt and state after, run state, runtime @@ -726,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![listed_first(), deployment(before)], 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")) diff --git a/apps/piqueld-ui/src/browser/management/deployments/history.rs b/apps/piqueld-ui/src/browser/management/deployments/history.rs index 5164ecc42..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,10 +73,16 @@ impl History { } match result { Ok(page) => { - if let (Some(newest), Some(running)) = - (DeploymentSummary::newest(&page.items), 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/mod.rs b/apps/piqueld-ui/src/browser/management/deployments/mod.rs index 13a14765c..15375bcf5 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/mod.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/mod.rs @@ -15,8 +15,7 @@ use crate::browser::ui::key_values; use leptos::prelude::*; use std::fmt::Display; -/// Deployments the history asks for per page, and a deployment's page reads -/// to tell whether a newer one is listed. +/// Deployments the history asks for per page. const PAGE: u16 = 20; /// Definition list of the values of `${{ vars. }}` references. diff --git a/apps/piqueld-ui/src/browser/management/deployments/page.rs b/apps/piqueld-ui/src/browser/management/deployments/page.rs index 1e6c3b725..8afd88d32 100644 --- a/apps/piqueld-ui/src/browser/management/deployments/page.rs +++ b/apps/piqueld-ui/src/browser/management/deployments/page.rs @@ -1,6 +1,5 @@ //! One deployment's page: its progress and timeline, details, snapshot and //! attempts, and Restore. -use super::PAGE; use super::snapshot::DeploymentSnapshot; use crate::application::DEPLOYMENT_TABS; use crate::browser::format::timestamp; @@ -25,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>, } @@ -35,27 +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, listed) = futures_util::join!( - client.deployment(&environment, &operation), - client.deployment_summaries(&environment, None, Some(PAGE)), - ); + let deployment = Client::browser().deployment(&environment, &operation).await; if !alive.get() { return; } - match deployment.and_then(|deployment| Ok((deployment, listed?))) { - Ok((deployment, listed)) => { - self.newer.set(deployment.superseded_in(&listed.items)); + match deployment { + Ok(deployment) => { self.deployment.set(Some(deployment)); self.error.set(None); } @@ -165,7 +155,7 @@ pub(in crate::browser::management) fn DeploymentPage(operation: String) -> impl {move || progress.with(|p| p.as_ref().map(status_pill))}
- +
@@ -219,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| { @@ -234,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 8e73b5495..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 @@ -36,11 +37,16 @@ pub trait DeploymentFacts { u64::try_from(operation.finished_at_ms? - started).ok() } - /// Whether `listed` holds a deployment created after it (see - /// `DeploymentSummary::newest`), whatever their order. - fn superseded_in(&self, listed: &[DeploymentSummary]) -> bool { - DeploymentSummary::newest(listed) - .is_some_and(|newest| newest.operation.recency() > self.operation().recency()) + /// 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 + }) } } @@ -301,20 +307,25 @@ mod tests { assert_eq!(built.duration_ms(), Some(38_000)); } - /// After a restart with the clock behind, the current deployment can - /// list below an older one with a higher ID: that one isn't newer, so - /// Restore isn't offered on the current deployment. + /// Only another deployment, the environment's latest, supersedes one: not + /// the deployment itself, a deletion, or another environment's operation. #[test] - fn only_a_deployment_created_later_supersedes_one() { - let mut current = deployment("operation-1", true, true); - current.operation.created_at_ms = 2_000; - let mut older = summary("operation-9", false, false); - older.operation.created_at_ms = 1_000; - let listed = vec![older, current.clone().into()]; - assert!(!current.superseded_in(&listed)); - let mut failed = summary("operation-0", false, false); - failed.operation.created_at_ms = 3_000; - assert!(current.superseded_in(&[listed, vec![failed]].concat())); + 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] diff --git a/crates/piqueld-core/src/api/deployments.rs b/crates/piqueld-core/src/api/deployments.rs index 793e9cf05..a415981e5 100644 --- a/crates/piqueld-core/src/api/deployments.rs +++ b/crates/piqueld-core/src/api/deployments.rs @@ -113,17 +113,6 @@ impl From for DeploymentSummary { } } -impl DeploymentSummary { - /// The newest of `deployments` by [`Operation::recency`], which need not - /// be the first one a page lists. - #[must_use] - pub fn newest(deployments: &[Self]) -> Option<&Self> { - deployments - .iter() - .max_by(|a, b| a.operation.recency().cmp(&b.operation.recency())) - } -} - /// A page of an environment's deployments, newest first, in the /// [`DeploymentListView`] asked for. #[derive(Clone, Debug, Deserialize, Serialize)] diff --git a/crates/piqueld-core/src/api/tests.rs b/crates/piqueld-core/src/api/tests.rs index d5cb46cff..7e4029bff 100644 --- a/crates/piqueld-core/src/api/tests.rs +++ b/crates/piqueld-core/src/api/tests.rs @@ -1,6 +1,6 @@ use super::{ - ApplicationView, BuildLogChunk, DeploymentPage, DeploymentSummary, EnvironmentAccess, - EnvironmentView, LogRecord, MountedSecret, SecretAccess, SecretMetadata, StoredSecret, + ApplicationView, BuildLogChunk, DeploymentPage, EnvironmentAccess, EnvironmentView, LogRecord, + MountedSecret, SecretAccess, SecretMetadata, StoredSecret, }; use crate::{ApplicationId, EnvironmentId, EnvironmentName, EnvironmentSource}; @@ -139,37 +139,3 @@ fn deployment_pages_are_documented_as_any_of() { assert!(schema.get("oneOf").is_none()); assert_eq!(schema["anyOf"].as_array().map(Vec::len), Some(2)); } - -/// Deployment `id`'s summary, created at `created_at_ms`. -fn summary(id: &str, created_at_ms: i64) -> DeploymentSummary { - serde_json::from_value(serde_json::json!({ - "operation": { - "id": id, "environment_id": "app-notes-01", "kind": "apply", - "generation": 1, "attempt": 1, "state": "succeeded", - "created_at_ms": created_at_ms, "updated_at_ms": created_at_ms, - }, - "succeeded_at_ms": created_at_ms, - "current_target": false, - "last_successful": false, - })) - .expect("deployment summary") -} - -/// After a restart with the clock behind, an older deployment can have the -/// higher ID and list first: the newest is the latest created, and of two -/// created in the same millisecond, the higher ID. -#[test] -fn the_newest_deployment_is_the_latest_created_not_the_first_listed() { - let newest = |listed: &[DeploymentSummary]| { - DeploymentSummary::newest(listed).map(|newest| newest.operation.id.clone()) - }; - let skewed = [ - summary("operation-f", 1), - summary("operation-a", 3), - summary("operation-b", 2), - ]; - assert_eq!(newest(&skewed).as_deref(), Some("operation-a")); - let tied = [summary("operation-a", 3), summary("operation-b", 3)]; - assert_eq!(newest(&tied).as_deref(), Some("operation-b")); - assert_eq!(newest(&[]), None); -} diff --git a/crates/piqueld-core/src/operation.rs b/crates/piqueld-core/src/operation.rs index 3c4952c2e..121dbccea 100644 --- a/crates/piqueld-core/src/operation.rs +++ b/crates/piqueld-core/src/operation.rs @@ -135,16 +135,6 @@ impl Operation { attempt > self.attempt || (attempt == self.attempt && self.state != OperationState::Requested) } - - /// How recent it is, as the store orders an environment's operations to - /// pick its latest: by creation time, then ID. IDs alone order only the - /// pages of a list, because they are monotonic within one daemon process: - /// after a restart with the clock behind, an older operation can have the - /// higher ID. - #[must_use] - pub fn recency(&self) -> (i64, &str) { - (self.created_at_ms, &self.id) - } } string_enum! {