Skip to main content

nautilus_architect_ax/common/
auth.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Authentication-token refresh lifecycle shared by AX clients.
17
18use 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
31/// Runs the AX authentication-token refresh loop.
32///
33/// A refreshed token becomes the HTTP session token during authentication, then `update_token`
34/// makes it available to future WebSocket reconnect handshakes.
35pub 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}