//! Forward OAuth progress for every configured provider sharing the changed grant. use crate::config_manager::ConfigManager; use crate::outgoing_message::OutgoingMessageSender; use akode_app_server_protocol::GatewayOAuthChangedNotification; use akode_app_server_protocol::GatewayOAuthStatus; use akode_app_server_protocol::ServerNotification; use akode_login::AuthManager; use akode_login::GatewayAuthStatus; use std::sync::Arc; use tokio::sync::broadcast::error::RecvError; use tokio_util::task::AbortOnDropHandle; pub(crate) fn status_fields(status: GatewayAuthStatus) -> (GatewayOAuthStatus, Option) { match status { GatewayAuthStatus::NotReady => (GatewayOAuthStatus::NotReady, None), GatewayAuthStatus::Started => (GatewayOAuthStatus::Started, None), GatewayAuthStatus::Succeeded => (GatewayOAuthStatus::Succeeded, None), GatewayAuthStatus::Failed { message } => (GatewayOAuthStatus::Failed, Some(message)), } } pub(crate) fn spawn( auth_manager: Arc, config_manager: ConfigManager, outgoing: Arc, ) -> AbortOnDropHandle<()> { let mut events = akode_login::subscribe_gateway_auth_status(&auth_manager.runtime_config()); AbortOnDropHandle::new(tokio::spawn(async move { loop { let change = match events.recv().await { Ok(change) => change, Err(RecvError::Lagged(_)) => continue, Err(RecvError::Closed) => break, }; let Ok(config) = config_manager .load_latest_config(/*fallback_cwd*/ None) .await else { continue; }; for (provider_id, provider) in &config.model_providers { let Ok(Some(manager)) = akode_model_provider::create_model_provider( provider.clone(), Some(Arc::clone(&auth_manager)), ) .gateway_auth_manager() else { continue; }; if !matches!(manager.oauth_session(), Some(oauth) if oauth.config() == &change.config) { continue; } let (status, error) = status_fields(change.status.clone()); outgoing .send_server_notification(ServerNotification::GatewayOAuthChanged( GatewayOAuthChangedNotification { auth_url: None, provider_id: provider_id.clone(), status, error, }, )) .await; } } })) }