Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 95 additions & 10 deletions fluss-rust/crates/fluss/src/client/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

use crate::client::metadata::Metadata;
use crate::error::{Error, Result};
use crate::rpc::RpcClient;
use crate::rpc::message::GetSecurityTokenRequest;
use crate::rpc::{RpcClient, RpcError};
use log::{debug, info, warn};
use parking_lot::RwLock;
use serde::Deserialize;
Expand All @@ -32,6 +32,8 @@ use tokio::task::JoinHandle;
const DEFAULT_TOKEN_RENEWAL_RATIO: f64 = 0.8;
/// Default retry backoff when token fetch fails
const DEFAULT_RENEWAL_RETRY_BACKOFF: Duration = Duration::from_secs(30);
const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
const CREDENTIALS_WAIT_TIMEOUT: Duration = Duration::from_secs(60);
/// Minimum delay between refreshes
const MIN_RENEWAL_DELAY: Duration = Duration::from_secs(1);
/// Maximum delay between refreshes (7 days) - prevents overflow and ensures periodic refresh
Expand All @@ -44,6 +46,50 @@ const DEFAULT_NON_EXPIRING_REFRESH_INTERVAL: Duration = Duration::from_secs(7 *
/// - `Some(HashMap)` = fetched (may be empty if no auth needed)
pub type CredentialsReceiver = watch::Receiver<Option<HashMap<String, String>>>;

#[derive(Clone)]
pub(crate) struct RemoteStorageCredentials {
pub(super) properties: CredentialsReceiver,
pub(super) initial_error: watch::Receiver<Option<Arc<Error>>>,
}

impl RemoteStorageCredentials {
pub(crate) async fn get(&mut self) -> Result<HashMap<String, String>> {
let result = tokio::time::timeout(CREDENTIALS_WAIT_TIMEOUT, async {
tokio::select! {
biased;
result = self.properties.wait_for(Option::is_some) => {
result.map(|props| Ok(props.as_ref().unwrap().clone()))
}
result = self.initial_error.wait_for(Option::is_some) => {
result.map(|error| {
let error = error.as_ref().unwrap();
Err(match error.as_ref() {
Error::FlussAPIError { api_error } => Error::FlussAPIError {
api_error: api_error.clone(),
},
_ => Error::UnexpectedError {
message: "Failed to obtain remote storage credentials".into(),
source: Some(Box::new(Arc::clone(error))),
},
})
})
}
}
})
.await
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!("Timed out after {CREDENTIALS_WAIT_TIMEOUT:?} waiting for remote storage credentials"),
)
})?;
result.map_err(|_| Error::UnexpectedError {
message: "Remote storage credential manager stopped".into(),
source: None,
})?
}
}

