apollo-rust-client 0.7.0

A Rust client for Apollo configuration center
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Caching system for Apollo configuration data.
//!
//! This module provides the `Cache` struct and related functionality for storing and managing
//! Apollo configuration data. The cache supports both in-memory and file-based storage with
//! platform-specific optimizations.
//!
//! # Features
//!
//! - **Multi-Level Caching**: In-memory cache with optional file-based persistence
//! - **Thread Safety**: All cache operations are thread-safe and async-friendly
//! - **Event System**: Support for event listeners on configuration changes
//! - **Platform Optimization**: Different behavior for native Rust vs WebAssembly
//! - **Concurrent Access Control**: Prevents race conditions during cache operations
//!
//! # Cache Hierarchy
//!
//! 1. **Memory Cache**: Fast in-memory storage for immediate access
//! 2. **File Cache** (native only): Persistent storage to reduce network requests
//! 3. **Remote Fetch**: Retrieval from Apollo server when cache misses occur
//!
//! # Platform Differences
//!
//! - **Native Rust**: Full caching with file persistence and background refresh
//! - **WebAssembly**: Persistent caching using browser localStorage with in-memory fallback for Node.js environments
//!
//! # Examples
//!
//! The cache is typically used internally by the `Client` struct and not directly
//! by end users. However, understanding its behavior is important for debugging
//! and performance optimization.

use crate::{
    EventListener,
    client_config::ClientConfig,
    namespace::{self, get_namespace},
};
use tokio::sync::RwLock;
use base64::display::Base64Display;
use cfg_if::cfg_if;
use chrono::Utc;
use hmac::{Hmac, KeyInit, Mac};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha1::Sha1;
use std::{fmt::Write, sync::Arc};
use tokio::sync::Notify;
use url::{ParseError, Url};

#[derive(Serialize, Deserialize)]
struct CacheItem {
    timestamp: i64,
    config: Value,
}

