use std::{future::Future, time::Duration};
use tokio::time::{Instant, sleep_until};
use super::AccessToken;
use crate::{Error, ErrorKind};
pub(super) const INTERVAL: Duration = Duration::from_secs(5);
pub(super) const BUDGET: Duration = Duration::from_secs(600);
pub(super) async fn poll<F, Fut>(interval: Duration, budget: Duration, mut fetch: F) -> Result<AccessToken, Error>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<Option<AccessToken>, Error>>,
{
let deadline = Instant::now().checked_add(budget);
loop {
match (Instant::now().checked_add(interval), deadline) {
(Some(next), None) => sleep_until(next).await,
(Some(next), Some(deadline)) if next <= deadline => sleep_until(next).await,
(_, Some(deadline)) => {
sleep_until(deadline).await;
break;
}
(None, None) => std::future::pending().await,
}
if deadline.is_some_and(|deadline| Instant::now() > deadline) {
break;
}
if let Some(token) = fetch().await? {
return Ok(token);
}
}
Err(Error::new(
ErrorKind::AuthorizationTimedOut,
format!("Polling timed out after {} seconds. User may not have completed authorization.", budget.as_secs()),
))
}