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 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
29/// Runs the AX authentication-token refresh loop.
30///
31/// A refreshed token becomes the HTTP session token during authentication, then `update_token`
32/// makes it available to future WebSocket reconnect handshakes.
33pub 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}