/// Comprehensive error types that can occur during cache operations.
///
/// This enum covers all possible error conditions that may arise during cache
/// operations, from I/O failures to network and parsing issues.
///
/// # Error Categories
///
/// - **I/O Errors**: File system operations, directory creation, and file writing
/// - **Namespace Errors**: Issues with namespace format detection and processing
/// - **Serialization Errors**: JSON parsing and serialization failures
/// - **Network Errors**: HTTP request failures and response parsing issues
/// - **URL Errors**: Malformed URLs and parsing failures
///
/// # Examples
///
/// ```rust,ignore
/// use apollo_rust_client::cache::Error;
///
/// // Example of handling different cache error types
/// fn handle_cache_error(error: Error) {
///     match error {
///         Error::Io(io_error) => {
///             // Handle file system errors
///             eprintln!("I/O error: {}", io_error);
///         }
///         Error::Reqwest(reqwest_error) => {
///             // Handle network errors
///             eprintln!("Network error: {}", reqwest_error);
///         }
///         Error::Serde(serde_error) => {
///             // Handle JSON parsing errors
///             eprintln!("JSON error: {}", serde_error);
///         }
///         Error::Namespace(namespace_error) => {
///             // Handle namespace errors
///             eprintln!("Namespace error: {}", namespace_error);
///         }
///         Error::NamespaceNotFound(namespace) => {
///             // Handle namespace not found
///             eprintln!("Namespace not found: {}", namespace);
///         }
///         Error::UrlParse(url_error) => {
///             // Handle URL parsing errors
///             eprintln!("URL parse error: {}", url_error);
///         }
///     }
/// }
/// ```
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// An I/O error occurred during file operations.
    ///
    /// This error occurs when there are issues with file system operations,
    /// such as reading/writing cache files, creating directories, or
    /// insufficient permissions.
    #[error("Io error: {0}")]
    Io(#[from] std::io::Error),

    /// An error occurred during namespace processing.
    ///
    /// This includes errors from format detection, parsing, or type conversion
    /// operations specific to namespace handling.
    #[error("Namespace error: {0}")]
    Namespace(namespace::Error),

    /// A serialization/deserialization error occurred.
    ///
    /// This error occurs when there are issues with JSON parsing, such as
    /// malformed JSON data, type mismatches, or encoding problems.
    #[error("Serde error: {0}")]
    Serde(#[from] serde_json::Error),

    /// The requested namespace was not found.
    ///
    /// This error occurs when attempting to access a namespace that doesn't
    /// exist in the cache or when the cache has not been properly initialized.
    #[error("Namespace not found: {0}")]
    NamespaceNotFound(String),

    /// A network request error occurred.
    ///
    /// This error occurs when there are issues with HTTP requests to the
    /// Apollo server, such as connection failures, timeouts, or invalid responses.
    #[error("Reqwest error: {0}")]
    Reqwest(#[from] reqwest::Error),

    /// A URL parsing error occurred.
    ///
    /// This error occurs when the constructed URL for the Apollo server
    /// is malformed or cannot be parsed.
    #[error("Url parse error: {0}")]
    UrlParse(#[from] url::ParseError),
}

/// A cache instance for managing configuration data for a specific namespace.
///
/// The `Cache` struct is responsible for storing, retrieving, and managing configuration
/// data for a single Apollo namespace. It provides multi-level caching with thread-safe
/// operations and event notification capabilities.
///
/// # Features
///
/// - **Multi-Level Storage**: Memory cache with optional file-based persistence
/// - **Thread Safety**: All operations are protected by async-aware locks
/// - **Event Listeners**: Callbacks for configuration change notifications
/// - **Concurrent Protection**: Prevents race conditions during cache operations
/// - **Platform Optimization**: Adapts behavior based on target platform
///
/// # Cache Levels
///
/// 1. **Memory Cache**: Fast in-memory storage using `Arc<RwLock<Option<Value>>>`
/// 2. **File Cache** (native only): Persistent JSON files for offline access
/// 3. **Remote Source**: Apollo Configuration Center via HTTP/HTTPS
///
/// # Concurrency Control
///
/// The cache uses `tokio::sync::RwLock` to ensure thread-safety.
/// The `memory` field is wrapped in an `Arc<RwLock<...>>` to allow multiple
/// concurrent readers and exclusive writers. This prevents data races when
/// accessing the cached configuration from multiple async tasks. The listeners
/// are also protected by a `RwLock`.
///
/// # Platform Differences
///
/// - **Native Rust**: Full feature set with file caching and background refresh
/// - **WebAssembly**: Persistent caching using browser localStorage with in-memory fallback and single-threaded execution
#[derive(Clone)]
pub(crate) struct Cache {
    /// Client configuration containing server details and authentication.
    client_config: ClientConfig,

    /// The namespace name this cache instance manages.
    namespace: String,

    /// In-memory storage for the parsed configuration data.
    ///
    /// Contains the JSON representation of the configuration. `None` indicates
    /// that the cache has not been populated or a fetch operation failed.
    memory: Arc<RwLock<Option<Value>>>,

    /// Collection of event listeners for configuration change notifications.
    ///
    /// Listeners are called when the cache is refreshed, allowing applications
    /// to react to configuration changes in real-time.
    listeners: Arc<RwLock<Vec<EventListener>>>,

    /// The isolated cache key for WebAssembly localStorage persistence (wasm32 targets only).
    #[cfg(target_arch = "wasm32")]
    wasm_cache_key: String,

    /// Flag indicating whether a fetch operation is currently in progress.
    ///
    /// This prevents multiple threads from simultaneously fetching the same
    /// configuration data, which could cause duplicate network requests.
    loading: Arc<RwLock<bool>>,

    /// Notification mechanism for waiting threads when loading completes.
    ///
    /// This allows threads to wait efficiently for loading completion instead
    /// of using busy-wait loops.
    loading_complete: Arc<Notify>,

    /// Path to the local cache file (native targets only).
    ///
    /// On native targets, this specifies where the configuration should be
    /// cached locally. The path includes the namespace name and any grayscale
    /// targeting parameters (IP, labels) to ensure cache isolation.
    #[cfg(not(target_arch = "wasm32"))]
    file_path: std::path::PathBuf,

    /// HTTP client for making network requests.
    http_client: reqwest::Client,
}

impl Cache {
    /// Create a new cache.
    ///
    /// # Arguments
    ///
    /// * `client_config` - The configuration for the Apollo client.
    /// * `namespace` - The namespace to get the cache for.
    /// * `http_client` - The HTTP client to use for requests.
    ///
    /// # Returns
    ///
    /// A new cache for the given namespace.
    pub(crate) fn new(
        client_config: ClientConfig,
        namespace: &str,
        http_client: reqwest::Client,
    ) -> Self {
        let mut file_name = namespace.to_string();
        if let Some(ip) = &client_config.ip {
            let _ = write!(file_name, "_{ip}");
        }
        if let Some(label) = &client_config.label {
            let _ = write!(file_name, "_{label}");
        }

        #[cfg(not(target_arch = "wasm32"))]
        let file_path = client_config
            .get_cache_dir()
            .join(format!("{file_name}.cache.json"));

        #[cfg(target_arch = "wasm32")]
        let mut wasm_cache_key = format!(
            "apollo_cache_{}_{}_{}",
            client_config.app_id,
            client_config.cluster,
            namespace
        );
        #[cfg(target_arch = "wasm32")]
        {
            if let Some(ip) = &client_config.ip {
                let _ = write!(wasm_cache_key, "_{ip}");
            }
            if let Some(label) = &client_config.label {
                let _ = write!(wasm_cache_key, "_{label}");
            }
        }

        Self {
            client_config,
            namespace: namespace.to_string(),
            memory: Arc::new(RwLock::new(None)),
            listeners: Arc::new(RwLock::new(Vec::new())),
            loading: Arc::new(RwLock::new(false)),
            loading_complete: Arc::new(Notify::new()),

            #[cfg(not(target_arch = "wasm32"))]
            file_path,
            #[cfg(target_arch = "wasm32")]
            wasm_cache_key,
            http_client,
        }
    }

    /// Get a configuration from the cache.
    ///
    /// This method retrieves the configuration for the namespace. It implements a read-through
    /// cache pattern with the following logic:
    ///
    /// 1.  It first attempts to read from the in-memory cache. If the cache is populated,
    ///     it returns the configuration immediately. This read is non-blocking for other readers.
    /// 2.  If the in-memory cache is empty, it acquires a write lock. It checks again if the cache
    ///     was populated while waiting for the lock.
    /// 3.  If the cache is still empty, it proceeds to load it, first from the file cache (on native targets)
    ///     if it's not stale, otherwise by fetching from the remote Apollo server.
    /// 4.  Once the configuration is fetched, it updates the in-memory cache and notifies any
    ///     registered listeners.
    ///
    /// This entire process is thread-safe thanks to the `RwLock` on the `memory` field.
    ///
    /// # Returns
    ///
    /// * `Ok(Value)` - The configuration value if successfully retrieved.
    /// * `Err(Error)` - An error if the configuration could not be retrieved. See the `Error`
    ///   enum for possible variants.
    ///
    /// # Errors
    ///
    /// This method can return various errors, such as I/O errors when reading the file cache,
    /// network errors when fetching from the remote server, or parsing errors if the configuration
    /// data is malformed.
    pub(crate) async fn get_value(&self) -> Result<Value, Error> {
        // First check: fast path if data is already in memory
        if let Some(value) = self.memory.read().await.as_ref() {
            return Ok(value.clone());
        }

        // Second check: see if another thread is already loading, using a loop to avoid race conditions
        let should_load = loop {
            // Check if value is now in memory (could have been loaded while we waited)
            if let Some(value) = self.memory.read().await.as_ref() {
                return Ok(value.clone());
            }

            let mut loading = self.loading.write().await;
            if *loading {
                // Another thread is loading, wait for it to complete and re-check
                drop(loading);
                self.loading_complete.notified().await;
            } else {
                *loading = true;
                break true;
            }
        };

        // We're the loading thread, proceed with the fetch
        if should_load {
            let result = self.load_and_cache().await;

            // Always reset loading flag and notify waiting threads
            {
                let mut loading = self.loading.write().await;
                *loading = false;
            }
            self.loading_complete.notify_waiters();

            result
        } else {
            // This should not happen, but handle gracefully
            Err(Error::NamespaceNotFound(self.namespace.clone()))
        }
    }

    /// Internal method to load configuration and update cache.
    ///
    /// This method handles the actual loading logic with proper error handling
    /// and ensures the loading flag is always reset.
    async fn load_and_cache(&self) -> Result<Value, Error> {
        let mut w_lock = self.memory.write().await;

        // Double-check: another thread might have loaded it while we were waiting
        if let Some(value) = w_lock.as_ref() {
            return Ok(value.clone());
        }

        // Try to load from file cache first (native targets only)
        cfg_if! {
            if #[cfg(not(target_arch = "wasm32"))] {
                let file_path = self.file_path.clone();
                if file_path.exists()
                    && let Ok(file) = std::fs::File::open(&file_path)
                        && let Ok(cache_item) = serde_json::from_reader::<_, CacheItem>(file) {
                            let mut is_stale = false;
                            if let Some(ttl) = self.client_config.cache_ttl {
                                let age = Utc::now().timestamp() - cache_item.timestamp;
                                #[allow(clippy::cast_possible_wrap)]
                                if age > ttl as i64 {
                                    is_stale = true;
                                }
                            }

                            if !is_stale {
                                w_lock.replace(cache_item.config.clone());
                                let config = cache_item.config;
                                let listeners = self.listeners.read().await.clone();
                                drop(w_lock); // Release the lock before notifying listeners
                                self.notify_listeners(&config, &listeners);
                                return Ok(config);
                            }
                        }
            } else {
                if let Some(cached_str) = load_from_local_storage(&self.wasm_cache_key) {
                    if let Ok(cache_item) = serde_json::from_str::<CacheItem>(&cached_str) {
                        w_lock.replace(cache_item.config.clone());
                        let config = cache_item.config;
                        let listeners = self.listeners.read().await.clone();
                        drop(w_lock); // Release the lock before notifying listeners
                        self.notify_listeners(&config, &listeners);
                        return Ok(config);
                    }
                }
            }
        }

        // Load from remote server
        let config = self.fetch_remote_config().await?;
        w_lock.replace(config.clone());
        let listeners = self.listeners.read().await.clone();
        drop(w_lock); // Release the lock before notifying listeners
        self.notify_listeners(&config, &listeners);
        Ok(config)
    }

    /// Refreshes the cache by fetching the latest configuration from the Apollo server.
    ///
    /// This method unconditionally fetches the latest configuration from the remote server,
    /// updates the in-memory cache, writes to the file cache (on native targets), and
    /// notifies all registered listeners.
    ///
    /// The method acquires a write lock on the in-memory cache, ensuring that no other
    /// tasks can read or write to the cache while the refresh is in progress.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the cache was successfully refreshed.
    /// * `Err(Error)` - An error if the refresh operation failed.
    ///
    /// # Errors
    ///
    /// This method can return various errors, such as network errors, parsing errors,
    /// or I/O errors when writing to the file cache.
    pub(crate) async fn refresh(&self) -> Result<(), Error> {
        let (config, listeners) = {
            let mut w_lock = self.memory.write().await;
            let config = self.fetch_remote_config().await?;
            w_lock.replace(config.clone());
            let listeners = self.listeners.read().await.clone();
            (config, listeners)
        };
        self.notify_listeners(&config, &listeners);
        Ok(())
    }

    fn notify_listeners(&self, config: &Value, listeners: &[EventListener]) {
        for listener in listeners {
            let listener = listener.clone(); // Clone each listener individually
            let config = config.clone();
            let namespace = self.namespace.clone();

            cfg_if::cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    // For WASM, call listeners synchronously to avoid Send/Sync issues
                    listener(
                        get_namespace(&namespace, config).map_err(crate::Error::Namespace),
                    );
                } else {
                    // For native targets, spawn listener notifications as separate tasks to prevent deadlocks
                    tokio::spawn(async move {
                        listener(
                            get_namespace(&namespace, config).map_err(crate::Error::Namespace),
                        );
                    });
                }
            }
        }
    }

    async fn fetch_remote_config(&self) -> Result<Value, Error> {
        let url = self.build_request_url()?;
        let client = self.build_http_request(&url)?;

        // Add timeout to prevent long pauses
        #[cfg(target_arch = "wasm32")]
        let response = self.execute_request(client).await?;

        #[cfg(not(target_arch = "wasm32"))]
        let response = {
            let timeout_duration = std::time::Duration::from_secs(10);
            tokio::time::timeout(timeout_duration, self.execute_request(client))
                .await
                .map_err(|_| {
                    let io_error = std::io::Error::new(
                        std::io::ErrorKind::TimedOut,
                        "Request timeout after 10 seconds",
                    );
                    Error::Io(io_error)
                })??
        };

        let config = self.parse_response(response).await?;

        cfg_if! {
            if #[cfg(not(target_arch = "wasm32"))] {
                self.write_to_file_cache(&config)?;
            } else {
                let cache_item = CacheItem {
                    timestamp: chrono::Utc::now().timestamp(),
                    config: config.clone(),
                };
                if let Ok(cache_content) = serde_json::to_string(&cache_item) {
                    let _ = save_to_local_storage(&self.wasm_cache_key, &cache_content);
                }
            }
        }

        Ok(config)
    }

    /// Builds the request URL for the Apollo configuration service.
    ///
    /// Constructs the URL with the base path, app ID, cluster, and namespace,
    /// and adds optional query parameters for IP and label.
    ///
    /// # Returns
    ///
    /// * `Ok(Url)` - The constructed URL
    /// * `Err(Error::UrlParse)` - If URL parsing fails
    fn build_request_url(&self) -> Result<Url, Error> {
        let url = format!(
            "{}/configfiles/json/{}/{}/{}",
            self.client_config.config_server,
            self.client_config.app_id,
            self.client_config.cluster,
            self.namespace
        );

        let mut url = match Url::parse(&url) {
            Ok(u) => u,
            Err(e) => return Err(Error::UrlParse(e)),
        };

        if let Some(ip) = &self.client_config.ip {
            url.query_pairs_mut().append_pair("ip", ip);
        }
        if let Some(label) = &self.client_config.label {
            url.query_pairs_mut().append_pair("label", label);
        }

        Ok(url)
    }

    /// Builds the HTTP request with optional authentication headers.
    ///
    /// If a secret is configured, adds timestamp and authorization headers
    /// with HMAC-SHA1 signature.
    ///
    /// # Arguments
    ///
    /// * `url` - The request URL
    ///
    /// # Returns
    ///
    /// * `Ok(reqwest::RequestBuilder)` - The configured request builder
    /// * `Err(Error)` - If signature generation fails
    fn build_http_request(&self, url: &Url) -> Result<reqwest::RequestBuilder, Error> {
        let mut client = self.http_client.get(url.as_str());

        if let Some(secret) = &self.client_config.secret {
            let timestamp = Utc::now().timestamp_millis();
            let signature = sign(timestamp, url.as_str(), secret)?;
            client = client.header("timestamp", timestamp.to_string());
            client = client.header(
                "Authorization",
                format!("Apollo {}:{}", &self.client_config.app_id, signature),
            );
        }

        Ok(client)
    }

    /// Executes the HTTP request and returns the response.
    ///
    /// # Arguments
    ///
    /// * `client` - The configured request builder
    ///
    /// # Returns
    ///
    /// * `Ok(reqwest::Response)` - The HTTP response
    /// * `Err(Error::Reqwest)` - If the request fails
    async fn execute_request(
        &self,
        client: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, Error> {
        match client.send().await {
            Ok(r) => Ok(r),
            Err(e) => Err(Error::Reqwest(e)),
        }
    }

    /// Parses the HTTP response body as JSON configuration.
    ///
    /// # Arguments
    ///
    /// * `response` - The HTTP response
    ///
    /// # Returns
    ///
    /// * `Ok(Value)` - The parsed configuration
    /// * `Err(Error::Reqwest)` - If reading the response body fails
    /// * `Err(Error::Serde)` - If JSON parsing fails
    async fn parse_response(&self, response: reqwest::Response) -> Result<Value, Error> {
        let body: String = match response.text().await {
            Ok(b) => b,
            Err(e) => return Err(Error::Reqwest(e)),
        };

        trace!("Response body {} for namespace {}", body, self.namespace);

        match serde_json::from_str(&body) {
            Ok(c) => Ok(c),
            Err(e) => {
                debug!("error parsing config: {e}");
                Err(Error::Serde(e))
            }
        }
    }

    /// Writes the configuration to the file cache (native targets only).
    ///
    /// Creates parent directories if they don't exist and writes the cache item
    /// with timestamp and configuration data.
    ///
    /// # Arguments
    ///
    /// * `config` - The configuration to cache
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If caching succeeds
    /// * `Err(Error::Io)` - If file operations fail
    /// * `Err(Error::Serde)` - If serialization fails
    #[cfg(not(target_arch = "wasm32"))]
    fn write_to_file_cache(&self, config: &Value) -> Result<(), Error> {
        debug!("writing cache file {}", self.file_path.display());

        // Create parent directories if they don't exist
        if let Some(parent) = self.file_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let cache_item = CacheItem {
            timestamp: Utc::now().timestamp(),
            config: config.clone(),
        };

        let cache_content = serde_json::to_string(&cache_item)?;

        std::fs::write(&self.file_path, cache_content)?;
        trace!(
            "Wrote cache file {} for namespace {}",
            self.file_path.display(),
            self.namespace
        );

        Ok(())
    }

    /// Adds an event listener to the cache.
    ///
    /// Listeners are closures that will be called when the cache is successfully refreshed.
    /// The listener will receive a `Result<Value, Error>`, which will be `Ok(new_config)`
    /// containing the newly fetched configuration.
    ///
    ///
    /// The listener is a callback function that conforms to the [`EventListener`] type alias:
    /// `Arc<dyn Fn(Result<Value, Error>) + Send + Sync>`.
    ///
    /// - `Value` is `serde_json::Value` representing the full configuration for the namespace.
    /// - `Error` is `crate::cache::Error` indicating a failure during the refresh process.
    ///
    /// Listeners are called when the cache is successfully refreshed with new configuration,
    /// or when an error occurs during a refresh attempt.
    ///
    /// # Arguments
    ///
    /// * `listener` - The event listener to register. It must be an `Arc`-wrapped, thread-safe
    ///   closure (`Send + Sync`).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use serde_json::Value;
    /// use apollo_rust_client::cache::{Cache, Error, EventListener};
    /// // Assuming `cache` is an existing Arc<Cache> instance
    ///
    /// let listener: EventListener = Arc::new(|result: Result<Value, Error>| {
    ///     match result {
    ///         Ok(config) => println!("Cache refreshed, new config: {:?}", config),
    ///         Err(e) => println!("Cache refresh failed: {:?}", e),
    ///     }
    /// });
    /// cache.add_listener(listener).await;
    /// ```
    pub async fn add_listener(&self, listener: EventListener) {
        let mut listeners = self.listeners.write().await;
        listeners.push(listener);
    }

    /// Returns the WASM cache key (wasm32 targets only).
    #[cfg(target_arch = "wasm32")]
    pub(crate) fn wasm_cache_key(&self) -> &str {
        &self.wasm_cache_key
    }
}

