From 01376eab9cf541a47591ac217c7a6a87909feabb Mon Sep 17 00:00:00 2001 From: Thang Pham Date: Sun, 25 Jun 2023 13:04:21 -0400 Subject: [PATCH] Implement timeout mechanism for getting authentication token --- spotify_player/src/token.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/spotify_player/src/token.rs b/spotify_player/src/token.rs index c94e0b82..46bf0511 100644 --- a/spotify_player/src/token.rs +++ b/spotify_player/src/token.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use anyhow::{anyhow, Result}; +use anyhow::Result; use chrono::{Duration, Utc}; use librespot_core::{keymaster, session::Session}; use rspotify::Token; @@ -24,13 +24,20 @@ const SCOPES: [&str; 15] = [ "user-library-modify", ]; +const TIMEOUT_IN_SECS: u64 = 5; + /// gets an authentication token with pre-defined permission scopes pub async fn get_token(session: &Session, client_id: &str) -> Result { tracing::info!("Getting new authentication token..."); - let token = keymaster::get_token(session, client_id, &SCOPES.join(",")) - .await - .map_err(|err| anyhow!(format!("failed to get token: {err:#?}")))?; + let scopes = SCOPES.join(","); + let fut = keymaster::get_token(session, client_id, &scopes); + let token = + match tokio::time::timeout(std::time::Duration::from_secs(TIMEOUT_IN_SECS), fut).await { + Ok(Ok(token)) => token, + Ok(Err(err)) => anyhow::bail!("failed to get the token: {:?}", err), + Err(_) => anyhow::bail!("timeout when getting the token"), + }; // converts the token returned by librespot `get_token` function to a `rspotify::Token`