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