1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! Clients using ``kafka_threadpool`` get a
//! [`KafkaPublisher`](crate::kafka_publisher) object when calling
//! [`start_threadpool()`](crate::start_threadpool). The
//! [`KafkaPublisher`](crate::kafka_publisher) is how
//! callers interface with the ``kafka_threadpool``'s
//! ``lockable work Vec`` called ``publish_msgs``
//! and can gracefully shutdown the threadpool.
//!
//! Example for shutting down the threadpool:
//!
//! ```rust
//! my_kafka_publisher.shutdown().await.unwrap();
//! ```
//!
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;

use log::info;

use crate::api::add_messages_to_locked_work_vec::add_messages_to_locked_work_vec;
use crate::api::build_kafka_publish_message::build_kafka_publish_message;
use crate::api::drain_messages_from_locked_work_vec::drain_messages_from_locked_work_vec;
use crate::api::get_kafka_consumer::get_kafka_consumer;
use crate::api::kafka_publish_message::KafkaPublishMessage;
use crate::api::kafka_publish_message_type::KafkaPublishMessageType;
use crate::config::kafka_client_config::KafkaClientConfig;
use crate::metadata::get_kafka_metadata::get_kafka_metadata;

/// KafkaPublishMessage
///
/// API object for clients calling [`start_threadpool`]
///
/// * `config` - holds the static configuration for each
/// thread (connectivity endpoints, tls assets, etc.)
/// * `publish_msgs` - lockable work Vec that is shared
/// by any thread(s) that want to publish
/// [`KafkaPublishMessage`]
/// messages to Kafka
///
#[derive(Default, Clone)]
pub struct KafkaPublisher {
    pub config: KafkaClientConfig,
    pub publish_msgs: Arc<Mutex<Vec<KafkaPublishMessage>>>,
}

