From 2816eb00ce78a30790299a2deacbfc405de8f62d Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 3 Jul 2026 01:35:27 -0400 Subject: [PATCH] [app-server] let idle auto-attached threads unload --- codex-rs/app-server/README.md | 1 + codex-rs/app-server/src/request_processors.rs | 1 + .../request_processors/thread_lifecycle.rs | 62 +++++--- .../thread_lifecycle_tests.rs | 87 ++++++++++ .../request_processors/thread_processor.rs | 28 +++- .../thread_processor_tests.rs | 149 +++++++++++++++++- .../src/request_processors/turn_processor.rs | 1 + codex-rs/app-server/src/thread_state.rs | 100 +++++++++--- 8 files changed, 368 insertions(+), 61 deletions(-) create mode 100644 codex-rs/app-server/src/request_processors/thread_lifecycle_tests.rs diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index c9ac2f5fb2..13b51f541f 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -160,6 +160,7 @@ Example with notification opt-out: - `thread/archive` — move a thread’s rollout file into the archived directory and attempt to move any spawned descendant thread rollout files; returns `{}` on success and emits `thread/archived` for each archived thread. - `thread/delete` — hard-delete an active or archived thread and any spawned descendant threads; returns `{}` on success and emits `thread/deleted` for each deleted thread. - `thread/unsubscribe` — unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server keeps the thread loaded and unloads it only after it has had no subscribers and no thread activity for 30 minutes, then emits `thread/closed`. +- Threads created internally by Codex are implicitly attached to every initialized connection so their events and server requests can be delivered. An implicit attachment does not count as a subscriber for the 30-minute idle unload. `thread/start`, `thread/resume`, and `thread/fork` establish retaining subscriptions; resuming an implicitly attached thread upgrades that connection. - `thread/name/set` — set or update a thread’s user-facing name for either a loaded thread or a persisted rollout; returns `{}` on success and emits `thread/name/updated` to initialized, opted-in clients. Thread names are not required to be unique; name lookups resolve to the most recently updated thread. - `thread/unarchive` — move an archived rollout file back into the sessions directory; returns the restored `thread` on success and emits `thread/unarchived`. - `thread/compact/start` — trigger conversation history compaction for a thread; returns `{}` immediately while progress streams through standard turn/item notifications. diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 587325c246..9d9c7bfeba 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -543,6 +543,7 @@ use crate::thread_state::ConnectionCapabilities; use crate::thread_state::ThreadListenerCommand; use crate::thread_state::ThreadState; use crate::thread_state::ThreadStateManager; +use crate::thread_state::ThreadSubscriptionKind; use token_usage_replay::latest_token_usage_turn_id_from_rollout_items; use token_usage_replay::send_thread_token_usage_update_to_connection; diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 82a49bae0b..8e28a6f885 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -18,8 +18,8 @@ pub(super) struct ListenerTaskContext { struct UnloadingState { delay: Duration, - has_subscribers_rx: watch::Receiver, - has_subscribers: (bool, Instant), + has_retaining_subscribers_rx: watch::Receiver, + has_retaining_subscribers: (bool, Instant), thread_status_rx: watch::Receiver, is_active: (bool, Instant), } @@ -30,30 +30,30 @@ impl UnloadingState { thread_id: ThreadId, delay: Duration, ) -> Option { - let has_subscribers_rx = listener_task_context + let has_retaining_subscribers_rx = listener_task_context .thread_state_manager - .subscribe_to_has_connections(thread_id) + .subscribe_to_has_explicit_subscribers(thread_id) .await?; let thread_status_rx = listener_task_context .thread_watch_manager .subscribe(thread_id) .await?; - let has_subscribers = (*has_subscribers_rx.borrow(), Instant::now()); + let has_retaining_subscribers = (*has_retaining_subscribers_rx.borrow(), Instant::now()); let is_active = ( matches!(*thread_status_rx.borrow(), ThreadStatus::Active { .. }), Instant::now(), ); Some(Self { delay, - has_subscribers_rx, - has_subscribers, + has_retaining_subscribers_rx, + has_retaining_subscribers, thread_status_rx, is_active, }) } fn unloading_target(&self) -> Option { - match (self.has_subscribers, self.is_active) { + match (self.has_retaining_subscribers, self.is_active) { ((false, has_no_subscribers_since), (false, is_inactive_since)) => { Some(std::cmp::max(has_no_subscribers_since, is_inactive_since) + self.delay) } @@ -62,9 +62,9 @@ impl UnloadingState { } fn sync_receiver_values(&mut self) { - let has_subscribers = *self.has_subscribers_rx.borrow(); - if self.has_subscribers.0 != has_subscribers { - self.has_subscribers = (has_subscribers, Instant::now()); + let has_retaining_subscribers = *self.has_retaining_subscribers_rx.borrow(); + if self.has_retaining_subscribers.0 != has_retaining_subscribers { + self.has_retaining_subscribers = (has_retaining_subscribers, Instant::now()); } let is_active = matches!(*self.thread_status_rx.borrow(), ThreadStatus::Active { .. }); @@ -73,6 +73,18 @@ impl UnloadingState { } } + fn note_retaining_subscriber_change(&mut self) { + self.has_retaining_subscribers = + (*self.has_retaining_subscribers_rx.borrow(), Instant::now()); + } + + fn note_thread_status_change(&mut self) { + self.is_active = ( + matches!(*self.thread_status_rx.borrow(), ThreadStatus::Active { .. }), + Instant::now(), + ); + } + fn should_unload_now(&mut self) -> bool { self.sync_receiver_values(); self.unloading_target() @@ -89,11 +101,6 @@ impl UnloadingState { loop { self.sync_receiver_values(); let unloading_target = self.unloading_target(); - if let Some(target) = unloading_target - && target <= Instant::now() - { - return true; - } let unloading_sleep = async { if let Some(target) = unloading_target { tokio::time::sleep_until(target.into()).await; @@ -102,19 +109,20 @@ impl UnloadingState { } }; tokio::select! { - _ = unloading_sleep => return true, - changed = self.has_subscribers_rx.changed() => { + biased; + changed = self.has_retaining_subscribers_rx.changed() => { if changed.is_err() { return false; } - self.sync_receiver_values(); + self.note_retaining_subscriber_change(); }, changed = self.thread_status_rx.changed() => { if changed.is_err() { return false; } - self.sync_receiver_values(); + self.note_thread_status_change(); }, + _ = unloading_sleep => return true, } } } @@ -140,6 +148,7 @@ pub(super) async fn ensure_conversation_listener( conversation_id: ThreadId, connection_id: ConnectionId, raw_events_enabled: bool, + subscription_kind: ThreadSubscriptionKind, ) -> Result { let conversation = match listener_task_context .thread_manager @@ -162,7 +171,12 @@ pub(super) async fn ensure_conversation_listener( } let Some(thread_state) = listener_task_context .thread_state_manager - .try_ensure_connection_subscribed(conversation_id, connection_id, raw_events_enabled) + .try_ensure_connection_attached( + conversation_id, + connection_id, + raw_events_enabled, + subscription_kind, + ) .await else { return Ok(EnsureConversationListenerResult::ConnectionClosed); @@ -413,7 +427,7 @@ pub(super) async fn unload_thread_without_subscribers( thread_id: ThreadId, thread: Arc, ) { - info!("thread {thread_id} has no subscribers and is idle; shutting down"); + info!("thread {thread_id} has no retaining subscribers and is idle; shutting down"); // Any pending app-server -> client requests for this thread can no longer be // answered; cancel their callbacks before shutdown/unload. @@ -800,3 +814,7 @@ pub(super) fn set_thread_status_and_interrupt_stale_turns( } thread.status = status; } + +#[cfg(test)] +#[path = "thread_lifecycle_tests.rs"] +mod tests; diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle_tests.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle_tests.rs new file mode 100644 index 0000000000..0d12ffb921 --- /dev/null +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle_tests.rs @@ -0,0 +1,87 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn reactivation_restarts_unloading_delay() { + let delay = Duration::from_secs(60); + let expired_at = Instant::now() - delay - Duration::from_secs(1); + let (_has_retaining_subscribers_tx, has_retaining_subscribers_rx) = watch::channel(false); + let (thread_status_tx, thread_status_rx) = watch::channel(ThreadStatus::Idle); + let mut unloading_state = UnloadingState { + delay, + has_retaining_subscribers_rx, + has_retaining_subscribers: (false, expired_at), + thread_status_rx, + is_active: (false, expired_at), + }; + + assert!(unloading_state.should_unload_now()); + + thread_status_tx + .send(ThreadStatus::Active { + active_flags: Vec::new(), + }) + .expect("thread status watcher should remain open"); + unloading_state.sync_receiver_values(); + assert_eq!(unloading_state.unloading_target(), None); + + thread_status_tx + .send(ThreadStatus::Idle) + .expect("thread status watcher should remain open"); + unloading_state.sync_receiver_values(); + assert!(!unloading_state.should_unload_now()); + assert!( + unloading_state + .unloading_target() + .is_some_and(|target| target > Instant::now()) + ); +} + +#[tokio::test] +async fn coalesced_changes_win_over_expired_unloading_deadline() { + let delay = Duration::from_secs(60); + let expired_at = Instant::now() - delay - Duration::from_secs(1); + let (has_retaining_subscribers_tx, has_retaining_subscribers_rx) = watch::channel(false); + let (thread_status_tx, thread_status_rx) = watch::channel(ThreadStatus::Idle); + let mut unloading_state = UnloadingState { + delay, + has_retaining_subscribers_rx, + has_retaining_subscribers: (false, expired_at), + thread_status_rx, + is_active: (false, expired_at), + }; + + has_retaining_subscribers_tx + .send(true) + .expect("subscriber watcher should remain open"); + has_retaining_subscribers_tx + .send(false) + .expect("subscriber watcher should remain open"); + assert!( + tokio::time::timeout( + Duration::from_millis(20), + unloading_state.wait_for_unloading_trigger(), + ) + .await + .is_err() + ); + + unloading_state.has_retaining_subscribers = (false, expired_at); + unloading_state.is_active = (false, expired_at); + thread_status_tx + .send(ThreadStatus::Active { + active_flags: Vec::new(), + }) + .expect("thread status watcher should remain open"); + thread_status_tx + .send(ThreadStatus::Idle) + .expect("thread status watcher should remain open"); + assert!( + tokio::time::timeout( + Duration::from_millis(20), + unloading_state.wait_for_unloading_trigger(), + ) + .await + .is_err() + ); +} diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index b78c53a383..d92d3f87ee 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -871,12 +871,14 @@ impl ThreadRequestProcessor { conversation_id: ThreadId, connection_id: ConnectionId, raw_events_enabled: bool, + subscription_kind: ThreadSubscriptionKind, ) -> Result { super::thread_lifecycle::ensure_conversation_listener( self.listener_task_context(), conversation_id, connection_id, raw_events_enabled, + subscription_kind, ) .await } @@ -1234,6 +1236,7 @@ impl ThreadRequestProcessor { thread_id, request_id.connection_id, experimental_raw_events, + ThreadSubscriptionKind::Explicit, ) .instrument(tracing::info_span!( "app_server.thread_start.attach_listener", @@ -2574,7 +2577,7 @@ impl ThreadRequestProcessor { self.thread_watch_manager.subscribe_running_turn_count() } - /// Best-effort: ensure initialized connections are subscribed to this thread. + /// Best-effort: implicitly attach initialized connections to this thread. pub(crate) async fn try_attach_thread_listener( &self, thread_id: ThreadId, @@ -2603,8 +2606,13 @@ impl ThreadRequestProcessor { for connection_id in connection_ids { log_listener_attach_result( - self.ensure_conversation_listener(thread_id, connection_id, raw_events_enabled) - .await, + self.ensure_conversation_listener( + thread_id, + connection_id, + raw_events_enabled, + ThreadSubscriptionKind::Implicit, + ) + .await, thread_id, connection_id, "thread", @@ -2797,6 +2805,7 @@ impl ThreadRequestProcessor { thread_id, request_id.connection_id, /*raw_events_enabled*/ false, + ThreadSubscriptionKind::Explicit, ) .await, thread_id, @@ -3017,11 +3026,10 @@ impl ThreadRequestProcessor { let config_snapshot = existing_thread.config_snapshot().await; let mismatch_details = collect_resume_override_mismatches(params, &config_snapshot); if !mismatch_details.is_empty() { - let has_subscribers = !self + let has_explicit_subscribers = self .thread_state_manager - .subscribed_connection_ids(existing_thread_id) - .await - .is_empty(); + .has_explicit_subscribers(existing_thread_id) + .await; let loaded_status = self .thread_watch_manager .loaded_status_for_thread(&existing_thread_id.to_string()) @@ -3029,7 +3037,10 @@ impl ThreadRequestProcessor { let is_running = matches!(existing_thread.agent_status().await, AgentStatus::Running); - if !has_subscribers && matches!(loaded_status, ThreadStatus::Idle) && !is_running { + if !has_explicit_subscribers + && matches!(loaded_status, ThreadStatus::Idle) + && !is_running + { // A loaded idle thread is only a cache entry. Shut it down // before removing it so cold resume cannot duplicate a // thread that timed out during shutdown. @@ -3543,6 +3554,7 @@ impl ThreadRequestProcessor { thread_id, request_id.connection_id, /*raw_events_enabled*/ false, + ThreadSubscriptionKind::Explicit, ) .await, thread_id, diff --git a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs index 8c0d59efed..5aca042461 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs @@ -1252,8 +1252,11 @@ mod thread_processor_behavior_tests { .connection_initialized(connection, ConnectionCapabilities::default()) .await; manager - .try_ensure_connection_subscribed( - thread_id, connection, /*experimental_raw_events*/ false, + .try_ensure_connection_attached( + thread_id, + connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Explicit, ) .await .expect("connection should be live"); @@ -1301,18 +1304,20 @@ mod thread_processor_behavior_tests { .connection_initialized(connection_b, ConnectionCapabilities::default()) .await; manager - .try_ensure_connection_subscribed( + .try_ensure_connection_attached( thread_id, connection_a, /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, ) .await .expect("connection_a should be live"); manager - .try_ensure_connection_subscribed( + .try_ensure_connection_attached( thread_id, connection_b, /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, ) .await .expect("connection_b should be live"); @@ -1336,6 +1341,130 @@ mod thread_processor_behavior_tests { Ok(()) } + #[tokio::test] + async fn implicit_attachment_delivers_without_retaining_thread() -> Result<()> { + let manager = ThreadStateManager::new(); + let thread_id = ThreadId::from_string("946c661d-d913-4384-97c9-5c62f7a8f1e4")?; + let connection = ConnectionId(1); + + manager + .connection_initialized(connection, ConnectionCapabilities::default()) + .await; + manager + .try_ensure_connection_attached( + thread_id, + connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, + ) + .await + .expect("connection should be live"); + + assert_eq!( + manager.subscribed_connection_ids(thread_id).await, + vec![connection] + ); + tokio::time::timeout( + Duration::from_secs(1), + manager.wait_for_thread_subscriber(thread_id), + ) + .await?; + let mut has_explicit_subscribers = manager + .subscribe_to_has_explicit_subscribers(thread_id) + .await + .expect("thread should have a subscription watcher"); + assert!(!*has_explicit_subscribers.borrow()); + + manager + .try_ensure_connection_attached( + thread_id, + connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Explicit, + ) + .await + .expect("connection should be live"); + tokio::time::timeout(Duration::from_secs(1), has_explicit_subscribers.changed()).await??; + assert!(*has_explicit_subscribers.borrow()); + + manager + .try_ensure_connection_attached( + thread_id, + connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, + ) + .await + .expect("connection should be live"); + assert!(*has_explicit_subscribers.borrow()); + + assert!( + manager + .unsubscribe_connection_from_thread(thread_id, connection) + .await + ); + tokio::time::timeout(Duration::from_secs(1), has_explicit_subscribers.changed()).await??; + assert!(!*has_explicit_subscribers.borrow()); + Ok(()) + } + + #[tokio::test] + async fn removing_last_explicit_subscriber_preserves_implicit_delivery() -> Result<()> { + let manager = ThreadStateManager::new(); + let thread_id = ThreadId::from_string("1951c0e7-7ec2-4e26-9b20-02407c8450a6")?; + let implicit_connection = ConnectionId(1); + let explicit_connection = ConnectionId(2); + + manager + .connection_initialized(implicit_connection, ConnectionCapabilities::default()) + .await; + manager + .connection_initialized(explicit_connection, ConnectionCapabilities::default()) + .await; + manager + .try_ensure_connection_attached( + thread_id, + implicit_connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, + ) + .await + .expect("implicit connection should be live"); + manager + .try_ensure_connection_attached( + thread_id, + explicit_connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Explicit, + ) + .await + .expect("explicit connection should be live"); + let mut has_explicit_subscribers = manager + .subscribe_to_has_explicit_subscribers(thread_id) + .await + .expect("thread should have a subscription watcher"); + assert!(*has_explicit_subscribers.borrow()); + + assert!( + manager + .unsubscribe_connection_from_thread(thread_id, explicit_connection) + .await + ); + tokio::time::timeout(Duration::from_secs(1), has_explicit_subscribers.changed()).await??; + + assert!(!*has_explicit_subscribers.borrow()); + assert_eq!( + manager.subscribed_connection_ids(thread_id).await, + vec![implicit_connection] + ); + tokio::time::timeout( + Duration::from_secs(1), + manager.wait_for_thread_subscriber(thread_id), + ) + .await?; + Ok(()) + } + #[tokio::test] async fn adding_connection_to_thread_updates_has_connections_watcher() -> Result<()> { let manager = ThreadStateManager::new(); @@ -1350,10 +1479,11 @@ mod thread_processor_behavior_tests { .connection_initialized(connection_b, ConnectionCapabilities::default()) .await; manager - .try_ensure_connection_subscribed( + .try_ensure_connection_attached( thread_id, connection_a, /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Explicit, ) .await .expect("connection_a should be live"); @@ -1426,13 +1556,16 @@ mod thread_processor_behavior_tests { assert!( manager - .try_ensure_connection_subscribed( - thread_id, connection, /*experimental_raw_events*/ false + .try_ensure_connection_attached( + thread_id, + connection, + /*experimental_raw_events*/ false, + ThreadSubscriptionKind::Implicit, ) .await .is_none() ); - assert!(!manager.has_subscribers(thread_id).await); + assert!(!manager.has_explicit_subscribers(thread_id).await); Ok(()) } diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index bb074e457b..afeae7b5db 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -1430,6 +1430,7 @@ impl TurnRequestProcessor { conversation_id, connection_id, raw_events_enabled, + ThreadSubscriptionKind::Explicit, ) .await } diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index fec786373c..d6ae731b99 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -249,29 +249,63 @@ mod tests { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ThreadSubscriptionKind { + Implicit, + Explicit, +} + struct ThreadEntry { state: Arc>, - connection_ids: HashSet, + connection_subscriptions: HashMap, has_connections_watcher: watch::Sender, + has_explicit_subscribers_watcher: watch::Sender, } impl Default for ThreadEntry { fn default() -> Self { Self { state: Arc::new(Mutex::new(ThreadState::default())), - connection_ids: HashSet::new(), + connection_subscriptions: HashMap::new(), has_connections_watcher: watch::channel(false).0, + has_explicit_subscribers_watcher: watch::channel(false).0, } } } impl ThreadEntry { - fn update_has_connections(&self) { + fn attach_connection( + &mut self, + connection_id: ConnectionId, + subscription_kind: ThreadSubscriptionKind, + ) { + self.connection_subscriptions + .entry(connection_id) + .and_modify(|existing_kind| { + if subscription_kind == ThreadSubscriptionKind::Explicit { + *existing_kind = ThreadSubscriptionKind::Explicit; + } + }) + .or_insert(subscription_kind); + self.update_connection_watchers(); + } + + fn update_connection_watchers(&self) { let _ = self.has_connections_watcher.send_if_modified(|current| { let prev = *current; - *current = !self.connection_ids.is_empty(); + *current = !self.connection_subscriptions.is_empty(); prev != *current }); + let _ = self + .has_explicit_subscribers_watcher + .send_if_modified(|current| { + let prev = *current; + *current = self + .connection_subscriptions + .values() + .any(|kind| *kind == ThreadSubscriptionKind::Explicit); + prev != *current + }); } } @@ -321,8 +355,8 @@ impl ThreadStateManager { state .threads .get(&thread_id)? - .connection_ids - .iter() + .connection_subscriptions + .keys() .filter_map(|connection_id| { state .live_connections @@ -355,7 +389,13 @@ impl ThreadStateManager { state .threads .get(&thread_id) - .map(|thread_entry| thread_entry.connection_ids.iter().copied().collect()) + .map(|thread_entry| { + thread_entry + .connection_subscriptions + .keys() + .copied() + .collect() + }) .unwrap_or_default() } @@ -471,29 +511,34 @@ impl ThreadStateManager { } } if let Some(thread_entry) = state.threads.get_mut(&thread_id) { - thread_entry.connection_ids.remove(&connection_id); - thread_entry.update_has_connections(); + thread_entry.connection_subscriptions.remove(&connection_id); + thread_entry.update_connection_watchers(); } }; true } - #[cfg(test)] - pub(crate) async fn has_subscribers(&self, thread_id: ThreadId) -> bool { + pub(crate) async fn has_explicit_subscribers(&self, thread_id: ThreadId) -> bool { self.state .lock() .await .threads .get(&thread_id) - .is_some_and(|thread_entry| !thread_entry.connection_ids.is_empty()) + .is_some_and(|thread_entry| { + thread_entry + .connection_subscriptions + .values() + .any(|kind| *kind == ThreadSubscriptionKind::Explicit) + }) } - pub(crate) async fn try_ensure_connection_subscribed( + pub(crate) async fn try_ensure_connection_attached( &self, thread_id: ThreadId, connection_id: ConnectionId, experimental_raw_events: bool, + subscription_kind: ThreadSubscriptionKind, ) -> Option>> { let thread_state = { let mut state = self.state.lock().await; @@ -506,8 +551,7 @@ impl ThreadStateManager { .or_default() .insert(thread_id); let thread_entry = state.threads.entry(thread_id).or_default(); - thread_entry.connection_ids.insert(connection_id); - thread_entry.update_has_connections(); + thread_entry.attach_connection(connection_id, subscription_kind); thread_entry.state.clone() }; { @@ -534,8 +578,7 @@ impl ThreadStateManager { .or_default() .insert(thread_id); let thread_entry = state.threads.entry(thread_id).or_default(); - thread_entry.connection_ids.insert(connection_id); - thread_entry.update_has_connections(); + thread_entry.attach_connection(connection_id, ThreadSubscriptionKind::Explicit); true } @@ -549,22 +592,22 @@ impl ThreadStateManager { .unwrap_or_default(); for thread_id in &thread_ids { if let Some(thread_entry) = state.threads.get_mut(thread_id) { - thread_entry.connection_ids.remove(&connection_id); - thread_entry.update_has_connections(); + thread_entry.connection_subscriptions.remove(&connection_id); + thread_entry.update_connection_watchers(); } } thread_ids .into_iter() .filter(|thread_id| { - state - .threads - .get(thread_id) - .is_some_and(|thread_entry| thread_entry.connection_ids.is_empty()) + state.threads.get(thread_id).is_some_and(|thread_entry| { + thread_entry.connection_subscriptions.is_empty() + }) }) .collect::>() } } + #[cfg(test)] pub(crate) async fn subscribe_to_has_connections( &self, thread_id: ThreadId, @@ -575,4 +618,15 @@ impl ThreadStateManager { .get(&thread_id) .map(|thread_entry| thread_entry.has_connections_watcher.subscribe()) } + + pub(crate) async fn subscribe_to_has_explicit_subscribers( + &self, + thread_id: ThreadId, + ) -> Option> { + let state = self.state.lock().await; + state + .threads + .get(&thread_id) + .map(|thread_entry| thread_entry.has_explicit_subscribers_watcher.subscribe()) + } }