1use std::fmt::{Debug, Formatter};
16use std::sync::Arc;
17use std::time::Duration;
18
19use common_grpc::channel_manager::{ChannelConfig, ChannelManager};
20use common_meta::node_manager::{DatanodeRef, FlownodeRef, NodeManager};
21use common_meta::peer::Peer;
22use moka::future::{Cache, CacheBuilder};
23
24use crate::flow::FlowRequester;
25use crate::region::RegionRequester;
26use crate::Client;
27
28pub struct NodeClients {
29 channel_manager: ChannelManager,
30 clients: Cache<Peer, Client>,
31}
32
33impl Default for NodeClients {
34 fn default() -> Self {
35 Self::new(ChannelConfig::new())
36 }
37}
38
39impl Debug for NodeClients {
40 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
41 f.debug_struct("NodeClients")
42 .field("channel_manager", &self.channel_manager)
43 .finish()
44 }
45}
46
47#[async_trait::async_trait]
48impl NodeManager for NodeClients {
49 async fn datanode(&self, datanode: &Peer) -> DatanodeRef {
50 let client = self.get_client(datanode).await;
51
52 Arc::new(RegionRequester::new(client))
53 }
54
55 async fn flownode(&self, flownode: &Peer) -> FlownodeRef {
56 let client = self.get_client(flownode).await;
57
58 Arc::new(FlowRequester::new(client))
59 }
60}
61
62impl NodeClients {
63 pub fn new(config: ChannelConfig) -> Self {
64 Self {
65 channel_manager: ChannelManager::with_config(config),
66 clients: CacheBuilder::new(1024)
67 .time_to_live(Duration::from_secs(30 * 60))
68 .time_to_idle(Duration::from_secs(5 * 60))
69 .build(),
70 }
71 }
72
73 pub async fn get_client(&self, datanode: &Peer) -> Client {
74 self.clients
75 .get_with_by_ref(datanode, async move {
76 Client::with_manager_and_urls(
77 self.channel_manager.clone(),
78 vec![datanode.addr.clone()],
79 )
80 })
81 .await
82 }
83
84 #[cfg(feature = "testing")]
85 pub async fn insert_client(&self, datanode: Peer, client: Client) {
86 self.clients.insert(datanode, client).await
87 }
88}