lake-pulse 0.1.0

A Rust library for analyzing data lake table health across multiple formats and storage providers.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright 2025 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
//
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use crate::storage::error::StorageError;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Storage provider type
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum StorageType {
    /// Local filesystem storage
    Local,
    /// AWS S3 storage
    Aws,
    /// Azure Data Lake Storage
    Azure,
    /// Google Cloud Storage
    Gcs,
}

/// Generic configuration for storage providers using object_store
///
/// This configuration uses a HashMap to store provider-specific options,
/// which are passed directly to the object_store builders. This approach
/// leverages object_store's built-in configuration system and reduces
/// the need for custom configuration structs.
///
/// # Examples
///
/// ## Local filesystem
/// ```
/// use lake_pulse::storage::StorageConfig;
///
/// let config = StorageConfig::local()
///     .with_option("path", "/tmp/data");
/// ```
///
/// ## AWS S3
/// ```
/// use lake_pulse::storage::StorageConfig;
///
/// let config = StorageConfig::new("s3")
///     .with_option("bucket", "my-bucket")
///     .with_option("region", "us-east-1")
///     .with_option("access_key_id", "ACCESS_KEY")
///     .with_option("secret_access_key", "SECRET_ACCESS_KEY");
/// ```
///
/// ## Azure
/// ```
/// use lake_pulse::storage::StorageConfig;
///
/// let config = StorageConfig::new("azure")
///     .with_option("container", "mycontainer")
///     .with_option("account_name", "myaccount")
///     .with_option("access_key", "ACCOUNT_KEY");
/// ```
///
/// ## GCS
/// ```
/// use lake_pulse::storage::StorageConfig;
///
/// let config = StorageConfig::new("gcs")
///     .with_option("bucket", "my-bucket")
///     .with_option("service_account_key_path", "/path/to/key.json");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Storage provider type
    #[serde(rename = "type")]
    pub storage_type: StorageType,

    /// Provider-specific configuration options
    ///
    /// These options are passed directly to the object_store builders.
    /// Common options include:
    ///
    /// AWS S3:
    /// - bucket: Bucket name
    /// - region: AWS region (e.g., "us-east-1")
    /// - access_key_id: AWS access key ID
    /// - secret_access_key: AWS secret access key
    /// - session_token: AWS session token (for temporary credentials)
    /// - endpoint: Custom endpoint URL (for S3-compatible services)
    /// - allow_http: "true" to allow HTTP connections
    ///
    /// Azure:
    /// - container: Container name
    /// - account_name: Storage account name
    /// - access_key: Account key
    /// - sas_token: SAS token
    /// - tenant_id: Azure AD tenant ID
    /// - client_id: Azure AD client ID
    /// - client_secret: Azure AD client secret
    ///
    /// GCS:
    /// - bucket: Bucket name
    /// - service_account_key_path: Path to service account JSON key file
    /// - service_account_key: Service account key as JSON string
    ///
    /// Local:
    /// - path: Base path
    #[serde(default)]
    pub options: HashMap<String, String>,
}

impl StorageConfig {
    /// Create a new storage configuration.
    ///
    /// # Arguments
    ///
    /// * `storage_type` - The type of storage provider ("local", "aws", "azure", "gcs")
    ///
    /// # Returns
    ///
    /// A new `StorageConfig` instance with default options for the specified storage type.
    ///
    /// # Panics
    ///
    /// Panics if the storage type is not recognized. Use [`try_new`](Self::try_new)
    /// for a fallible version that returns a `Result`.
    pub fn new(storage_type: impl Into<String>) -> Self {
        let storage_type_str: String = storage_type.into();
        Self::try_new(&storage_type_str)
            .unwrap_or_else(|_| panic!("Unknown storage type: {}", storage_type_str))
    }

