client/
client_manager.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
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
15use 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}