danube_client/client.rs
1use std::path::Path;
2use std::sync::Arc;
3use tonic::transport::{Certificate, ClientTlsConfig, Identity, Uri};
4
5use crate::{
6 auth_service::AuthService,
7 connection_manager::{ConnectionManager, ConnectionOptions},
8 consumer::ConsumerBuilder,
9 errors::Result,
10 health_check::HealthCheckService,
11 lookup_service::{LookupResult, LookupService},
12 producer::ProducerBuilder,
13};
14
15/// The main client for interacting with the Danube messaging system.
16///
17/// The `DanubeClient` struct is designed to facilitate communication with the Danube messaging system.
18/// It provides various methods for managing producers and consumers, performing topic lookups, and retrieving schema information. This client acts as the central interface for interacting with the messaging system and managing connections and services.
19#[derive(Debug, Clone)]
20pub struct DanubeClient {
21 pub(crate) uri: Uri,
22 pub(crate) cnx_manager: Arc<ConnectionManager>,
23 pub(crate) lookup_service: LookupService,
24 pub(crate) health_check_service: HealthCheckService,
25 pub(crate) auth_service: AuthService,
26}
27
28impl DanubeClient {
29 fn new_client(builder: DanubeClientBuilder, uri: Uri) -> Self {
30 let cnx_manager = ConnectionManager::new(builder.connection_options);
31 let cnx_manager = Arc::new(cnx_manager);
32
33 let auth_service = AuthService::new(cnx_manager.clone());
34
35 let lookup_service = LookupService::new(cnx_manager.clone(), auth_service.clone());
36
37 let health_check_service =
38 HealthCheckService::new(cnx_manager.clone(), auth_service.clone());
39
40 DanubeClient {
41 uri: uri.clone(),
42 cnx_manager,
43 lookup_service,
44 health_check_service,
45 auth_service,
46 }
47 }
48
49 /// Initializes a new `DanubeClientBuilder` instance.
50 ///
51 /// The builder pattern allows for configuring and constructing a `DanubeClient` instance with optional settings and options.
52 /// Using the builder, you can customize various aspects of the `DanubeClient`, such as connection settings, timeouts, and other configurations before creating the final `DanubeClient` instance.
53 pub fn builder() -> DanubeClientBuilder {
54 DanubeClientBuilder::default()
55 }
56
57 /// Returns a new `ProducerBuilder` for configuring and creating a `Producer` instance.
58 ///
59 /// This method initializes a `ProducerBuilder`, which is used to set up various options and settings for a `Producer`.
60 /// The builder pattern allows you to specify details such as the topic, producer name, partitions, schema, and other configurations before creating the final `Producer` instance.
61 pub fn new_producer(&self) -> ProducerBuilder {
62 ProducerBuilder::new(self)
63 }
64
65 /// Returns a new `ConsumerBuilder` for configuring and creating a `Consumer` instance.
66 ///
67 /// This method initializes a `ConsumerBuilder`, which is used to set up various options and settings for a `Consumer`.
68 /// The builder pattern allows you to specify details such as the topic, consumer name, subscription, subscription type, and other configurations before creating the final `Consumer` instance.
69 pub fn new_consumer(&self) -> ConsumerBuilder {
70 ConsumerBuilder::new(self)
71 }
72
73 /// Returns a reference to the `AuthService`.
74 ///
75 /// This method provides access to the `AuthService` instance used by the `DanubeClient`.
76 pub fn auth_service(&self) -> &AuthService {
77 &self.auth_service
78 }
79
80 /// Retrieves the address of the broker responsible for a specified topic.
81 ///
82 /// This asynchronous method performs a lookup to find the broker that is responsible for the given topic. The `addr` parameter specifies the address of the broker to connect to for performing the lookup. The method returns information about the broker handling the topic.
83 ///
84 /// # Parameters
85 ///
86 /// - `addr`: The address of the broker to connect to for the lookup. This is provided as a `&Uri`, which specifies where the request should be sent.
87 /// - `topic`: The name of the topic for which to look up the broker.
88 ///
89 /// # Returns
90 ///
91 /// - `Ok(LookupResult)`: Contains the result of the lookup operation, including the broker address.
92 /// - `Err(e)`: An error if the lookup fails or if there are issues during the operation. This could include connectivity problems, invalid topic names, or other errors related to the lookup process.
93 pub async fn lookup_topic(&self, addr: &Uri, topic: impl Into<String>) -> Result<LookupResult> {
94 self.lookup_service.lookup_topic(addr, topic).await
95 }
96}
97
98/// A builder for configuring and creating a `DanubeClient` instance.
99///
100/// The `DanubeClientBuilder` struct provides methods for setting various options needed to construct a `DanubeClient`. This includes configuring the base URI for the Danube service, connection settings.
101///
102/// # Fields
103///
104/// - `uri`: The base URI for the Danube service. This is a required field and specifies the address of the service that the client will connect to. It is essential for constructing the `DanubeClient`.
105/// - `connection_options`: Optional connection settings that define how the grpc client connects to the Danube service. These settings can include parameters such as timeouts, retries, and other connection-related configurations.
106#[derive(Debug, Clone, Default)]
107pub struct DanubeClientBuilder {
108 uri: String,
109 connection_options: ConnectionOptions,
110 api_key: Option<String>,
111}
112
113impl DanubeClientBuilder {
114 /// Sets the base URI for the Danube service in the builder.
115 ///
116 /// This method configures the base URI that the `DanubeClient` will use to connect to the Danube service. The base URI is a required parameter for establishing a connection and interacting with the service.
117 ///
118 /// # Parameters
119 ///
120 /// - `url`: The base URI to use for connecting to the Danube service. The URI should include the protocol and address of the Danube service.
121 pub fn service_url(mut self, url: impl Into<String>) -> Self {
122 self.uri = url.into();
123 self
124 }
125
126 /// Sets the TLS configuration for the client in the builder.
127 pub fn with_tls(mut self, ca_cert: impl AsRef<Path>) -> Result<Self> {
128 let tls_config =
129 ClientTlsConfig::new().ca_certificate(Certificate::from_pem(std::fs::read(ca_cert)?));
130 self.connection_options.tls_config = Some(tls_config);
131 self.connection_options.use_tls = true;
132 Ok(self)
133 }
134
135 /// Sets the mutual TLS configuration for the client in the builder.
136 pub fn with_mtls(
137 mut self,
138 ca_cert: impl AsRef<Path>,
139 client_cert: impl AsRef<Path>,
140 client_key: impl AsRef<Path>,
141 ) -> Result<Self> {
142 let ca_data = std::fs::read(ca_cert)?;
143 let cert_data = std::fs::read(client_cert)?;
144 let key_data = std::fs::read(client_key)?;
145
146 let tls_config = ClientTlsConfig::new()
147 .ca_certificate(Certificate::from_pem(ca_data))
148 .identity(Identity::from_pem(cert_data, key_data));
149
150 self.connection_options.tls_config = Some(tls_config);
151 self.connection_options.use_tls = true;
152 Ok(self)
153 }
154
155 /// Sets the API key for the client in the builder.
156 pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
157 self.api_key = Some(api_key.into());
158 self.connection_options.use_tls = true; // API key automatically enables TLS
159 self
160 }
161
162 /// Constructs and returns a `DanubeClient` instance based on the configuration specified in the builder.
163 ///
164 /// This method finalizes the configuration and creates a new `DanubeClient` instance. It uses the settings and options that were configured using the `DanubeClientBuilder` methods.
165 ///
166 /// # Returns
167 ///
168 /// - `Ok(DanubeClient)`: A new instance of `DanubeClient` configured with the specified options.
169 /// - `Err(e)`: An error if the configuration is invalid or incomplete.
170 pub async fn build(mut self) -> Result<DanubeClient> {
171 let uri = self.uri.parse::<Uri>()?;
172 let cnx_manager = Arc::new(ConnectionManager::new(self.connection_options.clone()));
173 let auth_service = AuthService::new(cnx_manager.clone());
174
175 if let Some(api_key) = self.api_key.clone() {
176 self.connection_options.api_key = Some(api_key.clone());
177 let token = auth_service.authenticate_client(&uri, &api_key).await?;
178 self.connection_options.jwt_token = Some(token);
179 }
180
181 Ok(DanubeClient::new_client(self, uri))
182 }
183}