diff --git a/fluss-rust/crates/fluss/src/client/admin.rs b/fluss-rust/crates/fluss/src/client/admin.rs index ccff515f636..7b275d4341d 100644 --- a/fluss-rust/crates/fluss/src/client/admin.rs +++ b/fluss-rust/crates/fluss/src/client/admin.rs @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use super::admin_gateway::{GatewayTarget, RetryableGateway}; use crate::client::metadata::Metadata; use crate::cluster::{Cluster, ServerNode}; use crate::metadata::{ @@ -26,6 +27,7 @@ use crate::metadata::{ RebalanceProgress, RegisterProducerResult, RemoteLogManifestEntry, Schema, SchemaInfo, ServerTag, TableBucket, TableDescriptor, TableInfo, TableOrPartition, TablePath, TableStats, }; +use crate::rpc::RpcClient; use crate::rpc::message::{ AcquireKvSnapshotLeaseRequest, AddServerTagRequest, AlterClusterConfigsRequest, AlterDatabaseRequest, AlterTableRequest, CancelRebalanceRequest, CreateAclsRequest, @@ -41,7 +43,6 @@ use crate::rpc::message::{ ReleaseKvSnapshotLeaseRequest, RemoveServerTagRequest, TableExistsRequest, }; use crate::rpc::message::{ListOffsetsRequest, OffsetSpec}; -use crate::rpc::{RpcClient, ServerConnection}; use crate::error::{Error, Result}; use crate::proto::GetTableInfoResponse; @@ -61,34 +62,28 @@ fn parse_table_descriptor(bytes: &[u8]) -> Result { pub struct FlussAdmin { metadata: Arc, rpc_client: Arc, + tablet_gateway: RetryableGateway, + coordinator_gateway: RetryableGateway, } impl FlussAdmin { pub fn new(connections: Arc, metadata: Arc) -> Self { FlussAdmin { + tablet_gateway: RetryableGateway::new( + GatewayTarget::TabletServer, + metadata.clone(), + connections.clone(), + ), + coordinator_gateway: RetryableGateway::new( + GatewayTarget::Coordinator, + metadata.clone(), + connections.clone(), + ), metadata, rpc_client: connections, } } - async fn admin_gateway(&self) -> Result { - let cluster = self.metadata.get_cluster(); - let coordinator = - cluster - .get_coordinator_server() - .ok_or_else(|| Error::UnexpectedError { - message: "Coordinator server not found in cluster metadata".to_string(), - source: None, - })?; - self.rpc_client.get_connection(coordinator).await - } - - async fn read_only_gateway(&self) -> Result { - self.rpc_client - .get_connection(&self.metadata.admin_read_server()?) - .await - } - pub async fn create_database( &self, database_name: &str, @@ -96,8 +91,7 @@ impl FlussAdmin { ignore_if_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(CreateDatabaseRequest::new( database_name, database_descriptor, @@ -114,8 +108,7 @@ impl FlussAdmin { ignore_if_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(CreateTableRequest::new( table_path, table_descriptor, @@ -131,8 +124,7 @@ impl FlussAdmin { ignore_if_not_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DropTableRequest::new(table_path, ignore_if_not_exists)) .await?; Ok(()) @@ -146,8 +138,7 @@ impl FlussAdmin { schema_id: Option, ) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetTableSchemaRequestMsg::new(table_path, schema_id)) .await?; @@ -162,16 +153,15 @@ impl FlussAdmin { pub async fn get_table_info(&self, table_path: &TablePath) -> Result { let info = self.fetch_table_info(table_path).await?; // Refresh bucket routing for callers that use the table id to request table stats. - self.metadata - .refresh_admin_metadata(Some(table_path)) + self.tablet_gateway + .call(|server| self.metadata.refresh_table_routing(server, table_path)) .await?; Ok(info) } async fn fetch_table_info(&self, table_path: &TablePath) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetTableRequest::new(table_path)) .await?; let GetTableInfoResponse { @@ -198,8 +188,7 @@ impl FlussAdmin { /// List all tables in the given database pub async fn list_tables(&self, database_name: &str) -> Result> { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(ListTablesRequest::new(database_name)) .await?; Ok(response.table_name) @@ -217,8 +206,7 @@ impl FlussAdmin { partial_partition_spec: Option<&PartitionSpec>, ) -> Result> { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(ListPartitionInfosRequest::new( table_path, partial_partition_spec, @@ -243,8 +231,7 @@ impl FlussAdmin { ignore_if_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(CreatePartitionRequest::new( table_path, partition_spec, @@ -262,8 +249,7 @@ impl FlussAdmin { ignore_if_not_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DropPartitionRequest::new( table_path, partition_spec, @@ -276,8 +262,7 @@ impl FlussAdmin { /// Check if a table exists pub async fn table_exists(&self, table_path: &TablePath) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(TableExistsRequest::new(table_path)) .await?; Ok(response.exists) @@ -291,8 +276,7 @@ impl FlussAdmin { cascade: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DropDatabaseRequest::new( database_name, ignore_if_not_exists, @@ -305,8 +289,7 @@ impl FlussAdmin { /// List all databases pub async fn list_databases(&self) -> Result> { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(ListDatabasesRequest::new()) .await?; Ok(response.database_name) @@ -315,8 +298,7 @@ impl FlussAdmin { /// Check if a database exists pub async fn database_exists(&self, database_name: &str) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(DatabaseExistsRequest::new(database_name)) .await?; Ok(response.exists) @@ -325,7 +307,7 @@ impl FlussAdmin { /// Get database information pub async fn get_database_info(&self, database_name: &str) -> Result { let request = GetDatabaseInfoRequest::new(database_name); - let response = self.read_only_gateway().await?.request(request).await?; + let response = self.tablet_gateway.request(request).await?; // Convert proto response to DatabaseInfo let database_descriptor = DatabaseDescriptor::from_json_bytes(&response.database_json)?; @@ -341,21 +323,14 @@ impl FlussAdmin { /// Get all alive server nodes in the cluster, including the coordinator /// and all tablet servers. Refreshes cluster metadata before returning. pub async fn get_server_nodes(&self) -> Result> { - if let Err(error) = self.metadata.refresh_admin_metadata(None).await { - if !error.is_retriable() && !matches!(error, Error::InvalidServerType { .. }) { - return Err(error); - } - // Explicit discovery still works when no cached tablet can answer. - self.metadata.reinit_cluster().await?; - } + self.metadata.refresh_server_nodes(None).await?; Ok(self.metadata.get_cluster().get_server_nodes()) } /// Get the latest lake snapshot for a table pub async fn get_latest_lake_snapshot(&self, table_path: &TablePath) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetLatestLakeSnapshotRequest::new(table_path)) .await?; @@ -534,8 +509,7 @@ impl FlussAdmin { /// List database summaries (name, created_time, table_count). pub async fn list_database_summaries(&self) -> Result> { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(ListDatabaseSummariesRequest::new()) .await?; Ok(response @@ -554,8 +528,7 @@ impl FlussAdmin { ignore_if_not_exists: bool, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(AlterDatabaseRequest::new( name, ignore_if_not_exists, @@ -576,8 +549,7 @@ impl FlussAdmin { ) -> Result<()> { changes.validate()?; let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(AlterTableRequest::new( table_path, ignore_if_not_exists, @@ -667,8 +639,7 @@ impl FlussAdmin { partition_name: Option<&str>, ) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetLatestKvSnapshotsRequest::new(table_path, partition_name)) .await?; Ok(LatestKvSnapshots::from_pb(&response)) @@ -683,8 +654,7 @@ impl FlussAdmin { snapshot_id: SnapshotId, ) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetKvSnapshotMetadataRequest::new( table_id, partition_id, @@ -703,8 +673,7 @@ impl FlussAdmin { snapshots_to_lease: Vec, ) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(AcquireKvSnapshotLeaseRequest::new( lease_id, lease_duration_ms, @@ -722,8 +691,7 @@ impl FlussAdmin { readable: Option, ) -> Result { let response = self - .read_only_gateway() - .await? + .tablet_gateway .request(GetLakeSnapshotRequest::new( table_path, snapshot_id, @@ -736,8 +704,7 @@ impl FlussAdmin { /// Create ACLs. Returns one result per submitted ACL (success or per-ACL error). pub async fn create_acls(&self, acls: Vec) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(CreateAclsRequest::new(acls)) .await?; response @@ -750,8 +717,7 @@ impl FlussAdmin { /// List ACLs matching a filter. pub async fn list_acls(&self, acl_filter: AclFilter) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(ListAclsRequest::new(acl_filter)) .await?; response.acl.iter().map(AclInfo::from_pb).collect() @@ -763,8 +729,7 @@ impl FlussAdmin { acl_filters: Vec, ) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DropAclsRequest::new(acl_filters)) .await?; response @@ -777,8 +742,7 @@ impl FlussAdmin { /// Describe cluster configuration. pub async fn describe_cluster_configs(&self) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DescribeClusterConfigsRequest::new()) .await?; Ok(response @@ -791,8 +755,7 @@ impl FlussAdmin { /// Alter cluster configuration. pub async fn alter_cluster_configs(&self, alter_configs: Vec) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(AlterClusterConfigsRequest::new(alter_configs)) .await?; Ok(()) @@ -801,8 +764,7 @@ impl FlussAdmin { /// Add a tag to servers. pub async fn add_server_tag(&self, server_ids: Vec, server_tag: ServerTag) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(AddServerTagRequest::new(server_ids, server_tag)) .await?; Ok(()) @@ -815,8 +777,7 @@ impl FlussAdmin { server_tag: ServerTag, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(RemoveServerTagRequest::new(server_ids, server_tag)) .await?; Ok(()) @@ -825,8 +786,7 @@ impl FlussAdmin { /// Trigger a rebalance. Returns the rebalance id assigned by the server. pub async fn rebalance(&self, goals: Vec) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(RebalanceRequest::new(goals)) .await?; Ok(response.rebalance_id) @@ -838,8 +798,7 @@ impl FlussAdmin { rebalance_id: Option<&str>, ) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(ListRebalanceProgressRequest::new(rebalance_id)) .await?; RebalanceProgress::from_pb(&response) @@ -848,8 +807,7 @@ impl FlussAdmin { /// Cancel a rebalance. pub async fn cancel_rebalance(&self, rebalance_id: Option<&str>) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(CancelRebalanceRequest::new(rebalance_id)) .await?; Ok(()) @@ -863,8 +821,7 @@ impl FlussAdmin { ttl_ms: Option, ) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(RegisterProducerOffsetsRequest::new( producer_id, table_offsets, @@ -880,8 +837,7 @@ impl FlussAdmin { /// Get producer offsets. pub async fn get_producer_offsets(&self, producer_id: &str) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(GetProducerOffsetsRequest::new(producer_id)) .await?; Ok(ProducerOffsets::from_pb(&response)) @@ -890,8 +846,7 @@ impl FlussAdmin { /// Delete producer offsets. pub async fn delete_producer_offsets(&self, producer_id: &str) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DeleteProducerOffsetsRequest::new(producer_id)) .await?; Ok(()) @@ -900,8 +855,7 @@ impl FlussAdmin { /// Get cluster health status. pub async fn get_cluster_health(&self) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(GetClusterHealthRequest::new()) .await?; ClusterHealth::from_pb(&response) @@ -914,8 +868,7 @@ impl FlussAdmin { partition_id: Option, ) -> Result> { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(ListRemoteLogManifestsRequest::new(table_id, partition_id)) .await?; Ok(response @@ -932,8 +885,7 @@ impl FlussAdmin { partition_id: Option, ) -> Result { let response = self - .admin_gateway() - .await? + .coordinator_gateway .request(ListKvSnapshotsRequest::new(table_id, partition_id)) .await?; Ok(ActiveKvSnapshots::from_pb(&response)) @@ -946,8 +898,7 @@ impl FlussAdmin { buckets_to_release: Vec, ) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(ReleaseKvSnapshotLeaseRequest::new( lease_id, buckets_to_release, @@ -959,8 +910,7 @@ impl FlussAdmin { /// Drop an entire KV snapshot lease. pub async fn drop_kv_snapshot_lease(&self, lease_id: &str) -> Result<()> { let _response = self - .admin_gateway() - .await? + .coordinator_gateway .request(DropKvSnapshotLeaseRequest::new(lease_id)) .await?; Ok(()) diff --git a/fluss-rust/crates/fluss/src/client/admin_gateway.rs b/fluss-rust/crates/fluss/src/client/admin_gateway.rs new file mode 100644 index 00000000000..29497510668 --- /dev/null +++ b/fluss-rust/crates/fluss/src/client/admin_gateway.rs @@ -0,0 +1,148 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use super::Metadata; +use crate::cluster::ServerNode; +use crate::error::{Error, FlussError, Result}; +use crate::proto::MetadataResponse; +use crate::rpc::message::{ReadType, RequestBody, WriteType}; +use crate::rpc::{RpcClient, RpcError}; +use arc_swap::ArcSwap; +use std::future::Future; +use std::io::Cursor; +use std::sync::Arc; +use tokio::sync::OnceCell; + +#[derive(Clone, Copy, Debug)] +pub(super) enum GatewayTarget { + TabletServer, + Coordinator, +} + +impl GatewayTarget { + pub(super) fn is_available(self, response: &MetadataResponse) -> bool { + match self { + Self::TabletServer => !response.tablet_servers.is_empty(), + Self::Coordinator => response.coordinator_server.is_some(), + } + } + + pub(super) fn needs_refresh(error: &Error) -> bool { + error.is_retriable() || matches!(error, Error::InvalidServerType { .. }) + } + + fn can_replay(self, error: &Error) -> bool { + // A standby rejects the RPC before applying it; a role mismatch fails the handshake. + // A lost response, on the other hand, can hide a successful coordinator mutation. + matches!(self, Self::TabletServer) + || matches!(error, Error::InvalidServerType { .. }) + || error.api_error() == Some(FlussError::NotCoordinatorLeaderException) + } +} + +type RefreshRound = OnceCell, ()>>; + +pub(super) struct RetryableGateway { + target: GatewayTarget, + metadata: Arc, + client: Arc, + refresh: ArcSwap, +} + +impl RetryableGateway { + pub(super) fn new( + target: GatewayTarget, + metadata: Arc, + client: Arc, + ) -> Self { + Self { + target, + metadata, + client, + refresh: ArcSwap::from_pointee(OnceCell::new()), + } + } + + fn select(&self, responding_tablet: Option<&ServerNode>) -> Result { + let cluster = self.metadata.get_cluster(); + let (server, missing) = match self.target { + // A recovered peer may still advertise stale addresses. Prefer the tablet that + // answered discovery only while its endpoint still matches this snapshot. + GatewayTarget::TabletServer => ( + responding_tablet + .filter(|t| cluster.get_tablet_server(t.id()) == Some(*t)) + .or_else(|| cluster.get_one_available_server()), + "No available tablet server for a read-only Admin request", + ), + GatewayTarget::Coordinator => ( + cluster.get_coordinator_server(), + "No coordinator in cluster metadata", + ), + }; + server + .cloned() + .ok_or_else(|| RpcError::ConnectionError(missing.into()).into()) + } + + pub(super) async fn request(&self, request: R) -> Result + where + R: RequestBody + Sync + WriteType>, + R::ResponseBody: ReadType>>, + { + let request = &request; + self.call(|server| async move { + self.client + .get_connection(&server) + .await? + .request(request) + .await + }) + .await + } + + pub(super) async fn call>>( + &self, + send: impl Fn(ServerNode) -> F, + ) -> Result { + // Capture the round before sending: even a late failure from the same batch can + // reuse discovery already completed by a sibling. + let round = self.refresh.load_full(); + let (error, replay) = match self.select(None) { + Ok(server) => match send(server).await { + Ok(response) => return Ok(response), + Err(e) if GatewayTarget::needs_refresh(&e) => { + let replay = self.target.can_replay(&e); + (e, replay) + } + Err(e) => return Err(e), + }, + // No destination was selected, so nothing has been sent, even for a mutation. + Err(e) => (e, true), + }; + let refreshed = round + .get_or_init(|| async { + let result = self.metadata.refresh_server_nodes(Some(self.target)).await; + self.refresh.store(Arc::new(OnceCell::new())); + result.map_err(|e| log::warn!("Failed to refresh {:?}: {e}", self.target)) + }) + .await; + match refreshed { + Ok(tablet) if replay => send(self.select(tablet.as_ref())?).await, + _ => Err(error), + } + } +} diff --git a/fluss-rust/crates/fluss/src/client/metadata.rs b/fluss-rust/crates/fluss/src/client/metadata.rs index 7430959572a..81d15641941 100644 --- a/fluss-rust/crates/fluss/src/client/metadata.rs +++ b/fluss-rust/crates/fluss/src/client/metadata.rs @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use super::admin_gateway::GatewayTarget; use crate::cluster::{Cluster, ServerNode, ServerType}; use crate::error::{Error, FlussError, Result}; use crate::metadata::{PhysicalTablePath, TableBucket, TablePath}; @@ -26,9 +27,10 @@ use crate::{PartitionId, TableId}; use arc_swap::{ArcSwap, Guard}; use log::{info, warn}; use parking_lot::{Mutex, MutexGuard, RwLock}; +use rand::seq::SliceRandom; use std::collections::HashSet; use std::future::Future; -use std::net::{SocketAddr, ToSocketAddrs}; +use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::sync::watch; @@ -50,16 +52,12 @@ pub struct Metadata { request_timeout: Duration, } -#[derive(Debug)] -struct BootstrapServer { - raw: String, - address: Result, -} - impl Metadata { pub async fn new(bootstrap: &str, connections: Arc) -> Result { - let cluster = - Self::init_cluster(bootstrap, connections.clone(), METADATA_REQUEST_TIMEOUT).await?; + let nodes = + Self::bootstrap_metadata(bootstrap, &connections, METADATA_REQUEST_TIMEOUT, None) + .await?; + let cluster = Cluster::from_metadata_response(nodes, None)?; let (cluster_version_tx, _) = watch::channel(0); Ok(Metadata { cluster: ArcSwap::from_pointee(cluster), @@ -81,52 +79,40 @@ impl Metadata { .send_modify(|v| *v = v.wrapping_add(1)); } - fn parse_bootstrap(bootstrap: &str) -> Result { - // Resolve all socket addresses and deterministically choose one. - let addrs = bootstrap - .to_socket_addrs() - .map_err(|e| Error::IllegalArgument { - message: format!("Invalid bootstrap address '{bootstrap}': {e}"), - })?; + async fn resolve_bootstrap(bootstrap: &str) -> Result { + let addrs = + tokio::net::lookup_host(bootstrap) + .await + .map_err(|e| Error::IllegalArgument { + message: format!("Invalid bootstrap address '{bootstrap}': {e}"), + })?; // Prefer IPv4 addresses; if none are available, fall back to the first IPv6. - let mut ipv6_candidate: Option = None; - for addr in addrs { - if addr.is_ipv4() { - return Ok(addr); - } - if ipv6_candidate.is_none() { - ipv6_candidate = Some(addr); - } - } - - let addr = ipv6_candidate.ok_or_else(|| Error::IllegalArgument { - message: format!("Unable to resolve bootstrap address '{bootstrap}'"), - })?; - Ok(addr) + let addr = addrs + .min_by_key(SocketAddr::is_ipv6) + .ok_or_else(|| Error::IllegalArgument { + message: format!("Unable to resolve bootstrap address '{bootstrap}'"), + })?; + Ok(ServerNode::new( + -1, + addr.ip().to_string(), + addr.port().into(), + ServerType::Unknown, + )) } - fn parse_bootstrap_servers(bootstrap_servers: &str) -> Result> { - let mut bootstraps = Vec::new(); - - for bootstrap in bootstrap_servers.split(',') { - let bootstrap = bootstrap.trim(); - if bootstrap.is_empty() { - continue; - } - bootstraps.push(BootstrapServer { - raw: bootstrap.to_string(), - address: Self::parse_bootstrap(bootstrap), - }); - } - - if bootstraps.is_empty() { + fn bootstrap_addresses(bootstrap: &str) -> Result> { + let addresses: Vec<_> = bootstrap + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect(); + if addresses.is_empty() { return Err(Error::IllegalArgument { - message: "No bootstrap servers configured".to_string(), + message: "No bootstrap servers configured".into(), }); } - - Ok(bootstraps) + Ok(addresses) } async fn retry_bootstrap( @@ -160,79 +146,61 @@ impl Metadata { } } - async fn init_cluster( - bootstrap_servers: &str, - connections: Arc, - request_timeout: Duration, - ) -> Result { - let bootstraps = Self::parse_bootstrap_servers(bootstrap_servers)?; - let bootstrap_count = bootstraps.len(); - let mut errors = Vec::new(); - let mut last_connection_error = None; - - for (index, bootstrap) in bootstraps.into_iter().enumerate() { - let socket_address = match bootstrap.address { - Ok(socket_address) => socket_address, - Err(err) => { - if index + 1 < bootstrap_count { - warn!( - "Failed to resolve bootstrap server '{}', trying the next server: {err}", - bootstrap.raw - ); - } - errors.push(format!("{}: {err}", bootstrap.raw)); - continue; - } - }; - let server_node = ServerNode::new( - -1, - socket_address.ip().to_string(), - socket_address.port() as u32, - ServerType::Unknown, - ); + async fn bootstrap_metadata( + bootstrap: &str, + connections: &RpcClient, + timeout: Duration, + target: Option, + ) -> Result { + let addresses = Self::bootstrap_addresses(bootstrap)?; + if target.is_none() + && let [address] = addresses.as_slice() + { + let server = Self::resolve_bootstrap(address).await?; + return Self::retry_bootstrap( + address, + || Self::request_server_nodes(connections, &server, timeout, None), + || connections.disconnect_endpoint(&server), + ) + .await; + } - let cluster_result = if bootstrap_count == 1 { - Self::retry_bootstrap( - &bootstrap.raw, - || { - Self::fetch_cluster_from_bootstrap( - &server_node, - connections.clone(), - request_timeout, - ) - }, - || connections.disconnect_endpoint(&server_node), - ) - .await - } else { - Self::fetch_cluster_from_bootstrap( - &server_node, - connections.clone(), - request_timeout, - ) - .await - }; - - match cluster_result { - Ok(cluster) => return Ok(cluster), - Err(err) => { - if index + 1 < bootstrap_count { - warn!( - "Failed to initialize cluster from bootstrap server '{}', trying the next server: {err}", - bootstrap.raw - ); + let round = || async { + let mut errors = Vec::new(); + let mut last_connection_error = None; + for &address in &addresses { + let server = match Self::resolve_bootstrap(address).await { + Ok(server) => server, + Err(error) => { + errors.push(format!("{address}: {error}")); + continue; + } + }; + match Self::request_server_nodes(connections, &server, timeout, target).await { + Ok(nodes) => return Ok(nodes), + Err(error) if target.is_some() && !GatewayTarget::needs_refresh(&error) => { + return Err(error); + } + Err(error) => { + errors.push(format!("{address}: {error}")); + last_connection_error = Some(error); } - errors.push(format!("{}: {err}", bootstrap.raw)); - last_connection_error = Some(err); } } - } + Err(Self::bootstrap_initialization_error( + bootstrap, + errors, + last_connection_error, + )) + }; - Err(Self::bootstrap_initialization_error( - bootstrap_servers, - errors, - last_connection_error, - )) + // Multi-address startup tries one round. Recovery repeats whole rounds so a + // responsive bootstrap with a stale node list doesn't delay the next address. + if target.is_some() { + Self::retry_bootstrap(bootstrap, round, || {}).await + } else { + round().await + } } fn bootstrap_initialization_error( @@ -255,19 +223,26 @@ impl Metadata { Error::IllegalArgument { message } } - async fn fetch_cluster_from_bootstrap( + async fn request_server_nodes( + connections: &RpcClient, server_node: &ServerNode, - connections: Arc, request_timeout: Duration, - ) -> Result { + target: Option, + ) -> Result { let response = Self::request_metadata( - &connections, + connections, server_node, UpdateMetadataRequest::new(&HashSet::default(), &HashSet::new(), vec![]), request_timeout, ) .await?; - Cluster::from_metadata_response(response, None) + if let Some(target) = target.filter(|target| !target.is_available(&response)) { + return Err(crate::rpc::RpcError::ConnectionError(format!( + "Cluster metadata contains no {target:?}" + )) + .into()); + } + Ok(response) } /// Fails as retriable if `server` does not answer within `timeout`, so the caller can ask @@ -293,44 +268,18 @@ impl Metadata { }) } - pub(super) fn admin_read_server(&self) -> Result { - self.cluster - .load() - .get_one_available_server() - .cloned() - .ok_or_else(|| { - crate::rpc::RpcError::ConnectionError( - "No available tablet server for a read-only Admin request".into(), - ) - .into() - }) - } - - pub(super) async fn refresh_admin_metadata(&self, table: Option<&TablePath>) -> Result<()> { - let request = - UpdateMetadataRequest::new(&table.into_iter().collect(), &HashSet::new(), vec![]); - let response = Self::request_metadata( - &self.connections, - &self.admin_read_server()?, - request, - self.request_timeout, - ) - .await?; + pub(super) async fn refresh_table_routing( + &self, + server: ServerNode, + table: &TablePath, + ) -> Result<()> { + let request = UpdateMetadataRequest::new(&HashSet::from([table]), &HashSet::new(), vec![]); + let response = + Self::request_metadata(&self.connections, &server, request, self.request_timeout) + .await?; self.update(response).await } - pub(crate) async fn reinit_cluster(&self) -> Result<()> { - let cluster = Self::init_cluster( - &self.bootstrap, - self.connections.clone(), - self.request_timeout, - ) - .await?; - let changing = self.changing.lock(); - self.replace_cluster(&changing, cluster); - Ok(()) - } - fn replace_cluster(&self, changing: &MutexGuard<'_, ()>, cluster: Cluster) { let cluster = self.swap_cluster(changing, cluster); // A successful refresh may advertise new addresses for previously failed servers. @@ -456,6 +405,43 @@ impl Metadata { .cloned() } + /// A rolling replacement can invalidate every cached address. Try each known tablet + /// once, then rediscover nodes from bootstrap using the existing backoff. + pub(super) async fn refresh_server_nodes( + &self, + target: Option, + ) -> Result> { + let mut tablets = self.get_cluster().get_server_nodes(); + tablets.retain(|s| s.server_type() == &ServerType::TabletServer); + tablets.shuffle(&mut rand::rng()); + for tablet in tablets { + match Self::request_server_nodes( + &self.connections, + &tablet, + self.request_timeout, + target, + ) + .await + { + Ok(response) => { + self.update(response).await?; + return Ok(Some(tablet)); + } + Err(error) if GatewayTarget::needs_refresh(&error) => continue, + Err(error) => return Err(error), + } + } + let response = Self::bootstrap_metadata( + &self.bootstrap, + &self.connections, + self.request_timeout, + target, + ) + .await?; + self.update(response).await?; + Ok(None) + } + pub async fn update_tables_metadata( &self, table_paths: &HashSet<&TablePath>, @@ -511,7 +497,15 @@ impl Metadata { info!( "No available tablet server to update metadata, attempting to re-initialize cluster using bootstrap server." ); - self.reinit_cluster().await?; + let nodes = Self::bootstrap_metadata( + &self.bootstrap, + &self.connections, + self.request_timeout, + None, + ) + .await?; + let cluster = Cluster::from_metadata_response(nodes, None)?; + self.replace_cluster(&self.changing.lock(), cluster); return Ok(None); } }; @@ -727,6 +721,8 @@ impl Metadata { #[cfg(test)] mod tests { + mod admin_gateway; + use super::*; use crate::error::ApiError; use crate::metadata::{TableBucket, TablePath}; @@ -1389,84 +1385,30 @@ mod tests { assert_eq!(error.api_error(), Some(FlussError::AuthenticateException)); } - #[test] - fn parse_bootstrap_variants() { - // valid IP - let bootstraps = Metadata::parse_bootstrap_servers("127.0.0.1:8080").unwrap(); - let addr = bootstraps[0].address.as_ref().unwrap(); - assert_eq!(addr.ip().to_string(), "127.0.0.1"); - assert_eq!(addr.port(), 8080); - - // valid hostname - let bootstraps = Metadata::parse_bootstrap_servers("localhost:9090").unwrap(); - let addr = bootstraps[0].address.as_ref().unwrap(); - assert_eq!(addr.ip().to_string(), "127.0.0.1"); - assert_eq!(addr.port(), 9090); - - // valid IPv6 address - let bootstraps = Metadata::parse_bootstrap_servers("[::1]:8080").unwrap(); - let addr = bootstraps[0].address.as_ref().unwrap(); - assert_eq!(addr.ip().to_string(), "::1"); - assert_eq!(addr.port(), 8080); - - // invalid input: missing port is preserved as an entry-level parse error - let bootstraps = Metadata::parse_bootstrap_servers("localhost").unwrap(); - assert!(bootstraps[0].address.is_err()); - - // invalid input: out-of-range port is preserved as an entry-level parse error - let bootstraps = Metadata::parse_bootstrap_servers("localhost:99999").unwrap(); - assert!(bootstraps[0].address.is_err()); - - // invalid input: empty string - assert!(Metadata::parse_bootstrap_servers("").is_err()); - - // invalid input: nonsensical address is preserved as an entry-level parse error - let bootstraps = Metadata::parse_bootstrap_servers("invalid_address").unwrap(); - assert!(bootstraps[0].address.is_err()); - } - - #[test] - fn parse_bootstrap_accepts_comma_separated_servers() { - let bootstraps = - Metadata::parse_bootstrap_servers("127.0.0.1:8080, localhost:9090, [::1]:7070") - .unwrap(); - - assert_eq!(bootstraps.len(), 3); - let first = bootstraps[0].address.as_ref().unwrap(); - assert_eq!(first.ip().to_string(), "127.0.0.1"); - assert_eq!(first.port(), 8080); - let second = bootstraps[1].address.as_ref().unwrap(); - assert_eq!(second.ip().to_string(), "127.0.0.1"); - assert_eq!(second.port(), 9090); - let third = bootstraps[2].address.as_ref().unwrap(); - assert_eq!(third.ip().to_string(), "::1"); - assert_eq!(third.port(), 7070); - } - - #[test] - fn parse_bootstrap_preserves_later_entries_when_one_entry_is_unresolvable() { - let bootstraps = - Metadata::parse_bootstrap_servers("invalid.invalid:8080, 127.0.0.1:9090").unwrap(); - - assert_eq!(bootstraps.len(), 2); - assert!(bootstraps[0].address.is_err()); - let addr = bootstraps[1].address.as_ref().unwrap(); - assert_eq!(addr.ip().to_string(), "127.0.0.1"); - assert_eq!(addr.port(), 9090); - } - - #[test] - fn parse_bootstrap_ignores_empty_comma_separated_entries() { - let bootstraps = - Metadata::parse_bootstrap_servers("127.0.0.1:8080, , localhost:9090,").unwrap(); - - assert_eq!(bootstraps.len(), 2); - assert_eq!(bootstraps[0].raw, "127.0.0.1:8080"); - assert_eq!(bootstraps[1].raw, "localhost:9090"); + #[tokio::test] + async fn resolves_bootstrap_hostnames_and_prefers_ipv4() { + for (address, host) in [ + ("127.0.0.1:8080", "127.0.0.1"), + ("localhost:8080", "127.0.0.1"), + ("[::1]:8080", "::1"), + ] { + let node = Metadata::resolve_bootstrap(address).await.unwrap(); + assert_eq!((node.host(), node.port()), (host, 8080)); + } + assert!(Metadata::resolve_bootstrap("localhost").await.is_err()); + assert!( + Metadata::resolve_bootstrap("localhost:99999") + .await + .is_err() + ); } #[test] - fn parse_bootstrap_rejects_config_without_servers() { - assert!(Metadata::parse_bootstrap_servers(" , ").is_err()); + fn bootstrap_list_ignores_empty_entries_and_rejects_an_empty_list() { + assert_eq!( + Metadata::bootstrap_addresses("127.0.0.1:8080, ,localhost:9090,").unwrap(), + ["127.0.0.1:8080", "localhost:9090"] + ); + assert!(Metadata::bootstrap_addresses(" , ").is_err()); } } diff --git a/fluss-rust/crates/fluss/src/client/metadata/tests/admin_gateway.rs b/fluss-rust/crates/fluss/src/client/metadata/tests/admin_gateway.rs new file mode 100644 index 00000000000..4d57023858d --- /dev/null +++ b/fluss-rust/crates/fluss/src/client/metadata/tests/admin_gateway.rs @@ -0,0 +1,224 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use super::*; +use crate::client::FlussAdmin; +use crate::proto::{DatabaseExistsResponse, DropDatabaseResponse, ListPartitionInfosResponse}; +use ApiKey::{DatabaseExists, DropDatabase, ListDatabases, ListPartitionInfos, MetaData}; +use ServerType::{CoordinatorServer, TabletServer}; + +async fn listen() -> TcpListener { + TcpListener::bind("127.0.0.1:0").await.unwrap() +} + +fn node(listener: &TcpListener) -> PbServerNode { + let addr = listener.local_addr().unwrap(); + PbServerNode { + host: addr.ip().to_string(), + port: addr.port().into(), + ..Default::default() + } +} + +fn admin(nodes: MetadataResponse, bootstrap: &str) -> FlussAdmin { + let cluster = Cluster::from_metadata_response(nodes, None).unwrap(); + let metadata = Arc::new(Metadata::new_for_test(Arc::new(cluster)).with_bootstrap(bootstrap)); + FlussAdmin::new(metadata.connections.clone(), metadata) +} + +async fn exchange(server: impl Future, client: impl Future) -> T { + tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(server, client).1 + }) + .await + .expect("Admin RPC exchange timed out") +} + +async fn reply_error(stream: &mut TcpStream, mut reply: Vec, error: FlussError) { + reply[0] = 1; + ErrorResponse { + error_code: error.code(), + error_message: None, + } + .encode(&mut reply) + .unwrap(); + write_reply(stream, &reply).await; +} + +#[tokio::test] +async fn partition_listing_recovers_a_moved_tablet() { + let empty = listen().await; + let bootstrap = listen().await; + let tablet = listen().await; + let addresses = format!( + "missing-port,{},{}", + empty.local_addr().unwrap(), + bootstrap.local_addr().unwrap() + ); + let cached = TablePath::new("db", "cached"); + let cluster = build_cluster_with_tables(&[(&cached, 42, 1)], 0); + let metadata = Arc::new(Metadata::new_for_test(Arc::new(cluster)).with_bootstrap(&addresses)); + let admin = FlussAdmin::new(metadata.connections.clone(), metadata.clone()); + let table = TablePath::new("db", "parts"); + let server = async { + // Only the second bootstrap knows the tablet's new address. + let nodes = MetadataResponse { + coordinator_server: Some(node(&bootstrap)), + ..Default::default() + }; + let moved = MetadataResponse { + tablet_servers: server_metadata(&[1], tablet.local_addr().unwrap().port()) + .tablet_servers, + ..nodes.clone() + }; + serve_metadata_as(empty, CoordinatorServer, Ok(nodes)).await; + serve_metadata_as(bootstrap, CoordinatorServer, Ok(moved)).await; + let mut ts = accept_handshake(tablet, TabletServer, &[ListPartitionInfos]).await; + serve_success( + &mut ts, + ListPartitionInfos, + &ListPartitionInfosResponse::default(), + ) + .await; + }; + let partitions = exchange(server, admin.list_partition_infos(&table)) + .await + .unwrap(); + assert!(partitions.is_empty()); + let cluster = metadata.get_cluster(); + assert_eq!(cluster.get_table_path_by_id(42), Some(&cached)); + assert!(cluster.leader_for(&TableBucket::new(42, 0)).is_none()); +} + +#[tokio::test] +async fn coordinator_only_bootstrap_allows_discovery_but_not_admin_reads() { + let listener = listen().await; + let admin = admin( + MetadataResponse::default(), + &listener.local_addr().unwrap().to_string(), + ); + let nodes = MetadataResponse { + coordinator_server: Some(node(&listener)), + ..Default::default() + }; + let (started, pending) = oneshot::channel(); + let server = async { + let mut cs = accept_handshake(listener, CoordinatorServer, &[MetaData]).await; + // The overlapping inspection may accept this node list, but the read still needs a TS. + let inspection = read_request(&mut cs, MetaData).await; + started.send(()).unwrap(); + let read = read_request(&mut cs, MetaData).await; + for mut reply in [inspection, read] { + nodes.encode(&mut reply).unwrap(); + write_reply(&mut cs, &reply).await; + } + for _ in 0..MAX_BOOTSTRAP_RETRIES { + serve_success(&mut cs, MetaData, &nodes).await; + } + }; + let (discovered, read) = exchange(server, async { + tokio::join!(admin.get_server_nodes(), async { + pending.await.unwrap(); + let start = tokio::time::Instant::now(); + let result = admin.list_databases().await; + assert!(start.elapsed() >= Duration::from_millis(700)); + result + }) + }) + .await; + assert!(matches!(&discovered.unwrap()[..], [cs] if cs.server_type() == &CoordinatorServer)); + assert!( + matches!(read, Err(Error::RpcError { source: crate::rpc::RpcError::ConnectionError(message), .. }) if message.contains("No available tablet server")) + ); +} + +#[tokio::test] +async fn concurrent_admin_reads_refresh_once_and_retry_once() { + let listener = listen().await; + let nodes = server_metadata(&[1], listener.local_addr().unwrap().port()); + let admin = admin(nodes.clone(), ""); + let found = DatabaseExistsResponse { exists: true }; + let server = async { + let apis = [DatabaseExists, ListDatabases, MetaData]; + let mut ts = accept_handshake(listener, TabletServer, &apis).await; + // Establish one socket before racing the two requests on it. + serve_success(&mut ts, DatabaseExists, &found).await; + let first = read_request(&mut ts, DatabaseExists).await; + let second = read_request(&mut ts, DatabaseExists).await; + for reply in [first, second] { + reply_error(&mut ts, reply, FlussError::NetworkException).await; + } + serve_success(&mut ts, MetaData, &nodes).await; + serve_success(&mut ts, DatabaseExists, &found).await; + let retry = read_request(&mut ts, DatabaseExists).await; + reply_error(&mut ts, retry, FlussError::NetworkException).await; + let denied = read_request(&mut ts, ListDatabases).await; + reply_error(&mut ts, denied, FlussError::AuthorizationException).await; + serve_success(&mut ts, DatabaseExists, &found).await; + }; + exchange(server, async { + let read = || admin.database_exists("db"); + read().await.unwrap(); + let (first, second) = tokio::join!(read(), read()); + let (ok, err) = if first.is_ok() { + (first, second) + } else { + (second, first) + }; + assert!(ok.unwrap()); + assert_eq!( + err.unwrap_err().api_error(), + Some(FlussError::NetworkException) + ); + assert_eq!( + admin.list_databases().await.unwrap_err().api_error(), + Some(FlussError::AuthorizationException) + ); + assert!(read().await.unwrap()); + }) + .await; +} + +#[tokio::test] +async fn coordinator_mutations_refresh_but_only_replay_a_rejected_request() { + let tablet = listen().await; + let old = listen().await; + let new = listen().await; + let mut nodes = server_metadata(&[1], tablet.local_addr().unwrap().port()); + nodes.coordinator_server = Some(node(&old)); + let admin = admin(nodes.clone(), ""); + nodes.coordinator_server = Some(node(&new)); + let server = async { + // The old coordinator takes the mutation, then loses its response. + let mut first = accept_handshake(old, CoordinatorServer, &[DropDatabase]).await; + read_request(&mut first, DropDatabase).await; + drop(first); + let mut ts = accept_handshake(tablet, TabletServer, &[MetaData]).await; + serve_success(&mut ts, MetaData, &nodes).await; + let mut cs = accept_handshake(new, CoordinatorServer, &[DropDatabase]).await; + let rejected = read_request(&mut cs, DropDatabase).await; + reply_error(&mut cs, rejected, FlussError::NotCoordinatorLeaderException).await; + serve_success(&mut ts, MetaData, &nodes).await; + serve_success(&mut cs, DropDatabase, &DropDatabaseResponse {}).await; + }; + exchange(server, async { + let lost = admin.drop_database("ambiguous", false, false).await; + assert!(matches!(lost, Err(Error::RpcError { .. }))); + admin.drop_database("rejected", false, false).await.unwrap(); + }) + .await; +} diff --git a/fluss-rust/crates/fluss/src/client/mod.rs b/fluss-rust/crates/fluss/src/client/mod.rs index f8027948ae5..fdebaedabac 100644 --- a/fluss-rust/crates/fluss/src/client/mod.rs +++ b/fluss-rust/crates/fluss/src/client/mod.rs @@ -16,6 +16,7 @@ // under the License. mod admin; +mod admin_gateway; mod connection; mod credentials; pub mod lookup; diff --git a/fluss-rust/crates/fluss/src/cluster/cluster.rs b/fluss-rust/crates/fluss/src/cluster/cluster.rs index 87b3ce4cbae..0771b77f27a 100644 --- a/fluss-rust/crates/fluss/src/cluster/cluster.rs +++ b/fluss-rust/crates/fluss/src/cluster/cluster.rs @@ -331,7 +331,15 @@ impl Cluster { table_info_by_path.extend(origin.get_table_info_by_path().clone()); table_id_by_path.extend(origin.get_table_id_by_path().clone()); partitions_id_by_path.extend(origin.partitions_id_by_path.clone()); - tmp_available_locations_by_path.extend(origin.available_locations_by_path.clone()); + tmp_available_locations_by_path = origin.available_locations_by_path.clone(); + if servers != origin.alive_tablet_servers_by_id { + // A node list gives new endpoints but doesn't confirm bucket leadership there. + for location in tmp_available_locations_by_path.values_mut().flatten() { + location + .leader + .take_if(|leader| servers.get(&leader.id()) != Some(leader)); + } + } bucket_count_by_table_or_partition .extend(origin.bucket_count_by_table_or_partition.clone()); } diff --git a/fluss-rust/crates/fluss/src/rpc/message/mod.rs b/fluss-rust/crates/fluss/src/rpc/message/mod.rs index fcf55b5fba8..c97dfa0a6a9 100644 --- a/fluss-rust/crates/fluss/src/rpc/message/mod.rs +++ b/fluss-rust/crates/fluss/src/rpc/message/mod.rs @@ -162,6 +162,12 @@ where fn write(&self, writer: &mut W) -> Result<(), WriteError>; } +impl, W: BufMut> WriteType for &T { + fn write(&self, writer: &mut W) -> Result<(), WriteError> { + (**self).write(writer) + } +} + pub trait ReadType: Sized where R: Buf,