Speed up remote control reconnects when a controller is active (#63471)

## Why

A silent WebSocket can leave an active controller waiting up to 60 seconds for the host to detect the outage. Reconnect backoff from earlier failures can delay recovery further.

## What changed

- Reconnect after 30 seconds without incoming WebSocket frames when a live controller is present. Keep the 60-second pong timeout when only the relay client is connected.
- Start at the initial jittered delay for the first five retries when controller activity resumes after a period with no live controllers, then increase backoff if failures continue.
- Preserve live streams and their terminals when a sequenced `initialize` request is replayed. Ignore cleanup from an old writer if a replacement connection has reused the stream.

## Testing

Cover the attached and relay-only timeout paths, retry backoff across controller lifecycle changes, and writer cleanup after stream reuse.

GitOrigin-RevId: 6618e7bca4852b05d41b18e53fe49efcb2b6db70
This commit is contained in:
Anton Panasenko
2026-11-23 23:55:35 +00:00
committed by copyberry
parent d4af2452f7
commit 6a33df4e0a
3 changed files with 311 additions and 50 deletions
@@ -44,15 +44,44 @@ struct ClientState {
pub(crate) struct ClientTracker {
pub(super) auth: Option<crate::ConnectionAuth>,
/// Whether the host has retried since it last had no live controllers.
pub(super) retried_with_controller: bool,
clients: HashMap<(ClientId, StreamId), ClientState>,
legacy_stream_ids: HashMap<ClientId, StreamId>,
join_set: JoinSet<(ClientId, StreamId)>,
join_set: JoinSet<(ConnectionId, (ClientId, StreamId))>,
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
transport_event_tx: mpsc::Sender<TransportEvent>,
shutdown_token: CancellationToken,
}
impl ClientTracker {
pub(super) fn has_controller(&self) -> bool {
self.has_controller_at(Instant::now())
}
fn has_controller_at(&self, now: Instant) -> bool {
self.clients
.iter()
.any(|((id, _), client)| is_live_controller(id, client, now))
}
// Sample liveness at the same instant that starts or refreshes a client.
// A controller can expire while we await space for ConnectionOpened.
fn begin_client_activity(&mut self) -> Instant {
let now = Instant::now();
if self.retried_with_controller && !self.has_controller_at(now) {
self.retried_with_controller = false;
}
now
}
fn refresh_client(&mut self, key: &(ClientId, StreamId)) -> Option<&mut ClientState> {
let now = self.begin_client_activity();
let client = self.clients.get_mut(key)?;
client.last_activity_at = now;
Some(client)
}
pub(crate) fn new(
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
transport_event_tx: mpsc::Sender<TransportEvent>,
@@ -60,6 +89,7 @@ impl ClientTracker {
) -> Self {
Self {
auth: None,
retried_with_controller: false,
clients: HashMap::new(),
legacy_stream_ids: HashMap::new(),
join_set: JoinSet::new(),
@@ -71,9 +101,17 @@ impl ClientTracker {
pub(crate) async fn bookkeep_join_set(&mut self) -> Option<(ClientId, StreamId)> {
while let Some(join_result) = self.join_set.join_next().await {
let Ok(client_key) = join_result else {
let Ok((connection_id, client_key)) = join_result else {
continue;
};
// A new connection can reuse this stream before its old writer exits.
if self
.clients
.get(&client_key)
.is_some_and(|client| client.connection_id != connection_id)
{
continue;
}
return Some(client_key);
}
futures::future::pending().await
@@ -132,24 +170,34 @@ impl ClientTracker {
let client_key = (client_id.clone(), stream_id.clone());
match event {
ClientEvent::ClientMessage { message } => {
let now = Instant::now();
let existing = self.clients.get_mut(&client_key);
let replacing_live_controller = is_initialize
&& existing
.as_deref()
.is_some_and(|client| is_live_controller(&client_id, client, now));
if let Some(seq_id) = seq_id
&& let Some(client) = self.clients.get(&client_key)
&& let Some(client) = existing
&& client
.last_inbound_seq_id
.is_some_and(|last_seq_id| last_seq_id >= seq_id)
&& !is_initialize
{
return Ok(());
if !is_initialize {
return Ok(());
}
// Desktop starts a new stream for each fresh initialize. A replay
// keeps the live stream active without closing its terminals.
if !is_legacy_stream_id && replacing_live_controller {
client.last_activity_at = now;
return Ok(());
}
}
if is_initialize && self.clients.contains_key(&client_key) {
self.close_client(&client_key).await?;
}
if let Some(connection_id) = self.clients.get_mut(&client_key).map(|client| {
client.last_activity_at = Instant::now();
client.connection_id
}) {
if !is_initialize {
let Some(client) = self.refresh_client(&client_key) else {
return Ok(());
};
let connection_id = client.connection_id;
self.send_transport_event(TransportEvent::IncomingMessage {
connection_id,
message,
@@ -159,8 +207,8 @@ impl ClientTracker {
return Ok(());
}
if !is_initialize {
return Ok(());
if self.clients.contains_key(&client_key) {
self.close_client(&client_key).await?;
}
let connection_id = next_connection_id();
@@ -178,6 +226,7 @@ impl ClientTracker {
let (status_tx, status_rx) = watch::channel(PongStatus::Active);
self.join_set.spawn(Self::run_client_outbound(
connection_id,
client_id.clone(),
stream_id.clone(),
self.server_event_tx.clone(),
@@ -185,12 +234,19 @@ impl ClientTracker {
status_rx,
disconnect_token.clone(),
));
// A legacy reinitialize replaces the connection on the same live
// stream. Its temporary removal is not a gap in controller activity.
let last_activity_at = if replacing_live_controller {
Instant::now()
} else {
self.begin_client_activity()
};
self.clients.insert(
client_key.clone(),
ClientState {
connection_id,
disconnect_token,
last_activity_at: Instant::now(),
last_activity_at,
last_inbound_seq_id: None,
status_tx,
},
@@ -220,8 +276,7 @@ impl ClientTracker {
}
ClientEvent::ClientMessageChunk { .. } | ClientEvent::Ack { .. } => Ok(()),
ClientEvent::Ping => {
if let Some(client) = self.clients.get_mut(&client_key) {
client.last_activity_at = Instant::now();
if let Some(client) = self.refresh_client(&client_key) {
let _ = client.status_tx.send(PongStatus::Active);
return Ok(());
}
@@ -245,13 +300,14 @@ impl ClientTracker {
}
async fn run_client_outbound(
connection_id: ConnectionId,
client_id: ClientId,
stream_id: StreamId,
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
mut writer_rx: mpsc::Receiver<QueuedOutgoingMessage>,
mut status_rx: watch::Receiver<PongStatus>,
disconnect_token: CancellationToken,
) -> (ClientId, StreamId) {
) -> (ConnectionId, (ClientId, StreamId)) {
loop {
let (event, write_complete_tx) = tokio::select! {
_ = disconnect_token.cancelled() => {
@@ -289,7 +345,8 @@ impl ClientTracker {
break;
}
}
(client_id, stream_id)
disconnect_token.cancel();
(connection_id, (client_id, stream_id))
}
pub(crate) async fn close_expired_clients(
@@ -438,6 +495,13 @@ fn remote_control_message_starts_connection(message: &JSONRPCMessage) -> bool {
)
}
fn is_live_controller(id: &ClientId, client: &ClientState, now: Instant) -> bool {
// The relay also initializes its own client for each online host.
!id.0.starts_with("backend_")
&& !client.disconnect_token.is_cancelled()
&& remote_control_client_is_alive(client, now)
}
fn remote_control_client_is_alive(client: &ClientState, now: Instant) -> bool {
now.duration_since(client.last_activity_at) < REMOTE_CONTROL_CLIENT_IDLE_TIMEOUT
}
@@ -74,6 +74,9 @@ const REMOTE_CONTROL_WEBSOCKET_PING_INTERVAL: std::time::Duration =
std::time::Duration::from_secs(10);
const REMOTE_CONTROL_WEBSOCKET_PONG_TIMEOUT: std::time::Duration =
std::time::Duration::from_secs(60);
// Reconnect a controller after three heartbeat intervals of complete silence.
const REMOTE_CONTROL_ACTIVE_IDLE_TIMEOUT: std::time::Duration =
REMOTE_CONTROL_WEBSOCKET_PING_INTERVAL.saturating_mul(3);
const REMOTE_CONTROL_ACCOUNT_ID_RETRY_INTERVAL: std::time::Duration =
std::time::Duration::from_secs(1);
const REMOTE_CONTROL_RECONNECT_BACKOFF_INITIAL: std::time::Duration =
@@ -547,7 +550,7 @@ impl RemoteControlWebsocket {
self.status_publisher
.publish_status(RemoteControlConnectionStatus::Connecting);
// Spread automatic reconnects before token refresh or enrollment, too.
let reconnect_delay = next_reconnect_delay(&mut self.reconnect_attempt);
let reconnect_delay = self.next_reconnect_delay().await;
tokio::select! {
biased;
_ = self.shutdown_token.cancelled() => break,
@@ -687,6 +690,11 @@ impl RemoteControlWebsocket {
}
}
async fn next_reconnect_delay(&mut self) -> std::time::Duration {
let mut clients = self.client_tracker.lock().await;
next_reconnect_delay(&mut self.reconnect_attempt, &mut clients)
}
async fn wait_until_enabled(&mut self) -> bool {
tokio::select! {
_ = self.shutdown_token.cancelled() => false,
@@ -822,7 +830,7 @@ impl RemoteControlWebsocket {
self.status_publisher
.publish_status(RemoteControlConnectionStatus::Errored);
let reconnect_attempt = self.reconnect_attempt.saturating_add(1);
let reconnect_delay = next_reconnect_delay(&mut self.reconnect_attempt);
let reconnect_delay = self.next_reconnect_delay().await;
let reconnect_delay = server_retry_delay
.map_or(reconnect_delay, |delay| reconnect_delay.max(delay));
let enrollment = self.current_enrollment.snapshot();
@@ -1187,11 +1195,23 @@ impl RemoteControlWebsocket {
let mut idle_sweep_interval = tokio::time::interval(REMOTE_CONTROL_IDLE_SWEEP_INTERVAL);
idle_sweep_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
let pong_deadline = tokio::time::sleep(pong_timeout);
tokio::pin!(pong_deadline);
let idle_deadline = tokio::time::sleep(REMOTE_CONTROL_ACTIVE_IDLE_TIMEOUT);
tokio::pin!(pong_deadline, idle_deadline);
loop {
let incoming_message = tokio::select! {
_ = shutdown_token.cancelled() => return Ok(()),
_ = &mut idle_deadline => {
// A controller may have expired or disconnected during the wait.
if !client_tracker.has_controller() {
idle_deadline.as_mut().reset(tokio::time::Instant::now() + REMOTE_CONTROL_ACTIVE_IDLE_TIMEOUT);
continue;
}
return Err(io::Error::new(
ErrorKind::TimedOut,
"remote control websocket idle timeout",
));
}
_ = &mut pong_deadline => {
return Err(io::Error::new(
ErrorKind::TimedOut,
@@ -1239,6 +1259,9 @@ impl RemoteControlWebsocket {
}
}
};
idle_deadline
.as_mut()
.reset(tokio::time::Instant::now() + REMOTE_CONTROL_ACTIVE_IDLE_TIMEOUT);
let (client_envelope, wire_size_bytes) = match incoming_message {
Ok(tungstenite::Message::Text(text)) => {
let wire_size_bytes = text.len();
@@ -1404,8 +1427,20 @@ async fn wait_for_auth_change(
auth_change_rx.changed().await
}
fn next_reconnect_delay(reconnect_attempt: &mut u64) -> std::time::Duration {
let exponent = u32::try_from(*reconnect_attempt).unwrap_or(u32::MAX);
fn next_reconnect_delay(
reconnect_attempt: &mut u64,
clients: &mut ClientTracker,
) -> std::time::Duration {
let has_controller = clients.has_controller();
if has_controller && !clients.retried_with_controller {
*reconnect_attempt = 0;
}
clients.retried_with_controller = has_controller;
// Give an attached controller five attempts at the initial jittered
// delay before increasing the backoff for a sustained outage.
let extra_attempts = if has_controller { 4 } else { 0 };
let exponent =
u32::try_from(reconnect_attempt.saturating_sub(extra_attempts)).unwrap_or(u32::MAX);
let backoff = REMOTE_CONTROL_RECONNECT_BACKOFF_INITIAL
.saturating_mul(2_u32.saturating_pow(exponent))
.min(REMOTE_CONTROL_RECONNECT_BACKOFF_CAP);
@@ -2900,6 +2935,29 @@ mod tests {
#[tokio::test]
async fn run_websocket_reader_inner_times_out_without_pong_frames() {
assert_eq!(
reader_timeout_without_pongs(/*attached*/ false).await,
Duration::from_secs(60)
);
assert_eq!(
reader_timeout_without_pongs(/*attached*/ true).await,
Duration::from_secs(30)
);
}
pub(super) async fn initialize_client(clients: &mut ClientTracker, id: &str) {
let initialize = serde_json::from_value(serde_json::json!({
"type": "client_message",
"client_id": id,
"stream_id": "stream",
"seq_id": 1,
"message": {"id": 1, "method": "initialize", "params": {}}
}))
.unwrap();
clients.handle_message(initialize).await.unwrap();
}
async fn reader_timeout_without_pongs(attached: bool) -> Duration {
let (client_stream, _server_stream) = connected_websocket_pair().await;
let (_websocket_writer, websocket_reader) = client_stream.split();
let (outbound_buffer, _used_rx) = BoundedOutboundBuffer::new();
@@ -2914,28 +2972,34 @@ mod tests {
let (transport_event_tx, _transport_event_rx) =
mpsc::channel(super::super::CHANNEL_CAPACITY);
let shutdown_token = CancellationToken::new();
let client_tracker = Arc::new(Mutex::new(ClientTracker::new(
server_event_tx,
transport_event_tx,
&shutdown_token,
)));
let mut client_tracker =
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
let err = timeout(
Duration::from_secs(5),
RemoteControlWebsocket::run_websocket_reader_inner(
client_tracker,
state,
websocket_reader,
Duration::from_millis(100),
shutdown_token,
),
initialize_client(&mut client_tracker, "backend_host").await;
if attached {
initialize_client(&mut client_tracker, "controller").await;
}
tokio::time::pause();
let start = tokio::time::Instant::now();
let err = RemoteControlWebsocket::run_websocket_reader_inner(
Arc::new(Mutex::new(client_tracker)),
state,
websocket_reader,
super::REMOTE_CONTROL_WEBSOCKET_PONG_TIMEOUT,
shutdown_token,
)
.await
.expect("reader should time out waiting for pong")
.expect_err("missing pong should fail the websocket reader");
let elapsed = start.elapsed();
tokio::time::resume();
assert_eq!(err.kind(), ErrorKind::TimedOut);
assert_eq!(err.to_string(), "remote control websocket pong timeout");
let expected_error = if attached {
"remote control websocket idle timeout"
} else {
"remote control websocket pong timeout"
};
assert_eq!(err.to_string(), expected_error);
Duration::from_secs(elapsed.as_secs())
}
#[test]
@@ -3,6 +3,7 @@
use super::tests::TEST_INSTALLATION_ID;
use super::tests::TEST_REMOTE_CONTROL_SERVER_TOKEN;
use super::tests::enabled_desired_state_sender;
use super::tests::initialize_client;
use super::tests::remote_control_auth_manager;
use super::tests::remote_control_enrollment;
use super::tests::remote_control_state_runtime;
@@ -137,7 +138,7 @@ async fn assert_conflict_recovery(subscribe_cursor: Option<&str>) {
assert!(matches!(outcome, ConnectOutcome::Connected(_)));
assert_eq!(websocket.reconnect_attempt, 11);
assert!(
next_reconnect_delay(&mut websocket.reconnect_attempt) >= Duration::from_secs(15),
websocket.next_reconnect_delay().await >= Duration::from_secs(15),
"a successful handshake must not reset backoff before the connection stays healthy"
);
assert_eq!(current_enrollment.snapshot(), Some(enrollment));
@@ -150,17 +151,149 @@ async fn assert_conflict_recovery(subscribe_cursor: Option<&str>) {
}
}
#[test]
fn reconnect_backoff_stays_capped_during_sustained_failures() {
let mut reconnect_attempt = 0;
for max_delay in [5, 10, 20] {
let delay = next_reconnect_delay(&mut reconnect_attempt);
#[tokio::test]
async fn fast_retries_restart_when_the_first_controller_attaches() {
let (server_tx, _server_rx) = mpsc::channel(/*buffer*/ 32);
let (transport_tx, transport_rx) = mpsc::channel(/*buffer*/ 32);
let mut clients = ClientTracker::new(server_tx, transport_tx, &CancellationToken::new());
let mut attempt = 0;
let fast_retries = [5, 5, 5, 5, 5, 10, 20];
initialize_client(&mut clients, "backend_host").await;
assert_reconnect_backoff(&mut attempt, &mut clients, &[5, 10, 20, 30, 30, 30, 30]);
initialize_client(&mut clients, "first").await;
assert_reconnect_backoff(&mut attempt, &mut clients, &fast_retries);
// Replaying initialize must preserve the original connection and its backoff.
tokio::time::pause();
tokio::time::advance(Duration::from_secs(599)).await;
let events_before_replay = transport_rx.len();
initialize_client(&mut clients, "first").await;
assert_eq!(transport_rx.len(), events_before_replay);
tokio::time::advance(Duration::from_secs(1)).await;
assert!(clients.has_controller());
assert!(next_reconnect_delay(&mut attempt, &mut clients) >= Duration::from_secs(15));
initialize_client(&mut clients, "second").await;
let stream = StreamId("stream".to_string());
clients
.close_client(&(ClientId("first".to_string()), stream.clone()))
.await
.unwrap();
assert!(next_reconnect_delay(&mut attempt, &mut clients) >= Duration::from_secs(15));
// The last controller leaves and a new one joins without an intervening retry.
clients
.close_client(&(ClientId("second".to_string()), stream))
.await
.unwrap();
initialize_client(&mut clients, "replacement").await;
assert_reconnect_backoff(&mut attempt, &mut clients, &fast_retries);
// A controller may initialize before the first idle sweep after a long outage.
tokio::time::advance(Duration::from_secs(600)).await;
assert!(!clients.has_controller());
initialize_client(&mut clients, "after-expiry").await;
assert_reconnect_backoff(&mut attempt, &mut clients, &fast_retries);
tokio::time::advance(Duration::from_secs(600)).await;
let ping = serde_json::from_value(serde_json::json!({
"type": "ping", "client_id": "after-expiry", "stream_id": "stream"
}))
.unwrap();
clients.handle_message(ping).await.unwrap();
assert_reconnect_backoff(&mut attempt, &mut clients, &fast_retries);
}
#[tokio::test]
async fn legacy_reinitialization_does_not_renew_fast_retries() {
let (server_tx, _server_rx) = mpsc::channel(/*buffer*/ 32);
let (transport_tx, _transport_rx) = mpsc::channel(/*buffer*/ 32);
let mut clients = ClientTracker::new(server_tx, transport_tx, &CancellationToken::new());
let initialize: ClientEnvelope = serde_json::from_value(serde_json::json!({
"type": "client_message",
"client_id": "legacy",
"message": {"id": 1, "method": "initialize", "params": {}}
}))
.unwrap();
let mut attempt = 0;
for _ in 0..7 {
clients.handle_message(initialize.clone()).await.unwrap();
next_reconnect_delay(&mut attempt, &mut clients);
}
assert!(next_reconnect_delay(&mut attempt, &mut clients) >= Duration::from_secs(15));
}
#[tokio::test(start_paused = true)]
async fn last_controller_can_expire_while_the_next_open_is_blocked() {
let (server_tx, _server_rx) = mpsc::channel(/*buffer*/ 2);
let (transport_tx, mut transport_rx) = mpsc::channel(/*buffer*/ 2);
let mut clients = ClientTracker::new(server_tx, transport_tx, &CancellationToken::new());
initialize_client(&mut clients, "first").await;
let mut attempt = 0;
for _ in 0..7 {
next_reconnect_delay(&mut attempt, &mut clients);
}
let wait = Duration::from_millis(5);
tokio::time::advance(Duration::from_secs(600) - wait).await;
assert!(clients.has_controller());
assert_eq!(transport_rx.len(), 2);
let ((), _first_open) = tokio::join!(
biased;
initialize_client(&mut clients, "next"),
async {
tokio::time::advance(wait).await;
let opened = transport_rx.recv().await.unwrap();
transport_rx.recv().await.unwrap();
opened
},
);
assert!(next_reconnect_delay(&mut attempt, &mut clients) <= Duration::from_secs(5));
}
#[tokio::test(start_paused = true)]
async fn cancelled_controller_uses_idle_backoff_before_writer_is_reaped() {
let (server_tx, _server_rx) = mpsc::channel(/*buffer*/ 2);
let (transport_tx, mut transport_rx) = mpsc::channel(/*buffer*/ 4);
let mut clients = ClientTracker::new(server_tx, transport_tx, &CancellationToken::new());
initialize_client(&mut clients, "controller").await;
let TransportEvent::ConnectionOpened {
disconnect_sender: Some(token),
writer: _writer,
..
} = transport_rx.recv().await.unwrap()
else {
panic!("missing connection open");
};
let mut attempt = 0;
for _ in 0..3 {
next_reconnect_delay(&mut attempt, &mut clients);
}
token.cancel();
assert!(!clients.has_controller());
assert!(next_reconnect_delay(&mut attempt, &mut clients) >= Duration::from_secs(15));
// A replay on the cancelled stream may open a replacement before the old
// writer finishes. Its cleanup must not close the replacement.
initialize_client(&mut clients, "controller").await;
assert!(
timeout(Duration::from_millis(10), clients.bookkeep_join_set())
.await
.is_err()
);
assert!(next_reconnect_delay(&mut attempt, &mut clients) <= Duration::from_secs(5));
}
fn assert_reconnect_backoff(attempt: &mut u64, clients: &mut ClientTracker, max_delays: &[u64]) {
for &max_delay in max_delays {
let delay = next_reconnect_delay(attempt, clients);
assert!(delay >= Duration::from_secs(max_delay) / 2);
assert!(delay <= Duration::from_secs(max_delay));
}
for mut reconnect_attempt in [reconnect_attempt, 9, u64::MAX] {
for mut reconnect_attempt in [*attempt, 9, u64::MAX] {
for _ in 0..1000 {
let delay = next_reconnect_delay(&mut reconnect_attempt);
let delay = next_reconnect_delay(&mut reconnect_attempt, clients);
assert!(delay >= Duration::from_secs(15));
assert!(delay <= Duration::from_secs(30));
}