dsh_sdk 0.8.1

SDK for KPN Data Services Hub
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! High-level API for interacting with DSH when your container is running on DSH.
//!
//! From [`Dsh`] you can retrieve the correct configuration to connect to Kafka and the schema store.
//!
//! For more low-level functions, see the [`datastream`] and [`certificates`] modules.
//!
//! ## Environment Variables
//! Refer to [`ENV_VARIABLES.md`](https://github.com/kpn-dsh/dsh-sdk-platform-rs/blob/main/dsh_sdk/ENV_VARIABLES.md)
//! for more information on configuring the consumer or producer via environment variables.
//!
//! # Example
//! ```no_run
//! use dsh_sdk::Dsh;
//! use rdkafka::consumer::{Consumer, StreamConsumer};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let dsh = Dsh::get();
//! let certificates = dsh.certificates()?;
//! let datastreams = dsh.datastream();
//! let kafka_config = dsh.kafka_config();
//! let tenant_name = dsh.tenant_name();
//! let task_id = dsh.task_id();
//! # Ok(())
//! # }
//! ```
use log::{info, warn};
use std::sync::{Arc, OnceLock};

use crate::certificates::{Cert, CertificatesError};
use crate::datastream::Datastream;
use crate::error::DshError;
use crate::utils;
use crate::*;

#[cfg(feature = "kafka")]
use crate::protocol_adapters::kafka_protocol::config::KafkaConfig;

/// Lazily initializes all related components to connect to DSH and Kafka.
/// - Information from `datastreams.json`
/// - Metadata of the running container/task
/// - Certificates for Kafka and DSH Schema Registry
///
/// ## Environment Variables
/// Refer to [`ENV_VARIABLES.md`](https://github.com/kpn-dsh/dsh-sdk-platform-rs/blob/main/dsh_sdk/ENV_VARIABLES.md)
/// for details on configuring the consumer or producer via environment variables.
#[derive(Debug, Clone)]
pub struct Dsh {
    config_host: String,
    task_id: String,
    tenant_name: String,
    datastream: Arc<Datastream>,
    certificates: Option<Cert>,
    #[cfg(feature = "kafka")]
    kafka_config: KafkaConfig,
}

impl Dsh {
    /// Constructs a new `Dsh` struct. This is internal and should typically be accessed via [`Dsh::get()`].
    pub(crate) fn new(
        config_host: String,
        task_id: String,
        tenant_name: String,
        datastream: Datastream,
        certificates: Option<Cert>,
    ) -> Self {
        let datastream = Arc::new(datastream);
        Self {
            config_host,
            task_id,
            tenant_name,
            datastream: datastream.clone(),
            certificates,
            #[cfg(feature = "kafka")]
            kafka_config: KafkaConfig::new(Some(datastream)),
        }
    }