    /// Try to create a new storage configuration.
    ///
    /// This is the fallible version of [`new`](Self::new) that returns a `Result`
    /// instead of panicking on invalid input.
    ///
    /// # Arguments
    ///
    /// * `storage_type` - The type of storage provider ("local", "aws", "azure", "gcs")
    ///
    /// # Returns
    ///
    /// * `Ok(StorageConfig)` - A new configuration with default options
    /// * `Err(StorageError)` - If the storage type is not recognized
    ///
    /// # Examples
    ///
    /// ```
    /// use lake_pulse::storage::StorageConfig;
    ///
    /// let config = StorageConfig::try_new("aws")?;
    /// # Ok::<(), lake_pulse::storage::StorageError>(())
    /// ```
    pub fn try_new(storage_type: impl Into<String>) -> Result<Self, StorageError> {
        let storage_type_str = storage_type.into();
        let storage_type = match storage_type_str.to_lowercase().as_str() {
            "local" => StorageType::Local,
            "aws" | "s3" => StorageType::Aws,
            "azure" => StorageType::Azure,
            "gcs" | "gcp" => StorageType::Gcs,
            _ => {
                return Err(StorageError::ConfigError(format!(
                    "Unknown storage type: {}",
                    storage_type_str
                )))
            }
        };

        Ok(Self {
            storage_type,
            options: Self::default_options(),
        })
    }

    /// Create a local filesystem storage configuration.
    ///
    /// # Returns
    ///
    /// A new `StorageConfig` instance configured for local filesystem access with default options.
    pub fn local() -> Self {
        Self {
            storage_type: StorageType::Local,
            options: Self::default_options(),
        }
    }

    /// Create an AWS S3 storage configuration.
    ///
    /// # Returns
    ///
    /// A new `StorageConfig` instance configured for AWS S3 access with default options.
    pub fn aws() -> Self {
        Self {
            storage_type: StorageType::Aws,
            options: Self::default_options(),
        }
    }

    /// Create an Azure storage configuration.
    ///
    /// # Returns
    ///
    /// A new `StorageConfig` instance configured for Azure Blob Storage access with default options.
    pub fn azure() -> Self {
        Self {
            storage_type: StorageType::Azure,
            options: Self::default_options(),
        }
    }

    /// Create a GCS storage configuration.
    ///
    /// # Returns
    ///
    /// A new `StorageConfig` instance configured for Google Cloud Storage access.
    pub fn gcs() -> Self {
        Self {
            storage_type: StorageType::Gcs,
            options: HashMap::new(),
        }
    }

    /// Get default options for all storage types.
    ///
    /// # Returns
    ///
    /// A HashMap containing default timeout, retry, and connection pool settings.
    pub fn default_options() -> HashMap<String, String> {
        [
            ("timeout", "1200"),
            ("connect_timeout", "30"),
            ("max_retries", "20"),
            ("retry_timeout", "1200"),
            ("pool_idle_timeout", "15"),
            ("pool_max_idle_per_host", "5"),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect()
    }

    /// Add a configuration option.
    ///
    /// # Arguments
    ///
    /// * `key` - The option key
    /// * `value` - The option value
    ///
    /// # Returns
    ///
    /// The `StorageConfig` instance with the added option (for method chaining).
    pub fn with_option(
        mut self,
        key: impl Into<String> + Clone,
        value: impl Into<String> + Clone,
    ) -> Self {
        self.options.insert(key.into(), value.into());
        self
    }

    /// Add multiple configuration options.
    ///
    /// # Arguments
    ///
    /// * `options` - HashMap of options to add
    ///
    /// # Returns
    ///
    /// The `StorageConfig` instance with the added options (for method chaining).
    pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
        self.options.extend(options);
        self
    }

    /// Get a configuration option.
    ///
    /// # Arguments
    ///
    /// * `key` - The option key to retrieve
    ///
    /// # Returns
    ///
    /// `Some(&String)` if the option exists, `None` otherwise.
    pub fn get_option(&self, key: &str) -> Option<&String> {
        self.options.get(key)
    }

    /// Get the storage type as a string.
    ///
    /// # Returns
    ///
    /// A string slice representing the storage type ("local", "aws", "azure", or "gcs").
    pub fn storage_type_str(&self) -> &str {
        match self.storage_type {
            StorageType::Local => "local",
            StorageType::Aws => "aws",
            StorageType::Azure => "azure",
            StorageType::Gcs => "gcs",
        }
    }
}

