nautilus_architect_ax/common/
auth.rs1use std::{fmt::Display, time::Instant};
19
20use nautilus_core::string::secret::SecretString;
21
22use super::{
23 consts::{
24 AX_AUTH_TOKEN_REFRESH_INTERVAL, AX_AUTH_TOKEN_REFRESH_RETRY_DELAY,
25 AX_AUTH_TOKEN_REQUEST_TIMEOUT, AX_AUTH_TOKEN_TTL_SECS,
26 },
27 credential::Credential,
28};
29use crate::http::client::AxHttpClient;
30
31pub async fn run_auth_token_refresh<E>(
36 http_client: AxHttpClient,
37 credential: Credential,
38 update_token: impl Fn(SecretString) -> Result<(), E> + Send + 'static,
39) where
40 E: Display + Send + 'static,
41{
42 let conservative_ttl = std::time::Duration::from_secs(AX_AUTH_TOKEN_TTL_SECS as u64)
43 .saturating_sub(AX_AUTH_TOKEN_REQUEST_TIMEOUT);
44 let mut fully_propagated_expiry = Instant::now() + conservative_ttl;
45 let mut next_delay = AX_AUTH_TOKEN_REFRESH_INTERVAL;
46
47 loop {
48 tokio::time::sleep(next_delay).await;
49 let request_started = Instant::now();
50
51 let result = tokio::time::timeout(
52 AX_AUTH_TOKEN_REQUEST_TIMEOUT,
53 http_client.authenticate(
54 credential.api_key(),
55 credential.api_secret(),
56 AX_AUTH_TOKEN_TTL_SECS,
57 ),
58 )
59 .await;
60
61 let error = match result {
62 Ok(Ok(token)) => match update_token(token) {
63 Ok(()) => {
64 fully_propagated_expiry = request_started
65 + std::time::Duration::from_secs(AX_AUTH_TOKEN_TTL_SECS as u64);
66 next_delay = AX_AUTH_TOKEN_REFRESH_INTERVAL;
67 log::debug!("AX authentication token refreshed");
68 continue;
69 }
70 Err(e) => format!("failed to update WebSocket reconnect authentication: {e}"),
71 },
72 Ok(Err(e)) => format!("authentication request failed: {e}"),
73 Err(_) => format!(
74 "authentication request timed out after {}s",
75 AX_AUTH_TOKEN_REQUEST_TIMEOUT.as_secs()
76 ),
77 };
78
79 if Instant::now() >= fully_propagated_expiry {
80 log::error!(
81 "AX authentication token refresh failed after the last fully propagated token expired: {error}"
82 );
83 } else {
84 log::warn!("AX authentication token refresh failed: {error}");
85 }
86 next_delay = AX_AUTH_TOKEN_REFRESH_RETRY_DELAY;
87 }
88}