bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::{future::Future, time::Duration};

use tokio::time::{Instant, sleep_until};

use super::AccessToken;
use crate::{Error, ErrorKind};

/// The default wait before each request for the token.
pub(super) const INTERVAL: Duration = Duration::from_secs(5);
/// The default time during which new requests for the token are started.
pub(super) const BUDGET: Duration = Duration::from_secs(600);

/// Calls `fetch` every `interval` until it returns a token or fails.
///
/// No request starts after the budget has passed: when the next request would start
/// later, the wait ends with the budget. A request that starts within the budget is
/// awaited to its end, so a token can arrive after the budget has passed. Dropping
/// the returned future stops the wait or the request in progress.
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>>,
{
    // A budget that cannot be added to the clock has no end.
    let deadline = Instant::now().checked_add(budget);
    loop {
        // An interval that cannot be added to the clock ends later than any budget.
        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;
            }
            // Neither time can be added to the clock, so the wait has no end.
            (None, None) => std::future::pending().await,
        }
        // The task can resume later than the time that it asked for.
        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()),
    ))
}