neuroclient 0.4.0

Independent Rust client for the Emotiv Cortex v2 WebSocket API
Documentation
use tokio::time::Instant;

use crate::error::CortexResult;

use super::{ResilientClient, TOKEN_REFRESH_INTERVAL};

impl ResilientClient {
    /// Returns the current Cortex token (for advanced use cases).
    pub async fn cortex_token(&self) -> String {
        self.state.read().await.cortex_token.clone()
    }

    /// Check if the token should be refreshed and do so if needed.
    ///
    /// Authentication I/O runs *outside* the state lock so a slow refresh
    /// cannot block concurrent operations or reconnection. The result is
    /// applied only if the connection was not replaced in the meantime
    /// (a reconnect already obtains a fresh token of its own).
    pub(super) async fn maybe_refresh_token(&self) -> CortexResult<()> {
        let refresh_client = {
            let state = self.state.read().await;
            if state.token_obtained_at.elapsed() <= TOKEN_REFRESH_INTERVAL {
                return Ok(());
            }
            std::sync::Arc::clone(&state.client)
        };

        tracing::info!("Proactively refreshing Cortex token");
        match refresh_client
            .authenticate(&self.config.client_id, &self.config.client_secret)
            .await
        {
            Ok(new_token) => {
                let mut state = self.state.write().await;
                // Apply only if this is still the active connection and no
                // concurrent refresh beat us to it.
                if std::sync::Arc::ptr_eq(&state.client, &refresh_client)
                    && state.token_obtained_at.elapsed() > TOKEN_REFRESH_INTERVAL
                {
                    state.cortex_token = new_token;
                    state.token_obtained_at = Instant::now();
                    tracing::info!("Token refreshed successfully");
                } else {
                    tracing::debug!("Discarding stale token refresh result");
                }
            }
            Err(e) => {
                tracing::warn!(
                    error_category = e.category(),
                    api_code = ?e.api_code(),
                    "Token refresh failed, will retry on next call"
                );
            }
        }

        Ok(())
    }

    /// Generate a new cortex token (or refresh an existing one).
    ///
    /// On success, also updates the internal token and refresh timestamp.
    ///
    /// # Errors
    /// Returns any error produced by the underlying Cortex API call,
    /// including connection, authentication, protocol, timeout, and configuration errors.
    pub async fn generate_new_token(&self) -> CortexResult<String> {
        let client_id = self.config.client_id.clone();
        let client_secret = self.config.client_secret.clone();
        let (new_token, source_client) = self
            .exec_with_token_tracked(move |c, token| {
                let id = client_id.clone();
                let secret = client_secret.clone();
                async move { c.generate_new_token(&token, &id, &secret).await }
            })
            .await?;

        // Commit only to the client generation that produced the token. If a
        // reconnect installed a newer client in the meantime, its freshly
        // authenticated token wins and is returned to the caller.
        let mut state = self.state.write().await;
        if std::sync::Arc::ptr_eq(&state.client, &source_client) {
            state.cortex_token.clone_from(&new_token);
            state.token_obtained_at = Instant::now();
            Ok(new_token)
        } else {
            tracing::debug!("Discarding token generated by stale client");
            Ok(state.cortex_token.clone())
        }
    }
}