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 <noreply@anthropic.com>
This commit is contained in:
1 parent
37e94b1ee6
commit
8d45a93d63
3 files changed
+128
-46
No files matched your search
@@ -384,9 +384,15 @@ async fn with_log_tail<T: TaskApi>(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<T: TaskApi>(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<T: TaskApi>(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: TaskApi, W: WorkspaceApi, R: RuntimeApi, C: Connector
|
||||
Ok(t) => 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<T: TaskApi, W: WorkspaceApi, R: RuntimeApi, C: Connector
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
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<ContainerTarget, String> {
|
||||
// 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<Pro
|
||||
let ctx = Reattach { generation, connection_id, region, sdk, who };
|
||||
if let Err(e) = reattach(&project, *task, ctx, &store).await {
|
||||
log::warn!("Project {}: could not re-open the tunnel to its task: {e}", project.id);
|
||||
tunnels::set_pending(&project.id, false);
|
||||
tunnels::end_reattach(&project.id, generation);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -947,7 +951,7 @@ async fn reattach(
|
||||
};
|
||||
if !reattach_still_wanted(store, &project.id, &task.arn) {
|
||||
tunnel.forward.close().await;
|
||||
tunnels::set_pending(&project.id, false);
|
||||
tunnels::end_reattach(&project.id, ctx.generation);
|
||||
log::info!("Project {}: stopped or removed while re-attaching; tunnel closed", project.id);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ struct Fake {
|
||||
secret_json: Mutex<Option<String>>,
|
||||
/// 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<Vec<Option<String>>>,
|
||||
}
|
||||
@@ -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<Vec<String>, 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"))]);
|
||||
}
|
||||
@@ -62,8 +62,9 @@ struct Registry {
|
||||
stopped: HashSet<String>,
|
||||
/// Projects whose tunnel is being re-opened in the background.
|
||||
pending: HashSet<String>,
|
||||
/// 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<String, u64>,
|
||||
}
|
||||
|
||||
@@ -91,6 +92,7 @@ fn notify() {
|
||||
pub fn register(project_id: &str, tunnel: LiveTunnel) -> Option<LiveTunnel> {
|
||||
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<LiveTunnel> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user