    /// Returns a reference to the global `Dsh` instance, initializing it if necessary.
    ///
    /// This struct contains configuration and certificates needed to connect to Kafka and DSH:
    /// - A struct mirroring `datastreams.json`
    /// - Metadata for the running container/task
    /// - Certificates for Kafka and DSH
    ///
    /// # Panics
    /// Panics if attempting to load an incorrect `local_datastream.json` on a local machine.
    /// If no file is available or the `LOCAL_DATASTREAMS_JSON` env variable is unset, it returns a default
    /// `datastream` struct and does **not** panic.
    ///
    /// # Example
    /// ```
    /// use dsh_sdk::Dsh;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dsh = Dsh::get();
    /// let datastreams = dsh.datastream();
    /// # Ok(())
    /// # }
    /// ```
    pub fn get() -> &'static Self {
        static PROPERTIES: OnceLock<Dsh> = OnceLock::new();
        PROPERTIES.get_or_init(|| tokio::task::block_in_place(Self::init))
    }

    /// Initializes the properties and bootstraps to DSH.
    fn init() -> Self {
        let tenant_name = utils::tenant_name().unwrap_or_else(|_| "local_tenant".to_string());
        let task_id =
            utils::get_env_var(VAR_TASK_ID).unwrap_or_else(|_| "local_task_id".to_string());
        let config_host =
            utils::get_env_var(VAR_DSH_KAFKA_CONFIG_ENDPOINT).map(utils::ensure_https_prefix);

        let certificates = if let Ok(cert) = Cert::from_pki_config_dir::<std::path::PathBuf>(None) {
            Some(cert)
        } else if let Ok(config_host) = &config_host {
            Cert::from_bootstrap(config_host, &tenant_name, &task_id)
                .inspect_err(|e| warn!("Could not bootstrap to DSH, due to: {}", e))
                .inspect(|_| info!("Successfully connected to DSH"))
                .ok()
        } else {
            None
        };

        let config_host = config_host.unwrap_or_else(|_| DEFAULT_CONFIG_HOST.to_string());
        let fetched_datastreams = certificates.as_ref().and_then(|cert| {
            cert.reqwest_blocking_client_config()
                .build()
                .ok()
                .and_then(|client| {
                    Datastream::fetch_blocking(&client, &config_host, &tenant_name, &task_id).ok()
                })
        });

        let datastream = if let Some(datastream) = fetched_datastreams {
            datastream
        } else {
            warn!("Could not fetch datastreams.json; using local or default datastreams");
            Datastream::load_local_datastreams().unwrap_or_default()
        };

        Self::new(config_host, task_id, tenant_name, datastream, certificates)
    }

    /// Returns a `reqwest::ClientBuilder` configured to connect to the DSH Schema Registry.
    /// If certificates are present, SSL is used. Otherwise, it falls back to a non-SSL connection.
    ///
    /// # Example
    /// ```
    /// # use dsh_sdk::Dsh;
    /// # use reqwest::Client;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dsh = Dsh::get();
    /// let client = dsh.reqwest_client_config().build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn reqwest_client_config(&self) -> reqwest::ClientBuilder {
        if let Ok(certificates) = &self.certificates() {
            certificates.reqwest_client_config()
        } else {
            reqwest::Client::builder()
        }
    }

    /// Returns a `reqwest::blocking::ClientBuilder` configured to connect to the DSH Schema Registry.
    /// If certificates are present, SSL is used. Otherwise, it falls back to a non-SSL connection.
    ///
    /// # Example
    /// ```
    /// # use dsh_sdk::Dsh;
    /// # use reqwest::blocking::Client;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dsh = Dsh::get();
    /// let client = dsh.reqwest_blocking_client_config().build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn reqwest_blocking_client_config(&self) -> reqwest::blocking::ClientBuilder {
        if let Ok(certificates) = &self.certificates() {
            certificates.reqwest_blocking_client_config()
        } else {
            reqwest::blocking::Client::builder()
        }
    }

    /// Retrieves the certificates and private key. Returns an error when running on a local machine.
    ///
    /// # Example
    /// ```no_run
    /// # use dsh_sdk::Dsh;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dsh = Dsh::get();
    /// let dsh_kafka_certificate = dsh.certificates()?.dsh_signed_certificate_pem();
    /// # Ok(())
    /// # }
    /// ```
    pub fn certificates(&self) -> Result<&Cert, DshError> {
        match &self.certificates {
            Some(cert) => Ok(cert),
            None => Err(CertificatesError::NoCertificates.into()),
        }
    }

    /// Returns the client ID derived from the task ID.
    pub fn client_id(&self) -> &str {
        &self.task_id
    }

    /// Returns the tenant name of the running container.
    pub fn tenant_name(&self) -> &str {
        &self.tenant_name
    }

    /// Returns the task ID of the running container.
    pub fn task_id(&self) -> &str {
        &self.task_id
    }

    /// Returns the current datastream object (fetched at initialization). This cannot be updated at runtime.
    pub fn datastream(&self) -> &Datastream {
        self.datastream.as_ref()
    }

    /// Fetches the latest datastream (Kafka properties) from DSH asynchronously.  
    /// This can be used to update the datastream during runtime.
    ///
    /// # Panics
    /// Panics if it fails to build a reqwest client.
    ///
    /// For a lower-level method allowing a custom client, see [`Datastream::fetch`].
    pub async fn fetch_datastream(&self) -> Result<Datastream, DshError> {
        static ASYNC_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

        let client = ASYNC_CLIENT.get_or_init(|| {
            self.reqwest_client_config()
                .build()
                .expect("Could not build reqwest client for fetching datastream")
        });

        Ok(Datastream::fetch(client, &self.config_host, &self.tenant_name, &self.task_id).await?)
    }

    /// Fetches the latest datastream from DSH in a blocking manner.  
    /// This can be used to update the datastream during runtime.
    ///
    /// # Panics
    /// Panics if it fails to build a reqwest blocking client.
    ///
    /// For a lower-level method allowing a custom client, see [`Datastream::fetch_blocking`].
    pub fn fetch_datastream_blocking(&self) -> Result<Datastream, DshError> {
        static BLOCKING_CLIENT: OnceLock<reqwest::blocking::Client> = OnceLock::new();

        let client = BLOCKING_CLIENT.get_or_init(|| {
            self.reqwest_blocking_client_config()
                .build()
                .expect("Could not build reqwest client for fetching datastream")
        });

        Ok(Datastream::fetch_blocking(
            client,
            &self.config_host,
            &self.tenant_name,
            &self.task_id,
        )?)
    }

    /// Returns the schema registry host as defined by the datastream.
    pub fn schema_registry_host(&self) -> &str {
        self.datastream().schema_store()
    }

    #[cfg(feature = "kafka")]
    /// Returns the [`KafkaConfig`] from this `Dsh` instance.
    pub fn kafka_config(&self) -> &KafkaConfig {
        &self.kafka_config
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::io::Read;

    impl Default for Dsh {
        fn default() -> Self {
            let datastream = Arc::new(Datastream::load_local_datastreams().unwrap_or_default());
            Self {
                task_id: "local_task_id".to_string(),
                tenant_name: "local_tenant".to_string(),
                config_host: "http://localhost/".to_string(),
                datastream,
                certificates: None,
                #[cfg(feature = "kafka")]
                kafka_config: KafkaConfig::default(),
            }
        }
    }

    // Helper to load test datastreams from a file.
    fn datastreams_json() -> String {
        std::fs::File::open("test_resources/valid_datastreams.json")
            .map(|mut file| {
                let mut contents = String::new();
                file.read_to_string(&mut contents).unwrap();
                contents
            })
            .unwrap()
    }

    // Helper to create a test Datastream.
    fn datastream() -> Datastream {
        serde_json::from_str(&datastreams_json()).unwrap()
    }

    #[test]
    #[serial(env_dependency)]
    fn test_get_or_init() {
        let properties = Dsh::get();
        assert_eq!(properties.client_id(), "local_task_id");
        assert_eq!(properties.task_id, "local_task_id");
        assert_eq!(properties.tenant_name, "local_tenant");
        assert_eq!(
            properties.config_host,
            "https://pikachu.dsh.marathon.mesos:4443"
        );
        assert!(properties.certificates.is_none());
    }

    #[test]
    #[serial(env_dependency)]
    fn test_reqwest_client_config() {
        let properties = Dsh::default();
        let _ = properties.reqwest_client_config();
        assert!(true);
    }

    #[test]
    #[serial(env_dependency)]
    fn test_client_id() {
        let properties = Dsh::default();
        assert_eq!(properties.client_id(), "local_task_id");
    }

    #[test]
    #[serial(env_dependency)]
    fn test_tenant_name() {
        let properties = Dsh::default();
        assert_eq!(properties.tenant_name(), "local_tenant");
    }

    #[test]
    #[serial(env_dependency)]
    fn test_task_id() {
        let properties = Dsh::default();
        assert_eq!(properties.task_id(), "local_task_id");
    }

    #[test]
    #[serial(env_dependency)]
    fn test_schema_registry_host() {
        let properties = Dsh::default();
        assert_eq!(
            properties.schema_registry_host(),
            "http://localhost:8081/apis/ccompat/v7"
        );
    }

    #[tokio::test]
    async fn test_fetch_datastream() {
        let mut server = mockito::Server::new_async().await;
        let tenant = "test-tenant";
        let task_id = "test-task-id";
        let host = server.url();
        let prop = Dsh::new(
            host,
            task_id.to_string(),
            tenant.to_string(),
            Datastream::default(),
            None,
        );
        server
            .mock("GET", "/kafka/config/test-tenant/test-task-id")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(datastreams_json())
            .create();
        let fetched_datastream = prop.fetch_datastream().await.unwrap();
        assert_eq!(fetched_datastream, datastream());
    }

    #[test]
    fn test_fetch_blocking_datastream() {
        let mut dsh = mockito::Server::new();
        let tenant = "test-tenant";
        let task_id = "test-task-id";
        let host = dsh.url();
        let prop = Dsh::new(
            host,
            task_id.to_string(),
            tenant.to_string(),
            Datastream::default(),
            None,
        );
        dsh.mock("GET", "/kafka/config/test-tenant/test-task-id")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(datastreams_json())
            .create();
        let fetched_datastream = prop.fetch_datastream_blocking().unwrap();
        assert_eq!(fetched_datastream, datastream());
    }
}