#[derive(Debug, Deserialize)]
struct Credentials {
access_key_id: String,
Expand Down Expand Up @@ -145,6 +191,7 @@ pub struct SecurityTokenManager {
credentials_tx: watch::Sender<Option<HashMap<String, String>>>,
/// Watch channel receiver (kept to allow cloning for new subscribers)
credentials_rx: watch::Receiver<Option<HashMap<String, String>>>,
initial_error: watch::Sender<Option<Arc<Error>>>,
/// Handle to the background refresh task
task_handle: RwLock<Option<JoinHandle<()>>>,
/// Sender to signal shutdown
Expand All @@ -161,6 +208,7 @@ impl SecurityTokenManager {
renewal_retry_backoff: DEFAULT_RENEWAL_RETRY_BACKOFF,
credentials_tx,
credentials_rx,
initial_error: watch::Sender::new(None),
task_handle: RwLock::new(None),
shutdown_tx: RwLock::new(None),
}
Expand All @@ -173,6 +221,13 @@ impl SecurityTokenManager {
self.credentials_rx.clone()
}

pub(crate) fn subscribe_for_download(&self) -> RemoteStorageCredentials {
RemoteStorageCredentials {
properties: self.subscribe(),
initial_error: self.initial_error.subscribe(),
}
}

/// Start the background token refresh task.
/// This should be called once after creating the manager.
pub fn start(&self) {
Expand All @@ -189,6 +244,7 @@ impl SecurityTokenManager {
let token_renewal_ratio = self.token_renewal_ratio;
let renewal_retry_backoff = self.renewal_retry_backoff;
let credentials_tx = self.credentials_tx.clone();
let initial_error = self.initial_error.clone();

let handle = tokio::spawn(async move {
Self::token_refresh_loop(
Expand All @@ -197,6 +253,7 @@ impl SecurityTokenManager {
token_renewal_ratio,
renewal_retry_backoff,
credentials_tx,
initial_error,
shutdown_rx,
)
.await;
Expand All @@ -223,20 +280,29 @@ impl SecurityTokenManager {
token_renewal_ratio: f64,
renewal_retry_backoff: Duration,
credentials_tx: watch::Sender<Option<HashMap<String, String>>>,
initial_error: watch::Sender<Option<Arc<Error>>>,
mut shutdown_rx: oneshot::Receiver<()>,
) {
info!("Starting token refresh loop");

loop {
// Fetch token and send to channel
let result = Self::fetch_token(&rpc_client, &metadata).await;
let result = tokio::select! {
biased;
_ = &mut shutdown_rx => break,
result = tokio::time::timeout(TOKEN_REQUEST_TIMEOUT, Self::fetch_token(&rpc_client, &metadata)) => {
result.unwrap_or_else(|_| Err(RpcError::ConnectionError(
format!("Remote storage token request timed out after {TOKEN_REQUEST_TIMEOUT:?}"),
).into()))
}
};

let next_delay = match result {
Ok((props, expiration_time)) => {
// Send credentials via watch channel (Some indicates fetched)
if let Err(e) = credentials_tx.send(Some(props)) {
debug!("No active subscribers for credentials update: {e:?}");
}
initial_error.send_replace(None);

// Calculate next renewal delay based on expiration time
if let Some(exp_time) = expiration_time {
Expand All @@ -253,6 +319,10 @@ impl SecurityTokenManager {
warn!(
"Failed to obtain security token: {e:?}, will retry in {renewal_retry_backoff:?}"
);
// Preserve the last successful token while its renewal retries.
if !e.is_retriable() && credentials_tx.borrow().is_none() {
initial_error.send_replace(Some(Arc::new(e)));
}
renewal_retry_backoff
}
};
Expand All @@ -279,13 +349,9 @@ impl SecurityTokenManager {
metadata: &Arc<Metadata>,
) -> Result<(HashMap<String, String>, Option<i64>)> {
let cluster = metadata.get_cluster();
let server_node =
cluster
.get_one_available_server()
.ok_or_else(|| Error::UnexpectedError {
message: "No tablet server available for token refresh".to_string(),
source: None,
})?;
let server_node = cluster.get_one_available_server().ok_or_else(|| {
RpcError::ConnectionError("No tablet server available for token refresh".into())
})?;

let conn = rpc_client.get_connection(server_node).await?;
let request = GetSecurityTokenRequest::new();
Expand Down Expand Up @@ -353,6 +419,25 @@ impl Drop for SecurityTokenManager {
mod tests {
use super::*;

#[tokio::test(start_paused = true)]
async fn credential_wait_times_out_and_can_recover() {
let (properties_tx, properties) = watch::channel(None);
let (_error_tx, initial_error) = watch::channel(None);
let mut credentials = RemoteStorageCredentials {
properties,
initial_error,
};
let start = tokio::time::Instant::now();

let error = credentials.get().await.unwrap_err();
assert!(matches!(error, Error::IoUnexpectedError { source, .. }
if source.kind() == std::io::ErrorKind::TimedOut));
assert_eq!(start.elapsed(), CREDENTIALS_WAIT_TIMEOUT);

properties_tx.send(Some(HashMap::new())).unwrap();
assert!(credentials.get().await.unwrap().is_empty());
}

#[test]
fn convert_hadoop_key_to_opendal_maps_known_keys() {
// S3 keys
Expand Down
34 changes: 34 additions & 0 deletions fluss-rust/crates/fluss/src/client/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,40 @@ mod tests {
write_reply(stream, &reply).await;
}

#[tokio::test]
async fn terminal_token_error_reaches_waiting_readers() {
use crate::client::SecurityTokenManager;

let token_api = ApiKey::GetFileSystemSecurityToken;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let nodes = server_metadata(&[1], listener.local_addr().unwrap().port());
let cluster = Arc::new(Cluster::from_metadata_response(nodes, None).unwrap());
let metadata = Arc::new(Metadata::new_for_test(cluster));
let manager = SecurityTokenManager::new(metadata.connections.clone(), metadata);
let mut credentials = manager.subscribe_for_download();
let server = tokio::spawn(async move {
let mut stream =
accept_handshake(listener, ServerType::TabletServer, &[token_api]).await;
let mut reply = read_request(&mut stream, token_api).await;
reply[0] = 1;
ErrorResponse {
error_code: FlussError::SecurityTokenException.code(),
error_message: Some("Test token request failed".into()),
}
.encode(&mut reply)
.unwrap();
write_reply(&mut stream, &reply).await;
});

manager.start();
let error = tokio::time::timeout(Duration::from_secs(5), credentials.get())
.await
.expect("the credential wait should return the RPC failure without retrying first")
.unwrap_err();
assert_eq!(error.api_error(), Some(FlussError::SecurityTokenException));
server.await.unwrap();
}

fn unavailable_ids(metadata: &Metadata) -> HashSet<i32> {
metadata
.unavailable_tablet_servers
Expand Down
30 changes: 19 additions & 11 deletions fluss-rust/crates/fluss/src/client/table/kv_snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use super::FlussTable;
use super::kv_value_decoder::{KvValueDecoder, read_schema_id};
use super::remote_log::RemoteLogDownloader;
use crate::SnapshotId;
use crate::client::{ClientSchemaGetter, CredentialsReceiver, FlussAdmin, SecurityTokenManager};
use crate::client::{
ClientSchemaGetter, FlussAdmin, RemoteStorageCredentials, SecurityTokenManager,
};
use crate::error::{Error, Result};
use crate::metadata::{
KvSnapshotLeaseForBucket, KvSnapshotLeaseForTable, KvSnapshotMetadata, RemotePathAndLocalFile,
Expand Down Expand Up @@ -274,7 +276,7 @@ impl FlussTable<'_> {
let directory = tempfile::Builder::new()
.prefix("kv-snapshot-")
.tempdir_in(parent)?;
let mut credentials = tokens.subscribe();
let mut credentials = tokens.subscribe_for_download();
tokens.start();
for file in &metadata.snapshot_files {
if tx.is_closed() {
Expand Down Expand Up @@ -504,7 +506,7 @@ impl ReadState {
async fn download_snapshot_file(
file: &RemotePathAndLocalFile,
directory: &Path,
credentials: &mut CredentialsReceiver,
credentials: &mut RemoteStorageCredentials,
slots: &Semaphore,
caller: &mut oneshot::Sender<Result<KvSnapshotReader>>,
read_concurrency: usize,
Expand All @@ -513,9 +515,7 @@ async fn download_snapshot_file(
tokio::select! {
biased;
_ = caller.closed() => return Err(snapshot_error("Snapshot creation cancelled")),
result = credentials.wait_for(|value| value.is_some()) => {
drop(result.map_err(|e| snapshot_error(format!("Snapshot credentials unavailable: {e}")))?);
}
result = credentials.get() => drop(result?),
}
let _permit = tokio::select! {
biased;
Expand All @@ -527,9 +527,7 @@ async fn download_snapshot_file(
let props = tokio::select! {
biased;
_ = caller.closed() => return Err(snapshot_error("Snapshot creation cancelled")),
result = credentials.wait_for(|value| value.is_some()) => result
.map_err(|e| snapshot_error(format!("Snapshot credentials unavailable: {e}")))?
.clone().unwrap(),
result = credentials.get() => result?,
};
RemoteLogDownloader::download_file(
&file.remote_path,
Expand Down Expand Up @@ -949,7 +947,12 @@ mod tests {
});
ready.await.unwrap();
let slots = Semaphore::new(1);
let (_credentials_tx, mut first_credentials) = watch::channel(Some(HashMap::new()));
let (_credentials_tx, properties) = watch::channel(Some(HashMap::new()));
let (_error_tx, initial_error) = watch::channel(None);
let mut first_credentials = RemoteStorageCredentials {
properties,
initial_error,
};
let mut second_credentials = first_credentials.clone();
let (mut first_tx, _first_rx) = oneshot::channel();
let (mut second_tx, second_rx) = oneshot::channel();
Expand Down Expand Up @@ -994,7 +997,12 @@ mod tests {
local_file_name: "CURRENT".into(),
};
let slots = Semaphore::new(1);
let (_credentials_tx, mut credentials) = watch::channel(None);
let (_credentials_tx, properties) = watch::channel(None);
let (_error_tx, initial_error) = watch::channel(None);
let mut credentials = RemoteStorageCredentials {
properties,
initial_error,
};
let (mut caller, receiver) = oneshot::channel();
let mut download = Box::pin(download_snapshot_file(
&file,
Expand Down
5 changes: 3 additions & 2 deletions fluss-rust/crates/fluss/src/client/table/log_fetch_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,7 +1096,7 @@ mod tests {
use super::*;
use crate::client::table::read_context_resolver::ReadContextResolver;
use crate::client::table::remote_log::{
FetchResult as DownloadResult, RemoteLogDownloadRequest, RemoteLogDownloader,
FetchError, FetchResult as DownloadResult, RemoteLogDownloadRequest, RemoteLogDownloader,
RemoteLogFetcher,
};
use crate::client::{EARLIEST_OFFSET, WriteRecord};
Expand Down Expand Up @@ -1511,7 +1511,8 @@ mod tests {
fn fetch(
&self,
_: &RemoteLogDownloadRequest,
) -> Pin<Box<dyn Future<Output = Result<DownloadResult>> + Send>> {
) -> Pin<Box<dyn Future<Output = std::result::Result<DownloadResult, FetchError>> + Send>>
{
let file_path = self.0.clone();
Box::pin(async move {
Ok(DownloadResult {
Expand Down
Loading
Loading