impl KafkaPublisher {
    /// new
    ///
    /// create a new singleton
    /// [`KafkaPublisher`](crate::kafka_publisher::KafkaPublisher)
    /// for interfacing with the backend kafka publish threadpool
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::kafka_publisher::KafkaPublisher;
    /// let kp = KafkaPublisher::new();
    /// ```
    ///
    pub fn new() -> Self {
        KafkaPublisher {
            config: KafkaClientConfig::new(
                &std::env::var("KAFKA_LOG_LABEL")
                    .unwrap_or_else(|_| "ktp".to_string()),
            ),
            publish_msgs: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// is_enabled
    ///
    /// Clients wanting to test if the threadpool is
    /// enabled can use this helper method.
    ///
    /// # Returns
    ///
    /// - ``true`` when the environment variable: ``KAFKA_ENABLED``
    ///   is set to ``true`` or ``1``
    /// - ``false`` when the environment variable: ``KAFKA_ENABLED``
    ///   is set to anything but ``true`` or ``1``
    ///
    pub fn is_enabled(&self) -> bool {
        self.config.is_enabled
    }

    /// add_data_msg
    ///
    /// Build a publishable data message from function
    /// arguments and add it to the
    /// lockable publish vector. Client libraries that
    /// want to just send a single
    /// message without worrying about the
    /// ``KafkaPublishMessageType`` should use this function.
    ///
    /// # Arguments
    ///
    /// * `topic` - kafka topic to publish the message into
    /// * `key` - kafka partition key
    /// * `headers` - optional - headers for the kafka message
    /// * `payload` - data within the kafka message
    ///
    /// Uses the utility API method:
    /// [`add_messages_to_locked_work_vec`](crate::api::add_messages_to_locked_work_vec)
    ///
    /// # Returns
    ///
    /// ``Result<usize, String>``
    /// where
    /// - ``usize`` = updated number of messages in ``self.publish_msgs``
    /// after adding the new ``msg``
    /// - ``String`` = error reason
    ///
    pub async fn add_data_msg(
        &self,
        topic: &str,
        key: &str,
        headers: Option<HashMap<String, String>>,
        payload: &str,
    ) -> Result<usize, String> {
        if self.config.is_enabled {
            let msg = build_kafka_publish_message(
                KafkaPublishMessageType::Data,
                topic,
                key,
                headers,
                payload,
            );
            let pub_vec: Vec<KafkaPublishMessage> = vec![msg];
            add_messages_to_locked_work_vec(&self.publish_msgs, pub_vec)
        } else {
            Ok(0)
        }
    }

    /// add_msg
    ///
    /// Add a single message to the lockable publish vector
    ///
    /// # Arguments
    ///
    /// * `msg` - an initialized
    /// [`KafkaPublishMessage`](crate::api::kafka_publish_message::KafkaPublishMessage)
    /// to add to the lockable work vector: ``self.publish_msgs``
    ///
    /// Uses the utility API method:
    /// [`add_messages_to_locked_work_vec`](crate::api::add_messages_to_locked_work_vec)
    ///
    /// # Returns
    ///
    /// ``Result<usize, String>``
    /// where
    /// - ``usize`` = updated number of messages in ``self.publish_msgs``
    /// after adding the new ``msg``
    /// - ``String`` = error reason
    ///
    pub async fn add_msg(
        &self,
        msg: KafkaPublishMessage,
    ) -> Result<usize, String> {
        if self.config.is_enabled {
            let pub_vec: Vec<KafkaPublishMessage> = vec![msg];
            add_messages_to_locked_work_vec(&self.publish_msgs, pub_vec)
        } else {
            Ok(0)
        }
    }

    /// add_msgs
    ///
    /// Add a vector of messages to the lockable publish vector
    ///
    /// # Arguments
    ///
    /// * `msgs` - vector of
    /// [`KafkaPublishMessage`](crate::api::kafka_publish_message::KafkaPublishMessage)
    /// to add to the lockable work vector: ``self.publish_msgs``
    ///
    /// Uses the utility API method:
    /// [`add_messages_to_locked_work_vec`](crate::api::add_messages_to_locked_work_vec)
    ///
    /// # Returns
    ///
    /// ``Result<usize, String>``
    /// where
    /// - ``usize`` = updated number of messages in ``self.publish_msgs``
    /// after adding the new ``msgs``
    /// - ``String`` = error reason
    ///
    pub async fn add_msgs(
        &self,
        msgs: Vec<KafkaPublishMessage>,
    ) -> Result<usize, String> {
        if self.config.is_enabled {
            add_messages_to_locked_work_vec(&self.publish_msgs, msgs)
        } else {
            Ok(0)
        }
    }

    /// drain_msgs
    ///
    /// Helper function for testing - allows draining
    /// all data in the lockable work vec: ``self.publish_msgs``
    ///
    /// # Returns
    ///
    /// ``Vec<KafkaPublishMessage>`` containing all drained messages
    ///
    pub async fn drain_msgs(&self) -> Vec<KafkaPublishMessage> {
        if self.config.is_enabled {
            drain_messages_from_locked_work_vec(&self.publish_msgs)
        } else {
            vec![]
        }
    }

    /// shutdown
    ///
    /// Gracefully shutdown the threadpool by
    /// sending the ``Shutdown`` control
    /// message to all worker threads
    ///
    /// # Errors
    ///
    /// Threads may get hung if something goes wrong.
    ///
    /// # Examples
    ///
    /// ```rust
    /// my_threadpool.shutdown().await.unwrap();
    /// ```
    ///
    pub async fn shutdown(&self) -> Result<String, String> {
        if self.config.is_enabled {
            let shutdown_msg_vec: Vec<KafkaPublishMessage> =
                vec![build_kafka_publish_message(
                    KafkaPublishMessageType::Shutdown,
                    "",
                    "",
                    None,
                    "",
                )];
            info!("sending shutdown msg");
            match add_messages_to_locked_work_vec(
                &self.publish_msgs,
                shutdown_msg_vec,
            ) {
                Ok(_) => Ok("shutdown started".to_string()),
                Err(e) => Err(e),
            }
        } else {
            Ok("kafka not enabled".to_string())
        }
    }

    /// get_metadata
    ///
    /// Get kafka cluster information by all topics or for
    /// just one topic
    ///
    /// # Arguments
    ///
    /// * `fetch_offsets` - when ``true`` this function will count the total number
    /// of messages in each topic
    /// * `topic` - If set, only get the details for that specific topic if set to ``None``
    /// get details for all topics
    ///
    pub async fn get_metadata(&self, fetch_offsets: bool, topic: Option<&str>) {
        if self.config.is_enabled {
            info!("creating consumer");
            let consumer = get_kafka_consumer(&self.config);
            get_kafka_metadata(&self.config, consumer, fetch_offsets, topic)
        } else {
            info!("kafka not enabled KAFKA_ENABLED={}", self.config.is_enabled);
        }
    }
}