type HmacSha1 = Hmac<Sha1>;

/// Generates a signature for Apollo API authentication using HMAC-SHA1.
///
/// This function takes a timestamp, the request URL (or its path and query), and an Apollo secret key
/// to create a Base64 encoded signature. This signature is typically used in the `Authorization`
/// header when making requests to the Apollo configuration service.
///
/// # Arguments
///
/// * `timestamp` - The current timestamp in milliseconds since the Unix epoch. This is used as part of the message to be signed.
/// * `url` - The URL being requested. This can be a full URL or just the path and query string.
/// * `secret` - The Apollo secret key used for generating the HMAC-SHA1 signature.
///
/// # Returns
///
/// * `Ok(String)` - A Base64 encoded string representing the signature
/// * `Err(Error::UrlParse)` - If URL parsing fails during signature generation
///
/// # Errors
///
/// This function will return an error if:
/// - The URL cannot be parsed (including relative URLs without a base)
/// - The URL structure is malformed
///
/// # Examples
///
/// ```rust,ignore
/// use apollo_rust_client::sign;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let signature = sign(1576478257344, "/configs/100004458/default/application?ip=10.0.0.1", "secret_key")?;
///     println!("Generated signature: {}", signature);
///     Ok(())
/// }
/// ```
pub(crate) fn sign(timestamp: i64, url: &str, secret: &str) -> Result<String, Error> {
    let u = match Url::parse(url) {
        Ok(u) => u,
        Err(e) => match e {
            ParseError::RelativeUrlWithoutBase => {
                let base_url = Url::parse("http://localhost:8080").unwrap();
                base_url.join(url).unwrap()
            }
            _ => {
                return Err(Error::UrlParse(e));
            }
        },
    };
    let mut path_and_query = String::from(u.path());
    if let Some(query) = u.query() {
        let _ = write!(path_and_query, "?{query}");
    }
    let input = format!("{timestamp}\n{path_and_query}");
    trace!("input for signing: {input}");

    let mut mac = HmacSha1::new_from_slice(secret.as_bytes()).unwrap();
    mac.update(input.as_bytes());
    let result: [u8; 20] = mac.finalize().into_bytes().into();

    // Convert the result to a string using base64
    let code = Base64Display::new(&result, &base64::engine::general_purpose::STANDARD);
    Ok(code.to_string())
}