impl From<StorageConfig> for String {
    fn from(config: StorageConfig) -> Self {
        config.storage_type_str().to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_storage_type_serialization() {
        // Test that StorageType serializes correctly
        let local = StorageType::Local;
        let aws = StorageType::Aws;
        let azure = StorageType::Azure;
        let gcs = StorageType::Gcs;

        assert_eq!(serde_json::to_string(&local).unwrap(), "\"local\"");
        assert_eq!(serde_json::to_string(&aws).unwrap(), "\"aws\"");
        assert_eq!(serde_json::to_string(&azure).unwrap(), "\"azure\"");
        assert_eq!(serde_json::to_string(&gcs).unwrap(), "\"gcs\"");
    }

    #[test]
    fn test_storage_type_deserialization() {
        // Test that StorageType deserializes correctly
        let local: StorageType = serde_json::from_str("\"local\"").unwrap();
        let aws: StorageType = serde_json::from_str("\"aws\"").unwrap();
        let azure: StorageType = serde_json::from_str("\"azure\"").unwrap();
        let gcs: StorageType = serde_json::from_str("\"gcs\"").unwrap();

        assert_eq!(local, StorageType::Local);
        assert_eq!(aws, StorageType::Aws);
        assert_eq!(azure, StorageType::Azure);
        assert_eq!(gcs, StorageType::Gcs);
    }

    #[test]
    fn test_storage_config_new_local() {
        let config = StorageConfig::new("local");
        assert_eq!(config.storage_type, StorageType::Local);
        assert!(!config.options.is_empty());
        assert_eq!(config.storage_type_str(), "local");
    }

    #[test]
    fn test_storage_config_new_aws() {
        let config1 = StorageConfig::new("aws");
        let config2 = StorageConfig::new("s3");
        let config3 = StorageConfig::new("AWS");

        assert_eq!(config1.storage_type, StorageType::Aws);
        assert_eq!(config2.storage_type, StorageType::Aws);
        assert_eq!(config3.storage_type, StorageType::Aws);
        assert_eq!(config1.storage_type_str(), "aws");
    }

    #[test]
    fn test_storage_config_new_azure() {
        let config = StorageConfig::new("azure");
        assert_eq!(config.storage_type, StorageType::Azure);
        assert_eq!(config.storage_type_str(), "azure");
    }

    #[test]
    fn test_storage_config_new_gcs() {
        let config1 = StorageConfig::new("gcs");
        let config2 = StorageConfig::new("gcp");

        assert_eq!(config1.storage_type, StorageType::Gcs);
        assert_eq!(config2.storage_type, StorageType::Gcs);
        assert_eq!(config1.storage_type_str(), "gcs");
    }

    #[test]
    #[should_panic(expected = "Unknown storage type")]
    fn test_storage_config_new_invalid() {
        StorageConfig::new("invalid");
    }

    #[test]
    fn test_storage_config_try_new_valid() {
        let config = StorageConfig::try_new("aws").unwrap();
        assert_eq!(config.storage_type, StorageType::Aws);

        let config = StorageConfig::try_new("s3").unwrap();
        assert_eq!(config.storage_type, StorageType::Aws);

        let config = StorageConfig::try_new("local").unwrap();
        assert_eq!(config.storage_type, StorageType::Local);

        let config = StorageConfig::try_new("azure").unwrap();
        assert_eq!(config.storage_type, StorageType::Azure);

        let config = StorageConfig::try_new("gcs").unwrap();
        assert_eq!(config.storage_type, StorageType::Gcs);

        let config = StorageConfig::try_new("gcp").unwrap();
        assert_eq!(config.storage_type, StorageType::Gcs);
    }

    #[test]
    fn test_storage_config_try_new_invalid() {
        let result = StorageConfig::try_new("invalid");
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unknown storage type"));
        assert!(err.to_string().contains("invalid"));
    }

    #[test]
    fn test_storage_config_local() {
        let config = StorageConfig::local();
        assert_eq!(config.storage_type, StorageType::Local);
        assert!(!config.options.is_empty());
    }

    #[test]
    fn test_storage_config_aws() {
        let config = StorageConfig::aws();
        assert_eq!(config.storage_type, StorageType::Aws);
        assert!(!config.options.is_empty());
    }

    #[test]
    fn test_storage_config_azure() {
        let config = StorageConfig::azure();
        assert_eq!(config.storage_type, StorageType::Azure);
        assert!(!config.options.is_empty());
    }

    #[test]
    fn test_storage_config_gcs() {
        let config = StorageConfig::gcs();
        assert_eq!(config.storage_type, StorageType::Gcs);
        // GCS has empty options by default
        assert!(config.options.is_empty());
    }

    #[test]
    fn test_default_options() {
        let options = StorageConfig::default_options();
        assert_eq!(options.get("timeout"), Some(&"1200".to_string()));
        assert_eq!(options.get("connect_timeout"), Some(&"30".to_string()));
        assert_eq!(options.get("max_retries"), Some(&"20".to_string()));
        assert_eq!(options.get("retry_timeout"), Some(&"1200".to_string()));
        assert_eq!(options.get("pool_idle_timeout"), Some(&"15".to_string()));
        assert_eq!(
            options.get("pool_max_idle_per_host"),
            Some(&"5".to_string())
        );
    }

    #[test]
    fn test_with_option() {
        let config = StorageConfig::local()
            .with_option("path", "/tmp/data")
            .with_option("custom_key", "custom_value");

        assert_eq!(config.get_option("path"), Some(&"/tmp/data".to_string()));
        assert_eq!(
            config.get_option("custom_key"),
            Some(&"custom_value".to_string())
        );
    }

    #[test]
    fn test_with_options() {
        let mut custom_options = HashMap::new();
        custom_options.insert("bucket".to_string(), "my-bucket".to_string());
        custom_options.insert("region".to_string(), "us-east-1".to_string());

        let config = StorageConfig::aws().with_options(custom_options);

        assert_eq!(config.get_option("bucket"), Some(&"my-bucket".to_string()));
        assert_eq!(config.get_option("region"), Some(&"us-east-1".to_string()));
        // Default options should still be present
        assert_eq!(config.get_option("timeout"), Some(&"1200".to_string()));
    }

    #[test]
    fn test_get_option() {
        let config = StorageConfig::local().with_option("path", "/tmp/data");

        assert_eq!(config.get_option("path"), Some(&"/tmp/data".to_string()));
        assert_eq!(config.get_option("nonexistent"), None);
    }

    #[test]
    fn test_storage_type_str() {
        assert_eq!(StorageConfig::local().storage_type_str(), "local");
        assert_eq!(StorageConfig::aws().storage_type_str(), "aws");
        assert_eq!(StorageConfig::azure().storage_type_str(), "azure");
        assert_eq!(StorageConfig::gcs().storage_type_str(), "gcs");
    }

    #[test]
    fn test_from_storage_config_to_string() {
        let local_str: String = StorageConfig::local().into();
        let aws_str: String = StorageConfig::aws().into();
        let azure_str: String = StorageConfig::azure().into();
        let gcs_str: String = StorageConfig::gcs().into();

        assert_eq!(local_str, "local");
        assert_eq!(aws_str, "aws");
        assert_eq!(azure_str, "azure");
        assert_eq!(gcs_str, "gcs");
    }

    #[test]
    fn test_method_chaining() {
        let config = StorageConfig::aws()
            .with_option("bucket", "my-bucket")
            .with_option("region", "us-west-2")
            .with_option("access_key_id", "AxxxxxxxxxNN7EXAMPLE");

        assert_eq!(config.storage_type, StorageType::Aws);
        assert_eq!(config.get_option("bucket"), Some(&"my-bucket".to_string()));
        assert_eq!(config.get_option("region"), Some(&"us-west-2".to_string()));
        assert_eq!(
            config.get_option("access_key_id"),
            Some(&"AxxxxxxxxxNN7EXAMPLE".to_string())
        );
    }

    #[test]
    fn test_config_serialization() {
        let config = StorageConfig::aws()
            .with_option("bucket", "test-bucket")
            .with_option("region", "us-east-1");

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"type\":\"aws\""));
        assert!(json.contains("\"bucket\""));
        assert!(json.contains("\"region\""));
    }

    #[test]
    fn test_config_deserialization() {
        let json = r#"{"type":"aws","options":{"bucket":"test-bucket","region":"us-east-1"}}"#;
        let config: StorageConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.storage_type, StorageType::Aws);
        assert_eq!(
            config.get_option("bucket"),
            Some(&"test-bucket".to_string())
        );
        assert_eq!(config.get_option("region"), Some(&"us-east-1".to_string()));
    }

    #[test]
    fn test_option_override() {
        let config = StorageConfig::local()
            .with_option("timeout", "600")
            .with_option("timeout", "900"); // Override previous value

        assert_eq!(config.get_option("timeout"), Some(&"900".to_string()));
    }

    #[test]
    fn test_clone() {
        let config1 = StorageConfig::aws().with_option("bucket", "my-bucket");
        let config2 = config1.clone();

        assert_eq!(config1.storage_type, config2.storage_type);
        assert_eq!(config1.get_option("bucket"), config2.get_option("bucket"));
    }
}