From 8d45a93d630b50cfb352a8b790864412929b3032 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 15 Nov 2026 09:30:17 -0800 Subject: [PATCH] fix(aws): a start cancels a pending re-attach; keep an unstoppable task recorded ensure_started cancels a background re-attach instead of waiting for it, and every register bumps the project's generation, so a late re-attach can never replace a newer tunnel. A task StopTask refused after a failed start keeps its ARN. A re-attach that gives up clears the pending flag only if still current; close_if_task checks and takes under one lock. Co-Authored-By: Claude Opus 5.5 --- app/src-tauri/src/host/aws_host.rs | 34 ++++--- app/src-tauri/src/host/aws_host/tests.rs | 27 ++++++ app/src-tauri/src/host/tunnels.rs | 113 ++++++++++++++++------- 3 files changed, 128 insertions(+), 46 deletions(-) diff --git a/app/src-tauri/src/host/aws_host.rs b/app/src-tauri/src/host/aws_host.rs index 4a58e98..a170cb6 100644 --- a/app/src-tauri/src/host/aws_host.rs +++ b/app/src-tauri/src/host/aws_host.rs @@ -384,9 +384,15 @@ async fn with_log_tail(api: &T, logs: &TaskLogs, arn: &str, err: Str } /// Stop a task this start ran, best-effort, so nothing billed is orphaned. -async fn stop_created(api: &T, cluster: &str, arn: &str) { - if let Err(e) = api.stop_task(cluster, arn, STOP_REASON).await { - log::warn!("Could not stop task {arn} after a failed start: {e}"); +/// `true` when StopTask succeeded; otherwise the task may still run and its +/// ARN must stay recorded. +async fn stop_created(api: &T, cluster: &str, arn: &str) -> bool { + match api.stop_task(cluster, arn, STOP_REASON).await { + Ok(()) => true, + Err(e) => { + log::warn!("Could not stop task {arn} after a failed start: {e}"); + false + } } } @@ -485,8 +491,9 @@ pub async fn start_core t, Err(e) => { let msg = with_log_tail(tasks, &logs, &arn, e.to_string()).await; - stop_created(tasks, &env.cluster_arn, &arn).await; - (inp.on_task)(None); + if stop_created(tasks, &env.cluster_arn, &arn).await { + (inp.on_task)(None); + } return Err(msg); } }; @@ -522,8 +529,7 @@ pub async fn start_core { - if created { - stop_created(tasks, &env.cluster_arn, &task.arn).await; + if created && stop_created(tasks, &env.cluster_arn, &task.arn).await { (inp.on_task)(None); } Err(e) @@ -551,12 +557,10 @@ pub async fn ensure_started( store: &ProjectsStore, progress: &(dyn Fn(&str) + Send + Sync), ) -> Result { - // A background re-attach (after a restart) is opening the tunnel: wait - // for it rather than racing it with a second one. - if tunnels::is_pending(&project.id) { - progress(PROGRESS_CONNECTING); - tunnels::wait_endpoint(&project.id, REATTACH_WAIT).await; - } + // A background re-attach (after a restart) may be opening a tunnel: + // cancel it, this start attaches itself. Its tunnel, if it gets one, is + // refused by the registry and closed. + tunnels::cancel_reattach(&project.id); // Already connected and answering: nothing to do. if let Some(ep) = tunnels::get_endpoint(&project.id) { if matches!(agent::is_running(&ep).await, Ok(true)) { @@ -884,7 +888,7 @@ pub async fn reconcile(project: &Project, settings: &AppSettings, store: Arc>, /// A losing start rotates the secret's token while this one connects. rotated_by_loser: bool, + /// StopTask is refused (expired credentials, say). + stop_fails: bool, /// What `on_task` was told, in order. recorded: Mutex>>, } @@ -129,6 +131,9 @@ impl TaskApi for Fake { } async fn stop_task(&self, _c: &str, arn: &str, reason: &str) -> Result<(), AwsError> { self.log(format!("stop {arn} {reason}")); + if self.stop_fails { + return Err(AwsError::Other { message: "ExpiredToken".into() }); + } Ok(()) } async fn log_tail(&self, _g: &str, _s: &str, _l: i32) -> Result, AwsError> { @@ -671,3 +676,25 @@ fn a_start_records_its_task_and_keeps_the_stored_handles_it_does_not_know() { let a = store.get(&p.id).unwrap().aws.unwrap(); assert_eq!((a.task_arn, a.access_point_id.as_deref()), (None, Some("fsap-old"))); } + +#[tokio::test] +async fn a_task_that_could_not_be_stopped_after_a_failed_start_stays_recorded() { + let p = aws_project(StorageMode::Ephemeral); + let fake = Fake { + run: Some(task(&p, "slow", "PENDING", false)), + stop_fails: true, + ..Default::default() + }; + assert!(start(&fake, &p).await.0.is_err()); + assert!(fake.called("stop")); + assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("slow"))], "still findable"); + + let fake = Fake { + run: Some(task(&p, "new", "RUNNING", true)), + connect_fails: true, + stop_fails: true, + ..Default::default() + }; + assert!(start(&fake, &p).await.0.is_err()); + assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("new"))]); +} diff --git a/app/src-tauri/src/host/tunnels.rs b/app/src-tauri/src/host/tunnels.rs index 831dff2..49c760e 100644 --- a/app/src-tauri/src/host/tunnels.rs +++ b/app/src-tauri/src/host/tunnels.rs @@ -62,8 +62,9 @@ struct Registry { stopped: HashSet, /// Projects whose tunnel is being re-opened in the background. pending: HashSet, - /// Bumped by every [`close`] (a stop or remove): a background re-attach - /// that began under an older generation must not register. + /// Bumped by every [`close`] (a stop or remove), every [`register`] (a + /// start's own tunnel) and [`cancel_reattach`]: a background re-attach + /// that began under an older generation must never register. generation: HashMap, } @@ -91,6 +92,7 @@ fn notify() { pub fn register(project_id: &str, tunnel: LiveTunnel) -> Option { let old = { let mut r = lock(); + *r.generation.entry(project_id.to_string()).or_default() += 1; r.stopped.remove(tunnel.endpoint.base_url.as_str()); r.pending.remove(project_id); r.live.insert(project_id.to_string(), tunnel) @@ -171,25 +173,57 @@ pub fn register_if_current( /// [`close`], but only when the registered tunnel leads to `task_arn` (a /// death report about an older task must not close a newer one's tunnel). pub async fn close_if_task(project_id: &str, task_arn: &str) { - let matches = lock().live.get(project_id).is_some_and(|t| t.task_arn == task_arn); - if matches { - close(project_id).await; + let taken = { + let mut r = lock(); + if !r.live.get(project_id).is_some_and(|t| t.task_arn == task_arn) { + return; + } + take(&mut r, project_id) + }; + notify(); + if let Some(t) = taken { + t.forward.close().await; } } +/// Under the lock: invalidate a re-attach in flight and take the tunnel out. +fn take(r: &mut Registry, project_id: &str) -> Option { + r.pending.remove(project_id); + *r.generation.entry(project_id.to_string()).or_default() += 1; + let t = r.live.remove(project_id); + if let Some(ref t) = t { + r.stopped.remove(t.endpoint.base_url.as_str()); + } + t +} + +/// A start is about to attach itself: any background re-attach in flight +/// is cancelled (it will hand its tunnel back and close it). +pub fn cancel_reattach(project_id: &str) { + { + let mut r = lock(); + r.pending.remove(project_id); + *r.generation.entry(project_id.to_string()).or_default() += 1; + } + notify(); +} + +/// A background re-attach that began at `generation` gave up: clear the +/// pending flag, unless something newer has taken over since. +pub fn end_reattach(project_id: &str, generation: u64) { + { + let mut r = lock(); + if r.generation.get(project_id).copied().unwrap_or_default() == generation { + r.pending.remove(project_id); + } + } + notify(); +} + /// Take the project's tunnel out and close it, and invalidate a background /// re-attach in flight. pub async fn close(project_id: &str) { - let taken = { - let mut r = lock(); - r.pending.remove(project_id); - *r.generation.entry(project_id.to_string()).or_default() += 1; - let t = r.live.remove(project_id); - if let Some(ref t) = t { - r.stopped.remove(t.endpoint.base_url.as_str()); - } - t - }; + let taken = take(&mut lock(), project_id); notify(); if let Some(t) = taken { t.forward.close().await; @@ -221,19 +255,6 @@ pub fn is_stopped(target_id: &str) -> bool { lock().stopped.contains(target_id) } -/// A background re-attach for this project has begun / ended without a tunnel. -pub fn set_pending(project_id: &str, pending: bool) { - { - let mut r = lock(); - if pending { - r.pending.insert(project_id.to_string()); - } else { - r.pending.remove(project_id); - } - } - notify(); -} - pub fn is_pending(project_id: &str) -> bool { lock().pending.contains(project_id) } @@ -348,6 +369,36 @@ pub(crate) mod tests { close(&p).await; } + #[tokio::test] + async fn a_starts_tunnel_survives_a_reattach_that_finishes_after_it() { + let closes = Arc::new(AtomicUsize::new(0)); + // Start cancels the pending re-attach, then registers its own. + let p = pid("start-wins"); + let g = begin_reattach(&p); + cancel_reattach(&p); + assert!(!is_pending(&p)); + register(&p, fake_tunnel(61010, closes.clone())); + let late = register_if_current(&p, g, fake_tunnel(61011, closes.clone())); + late.err().expect("the late re-attach is refused").forward.close().await; + assert_eq!(get_endpoint(&p).unwrap().base_url.port(), Some(61010), "Start's tunnel stays"); + assert_eq!(closes.load(Ordering::SeqCst), 1, "only the late tunnel was closed"); + // A stale end of that re-attach does not clear a newer one's pending flag. + let g2 = begin_reattach(&p); + end_reattach(&p, g); + assert!(is_pending(&p)); + end_reattach(&p, g2); + assert!(!is_pending(&p)); + close(&p).await; + + // Even without a cancel, a plain register makes an older re-attach stale. + let p = pid("register-bumps"); + let g = begin_reattach(&p); + register(&p, fake_tunnel(61012, closes.clone())); + assert!(register_if_current(&p, g, fake_tunnel(61013, closes.clone())).is_err()); + assert_eq!(get_endpoint(&p).unwrap().base_url.port(), Some(61012)); + close(&p).await; + } + #[tokio::test] async fn a_death_report_closes_only_the_tunnel_of_the_task_that_died() { let closes = Arc::new(AtomicUsize::new(0)); @@ -364,7 +415,7 @@ pub(crate) mod tests { async fn waiting_for_an_endpoint_ends_when_it_is_registered_or_the_reattach_gives_up() { let p = pid("wait"); assert!(wait_endpoint(&p, Duration::from_secs(5)).await.is_none(), "nothing pending"); - set_pending(&p, true); + begin_reattach(&p); let p2 = p.clone(); let waiter = tokio::spawn(async move { wait_endpoint(&p2, Duration::from_secs(5)).await }); tokio::time::sleep(Duration::from_millis(20)).await; @@ -372,11 +423,11 @@ pub(crate) mod tests { assert_eq!(waiter.await.unwrap().unwrap().base_url.port(), Some(61004)); close(&p).await; - set_pending(&p, true); + let g = begin_reattach(&p); let p2 = p.clone(); let waiter = tokio::spawn(async move { wait_endpoint(&p2, Duration::from_secs(5)).await }); tokio::time::sleep(Duration::from_millis(20)).await; - set_pending(&p, false); + end_reattach(&p, g); assert!(waiter.await.unwrap().is_none()); } }