#[cfg(target_arch = "wasm32")]
fn load_from_local_storage(key: &str) -> Option<String> {
    let global = js_sys::global();
    let storage = js_sys::Reflect::get(&global, &wasm_bindgen::JsValue::from_str("localStorage")).ok()?;
    if storage.is_undefined() || storage.is_null() {
        return None;
    }
    let get_item_fn = js_sys::Reflect::get(&storage, &wasm_bindgen::JsValue::from_str("getItem")).ok()?;
    if get_item_fn.is_function() {
        let args = js_sys::Array::of1(&wasm_bindgen::JsValue::from_str(key));
        let result = js_sys::Reflect::apply(&get_item_fn.into(), &storage, &args).ok()?;
        if !result.is_null() && !result.is_undefined() {
            return result.as_string();
        }
    }
    None
}

#[cfg(target_arch = "wasm32")]
fn save_to_local_storage(key: &str, value: &str) -> Option<()> {
    let global = js_sys::global();
    let storage = js_sys::Reflect::get(&global, &wasm_bindgen::JsValue::from_str("localStorage")).ok()?;
    if storage.is_undefined() || storage.is_null() {
        return None;
    }
    let set_item_fn = js_sys::Reflect::get(&storage, &wasm_bindgen::JsValue::from_str("setItem")).ok()?;
    if set_item_fn.is_function() {
        let args = js_sys::Array::of2(&wasm_bindgen::JsValue::from_str(key), &wasm_bindgen::JsValue::from_str(value));
        let _ = js_sys::Reflect::apply(&set_item_fn.into(), &storage, &args).ok()?;
    }
    Some(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{TempDir, client_config::ClientConfig, setup};
    use std::sync::Arc;

    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn test_concurrent_get_value() {
        setup();
        let temp_dir = TempDir::new("apollo_concurrent_get_test");

        let config = ClientConfig {
            app_id: String::from("101010101"),
            cluster: String::from("default"),
            config_server: std::env::var("APOLLO_TEST_SERVER").unwrap_or_else(|_| String::from("http://localhost:8080")),
            secret: None,
            cache_dir: Some(temp_dir.path().to_str().unwrap().to_string()),
            label: None,
            ip: None,
            allow_insecure_https: None,
            #[cfg(not(target_arch = "wasm32"))]
            cache_ttl: None,
            #[cfg(not(target_arch = "wasm32"))]
            refresh_interval: None,
            #[cfg(not(target_arch = "wasm32"))]
            http_client: None,
        };

        let cache = Arc::new(Cache::new(
            config,
            "application",
            reqwest::Client::new(),
        ));

        let mut handles = Vec::new();
        for _ in 0..10 {
            let cache = cache.clone();
            let handle = tokio::spawn(async move { cache.get_value().await });
            handles.push(handle);
        }

        let results = futures::future::join_all(handles).await;

        let first_result = results[0].as_ref().unwrap().as_ref().unwrap();
        for result in &results {
            let result = result.as_ref().unwrap().as_ref().unwrap();
            assert_eq!(result, first_result);
        }
    }

    #[test]
    fn test_sign_with_path() {
        let url = "/configs/100004458/default/application?ip=10.0.0.1";
        let secret = "df23df3f59884980844ff3dada30fa97";
        let signature = sign(1_576_478_257_344, url, secret).unwrap();
        assert_eq!(signature, "EoKyziXvKqzHgwx+ijDJwgVTDgE=");
    }

    #[test]
    fn test_sign_url() {
        setup();
        let url = "http://localhost:8080/configs/100004458/default/application?ip=10.0.0.1";
        let secret = "df23df3f59884980844ff3dada30fa97";
        let signature = sign(1_576_478_257_344, url, secret).unwrap();
        assert_eq!(signature, "EoKyziXvKqzHgwx+ijDJwgVTDgE=");
    }
}