tauri-plugin-cache 0.1.6

Advanced disk caching solution for Tauri applications. Provides compression, TTL management, memory caching, automatic cleanup, and cross-platform support. Enhances data access performance and storage optimization.
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
use base64::{engine::general_purpose::STANDARD, Engine as _};
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tauri::{plugin::PluginApi, AppHandle, Runtime};
use xz2::read::XzDecoder;
use xz2::write::XzEncoder;

use crate::models::*;
use crate::Error;

// Define a type alias for the complex cache value type
type CacheValueEntry = (serde_json::Value, Option<u64>);
type CacheValueMap = HashMap<String, CacheValueEntry>;
type ThreadSafeCacheMap = Arc<Mutex<CacheValueMap>>;

// Store the value and its optional expiry time in a single struct for better organization
#[derive(Clone, Serialize, Deserialize)]
struct CacheEntry {
    value: serde_json::Value,
    expires_at: Option<u64>,
    is_compressed: Option<bool>,
}

// Initialize the cache with a custom configuration
pub fn init_with_config<R: Runtime, C: DeserializeOwned>(
    app: &AppHandle<R>,
    _api: PluginApi<R, C>,
    cache_file_path: PathBuf,
    cleanup_interval: u64,
) -> crate::Result<Cache<R>> {
    let cache = Cache {
        app: app.clone(),
        cache_file_path,
        cleanup_interval,
        file_mutex: Arc::new(Mutex::new(())),
        compression: CompressionConfig::default(),
        value_cache: Arc::new(Mutex::new(HashMap::new())),
    };

    // Set up a background task to clean expired entries periodically
    cache.start_cleanup_task();

    Ok(cache)
}

/// Access to the cache APIs.
#[allow(dead_code)]
pub struct Cache<R: Runtime> {
    app: AppHandle<R>,
    cache_file_path: PathBuf,
    cleanup_interval: u64,
    file_mutex: Arc<Mutex<()>>,
    compression: CompressionConfig,
    value_cache: ThreadSafeCacheMap,
}

impl<R: Runtime> Cache<R> {
    /// Start a background task to periodically clean up expired cache entries
    fn start_cleanup_task(&self) {
        let file_mutex = self.file_mutex.clone();
        let value_cache = self.value_cache.clone();
        let interval = self.cleanup_interval;
        let cache_file_path = self.cache_file_path.clone();

        // Use a background thread to periodically clean up expired items
        std::thread::spawn(move || {
            loop {
                std::thread::sleep(Duration::from_secs(interval));

                // Clean up expired entries
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();

                // Also clean up the in-memory value cache
                {
                    let mut cache = value_cache.lock().unwrap();
                    let expired_keys: Vec<String> = cache
                        .iter()
                        .filter_map(|(key, (_, expires_at))| {
                            if let Some(expires) = expires_at {
                                if *expires < now {
                                    Some(key.clone())
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        })
                        .collect();

                    for key in expired_keys {
                        cache.remove(&key);
                    }
                }

                // Lock the file for exclusive access
                let _guard = file_mutex.lock().unwrap();

                // Read the current cache
                let mut data: HashMap<String, CacheEntry> =
                    match Self::read_from_file(&cache_file_path) {
                        Ok(data) => data,
                        Err(_) => continue, // Skip this cleanup cycle if file cannot be read
                    };

                // Filter out expired entries
                let expired_keys: Vec<String> = data
                    .iter()
                    .filter_map(|(key, entry)| {
                        if let Some(expires_at) = entry.expires_at {
                            if expires_at < now {
                                Some(key.clone())
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    })
                    .collect();

                let mut modified = false;
                for key in expired_keys {
                    data.remove(&key);
                    modified = true;
                }

                // Save to file if cache was modified
                if modified {
                    let _ = Self::write_to_file(&cache_file_path, &data);
                }
            }
        });
    }

    /// Read cache data from file
    fn read_from_file(path: &PathBuf) -> io::Result<HashMap<String, CacheEntry>> {
        if !path.exists() {
            return Ok(HashMap::new());
        }

        let file = fs::File::open(path)?;
        let file_size = file.metadata()?.len();

        // For large files, use a buffered reader for better performance
        let mut reader = BufReader::with_capacity(
            std::cmp::min(file_size as usize, 128 * 1024), // 128KB buffer or file size
            file,
        );

        let mut contents = String::with_capacity(file_size as usize);
        reader.read_to_string(&mut contents)?;

        if contents.is_empty() {
            return Ok(HashMap::new());
        }

        match serde_json::from_str(&contents) {
            Ok(data) => Ok(data),
            Err(_) => Ok(HashMap::new()),
        }
    }

    /// Write cache data to file
    fn write_to_file(path: &PathBuf, data: &HashMap<String, CacheEntry>) -> io::Result<()> {
        let file = fs::File::create(path)?;

        // Use a buffered writer for better performance
        let mut writer = BufWriter::with_capacity(128 * 1024, file); // 128KB buffer

        serde_json::to_writer(&mut writer, data)?;
        writer.flush()?;
        Ok(())
    }

    /// Compress a JSON value using a specific configuration
    fn compress_value_with_config(
        &self,
        value: &serde_json::Value,
        config: &CompressionConfig,
    ) -> crate::Result<Vec<u8>> {
        // First serialize to JSON string to determine size
        let json_string = serde_json::to_string(value)
            .map_err(|e| Error::Cache(format!("Failed to serialize value: {}", e)))?;

        // Check if value is below the compression threshold
        if !config.enabled || json_string.len() < config.threshold {
            // Return a special marker that indicates this value wasn't compressed
            let mut result = Vec::with_capacity(json_string.len() + 2);
            result.push(0); // Marker for uncompressed data
            result.push(0); // Method marker (unused for uncompressed)
            result.extend_from_slice(json_string.as_bytes());
            return Ok(result);
        }

        // For large data, use chunked processing to avoid memory spikes
        let bytes = json_string.as_bytes();
        const CHUNK_SIZE: usize = 64 * 1024; // 64KB chunks

        match config.method {
            CompressionMethod::Zlib => {
                // Apply Zlib compression with the configured level
                let zlib_level = Compression::new(config.level);
                let mut encoder = ZlibEncoder::new(Vec::new(), zlib_level);

                if bytes.len() > CHUNK_SIZE {
                    // Process in chunks for large data
                    for chunk in bytes.chunks(CHUNK_SIZE) {
                        encoder.write_all(chunk).map_err(|e| {
                            Error::Cache(format!("Failed to compress value chunk: {}", e))
                        })?;
                    }
                } else {
                    // Small data can be written at once
                    encoder
                        .write_all(bytes)
                        .map_err(|e| Error::Cache(format!("Failed to compress value: {}", e)))?;
                }

                // Add marker for compressed data
                let mut compressed = encoder
                    .finish()
                    .map_err(|e| Error::Cache(format!("Failed to finish compression: {}", e)))?;

                // Prepend markers (1 = compressed, 1 = Zlib)
                let mut result = Vec::with_capacity(compressed.len() + 2);
                result.push(1); // Compressed marker
                result.push(1); // Method marker: 1 = Zlib
                result.append(&mut compressed);

                Ok(result)
            }
            CompressionMethod::Lzma2 => {
                // Apply LZMA2 compression with the configured level
                let mut encoder = XzEncoder::new(Vec::new(), config.level);

                if bytes.len() > CHUNK_SIZE {
                    // Process in chunks for large data
                    for chunk in bytes.chunks(CHUNK_SIZE) {
                        encoder.write_all(chunk).map_err(|e| {
                            Error::Cache(format!("Failed to compress value chunk: {}", e))
                        })?;
                    }
                } else {
                    // Small data can be written at once
                    encoder
                        .write_all(bytes)
                        .map_err(|e| Error::Cache(format!("Failed to compress value: {}", e)))?;
                }

                // Add marker for compressed data
                let mut compressed = encoder
                    .finish()
                    .map_err(|e| Error::Cache(format!("Failed to finish compression: {}", e)))?;

                // Prepend markers (1 = compressed, 2 = LZMA2)
                let mut result = Vec::with_capacity(compressed.len() + 2);
                result.push(1); // Compressed marker
                result.push(2); // Method marker: 2 = LZMA2
                result.append(&mut compressed);

                Ok(result)
            }
        }
    }

    /// Compress a JSON value using the default compression configuration
    #[allow(dead_code)]
    fn compress_value(&self, value: &serde_json::Value) -> crate::Result<Vec<u8>> {
        self.compress_value_with_config(value, &self.compression)
    }

    /// Decompress a compressed value back to JSON
    fn decompress_value(&self, data: &[u8]) -> crate::Result<serde_json::Value> {
        if data.is_empty() {
            return Err(Error::Cache(
                "Empty data provided for decompression".to_string(),
            ));
        }

        // First byte indicates if data is compressed
        let is_compressed = data[0] == 1;

        if !is_compressed {
            // Data is not compressed - parse the JSON directly
            let json_data = &data[2..]; // Skip the marker bytes

            let string_data = std::str::from_utf8(json_data)
                .map_err(|e| Error::Cache(format!("Failed to decode uncompressed data: {}", e)))?;

            return serde_json::from_str(string_data)
                .map_err(|e| Error::Cache(format!("Failed to deserialize value: {}", e)));
        }

        // Second byte indicates compression method
        let method_marker = data[1];
        let compressed_data = &data[2..]; // Skip the marker bytes

        match method_marker {
            1 => {
                // Zlib decompression
                let mut decoder = ZlibDecoder::new(compressed_data);
                let mut json_string = String::new();

                decoder
                    .read_to_string(&mut json_string)
                    .map_err(|e| Error::Cache(format!("Failed to decompress Zlib data: {}", e)))?;

                serde_json::from_str(&json_string)
                    .map_err(|e| Error::Cache(format!("Failed to parse decompressed JSON: {}", e)))
            }
            2 => {
                // LZMA2 decompression
                let mut decoder = XzDecoder::new(compressed_data);
                let mut json_string = String::new();

                decoder
                    .read_to_string(&mut json_string)
                    .map_err(|e| Error::Cache(format!("Failed to decompress LZMA2 data: {}", e)))?;

                serde_json::from_str(&json_string)
                    .map_err(|e| Error::Cache(format!("Failed to parse decompressed JSON: {}", e)))
            }
            _ => Err(Error::Cache(format!(
                "Unknown compression method marker: {}",
                method_marker
            ))),
        }
    }

    /// Sets a value in the cache with an optional TTL
    pub fn set<T: Serialize + std::fmt::Debug>(
        &self,
        key: String,
        value: T,
        options: Option<SetItemOptions>,
    ) -> crate::Result<EmptyResponse> {
        // Serialize the value to JSON first (do this outside the lock)
        let value_json = serde_json::to_value(value)
            .map_err(|e| Error::Cache(format!("Failed to serialize value: {}", e)))?;

        // Calculate expiration time if TTL is set
        let expires_at = options.as_ref().and_then(|opt| {
            opt.ttl.map(|ttl| {
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    + ttl
            })
        });

        // Update the in-memory cache first
        {
            let mut cache = self.value_cache.lock().unwrap();
            cache.insert(key.clone(), (value_json.clone(), expires_at));
        }

        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Get current cache data
        let mut data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        // Check if compression is requested
        let should_compress = options
            .as_ref()
            .and_then(|opt| opt.compress)
            .unwrap_or(self.compression.enabled);

        // Create a temporary compression config based on options
        let temp_compression = CompressionConfig {
            enabled: should_compress,
            level: self.compression.level,
            threshold: self.compression.threshold,
            method: options
                .as_ref()
                .and_then(|opt| opt.compression_method.clone())
                .unwrap_or(self.compression.method.clone()),
        };

        // Process the value based on compression settings
        let entry = if should_compress {
            // Compress the value using the temporary compression config
            let processed_data = self.compress_value_with_config(&value_json, &temp_compression)?;
            // Store the processed data as a base64 string
            let encoded_str = STANDARD.encode(&processed_data);
            CacheEntry {
                value: serde_json::Value::String(encoded_str),
                expires_at,
                is_compressed: Some(true),
            }
        } else {
            CacheEntry {
                value: value_json,
                expires_at,
                is_compressed: Some(false),
            }
        };

        // Update the cache
        data.insert(key, entry);

        // Save the updated cache to file
        Self::write_to_file(&self.cache_file_path, &data)
            .map_err(|e| Error::Cache(format!("Failed to write cache file: {}", e)))?;

        Ok(EmptyResponse::default())
    }

    /// Gets a value from the cache
    pub fn get(&self, key: &str) -> crate::Result<Option<serde_json::Value>> {
        // First check the in-memory cache
        {
            let cache = self.value_cache.lock().unwrap();
            if let Some((value, expires_at)) = cache.get(key) {
                // Check if expired
                if let Some(expires) = expires_at {
                    let now = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap()
                        .as_secs();

                    if *expires < now {
                        // Item has expired, remove from in-memory cache
                        drop(cache); // Release the lock before modifying
                        let mut cache = self.value_cache.lock().unwrap();
                        cache.remove(key);
                    } else {
                        // Not expired, return the cached value
                        return Ok(Some(value.clone()));
                    }
                } else {
                    // No expiration, return the cached value
                    return Ok(Some(value.clone()));
                }
            }
        }

        // If not in memory cache, check the file
        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Get current cache data
        let data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        if let Some(entry) = data.get(key) {
            // Check if the item has expired
            if let Some(expires_at) = entry.expires_at {
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();

                if expires_at < now {
                    // Item has expired
                    return Ok(None);
                }
            }

            // Check if the value is compressed
            if entry.is_compressed.unwrap_or(false) {
                // Value is compressed - need to decompress
                if let serde_json::Value::String(compressed_str) = &entry.value {
                    // Decode base64
                    let compressed_data = STANDARD
                        .decode(compressed_str)
                        .map_err(|e| Error::Cache(format!("Failed to decode base64: {}", e)))?;

                    // Decompress
                    let value = self.decompress_value(&compressed_data)?;

                    // Cache the decompressed value in memory for future use
                    {
                        let mut cache = self.value_cache.lock().unwrap();
                        cache.insert(key.to_string(), (value.clone(), entry.expires_at));
                    }

                    return Ok(Some(value));
                } else {
                    return Err(Error::Cache(
                        "Compressed value is not in expected format".to_string(),
                    ));
                }
            }

            // Store uncompressed value in memory cache for future use
            {
                let mut cache = self.value_cache.lock().unwrap();
                cache.insert(key.to_string(), (entry.value.clone(), entry.expires_at));
            }

            // Return the value as is (not compressed)
            Ok(Some(entry.value.clone()))
        } else {
            Ok(None)
        }
    }

    /// Checks if a key exists in the cache and hasn't expired
    pub fn has(&self, key: &str) -> crate::Result<BooleanResponse> {
        // First check the in-memory cache
        {
            let cache = self.value_cache.lock().unwrap();
            if let Some((_, expires_at)) = cache.get(key) {
                // Check if expired
                if let Some(expires) = expires_at {
                    let now = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap()
                        .as_secs();

                    if *expires < now {
                        // Item has expired
                        drop(cache); // Release the lock before modifying
                        let mut cache = self.value_cache.lock().unwrap();
                        cache.remove(key);
                    } else {
                        // Not expired
                        return Ok(BooleanResponse { value: true });
                    }
                } else {
                    // No expiration
                    return Ok(BooleanResponse { value: true });
                }
            }
        }

        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Get current time
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| Error::Cache(e.to_string()))?
            .as_secs();

        // Load data from file
        let data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        if let Some(entry) = data.get(key) {
            // Check if the entry has expired
            if let Some(expires_at) = entry.expires_at {
                if expires_at < now {
                    return Ok(BooleanResponse { value: false });
                }
            }

            // Add to memory cache
            {
                let mut cache = self.value_cache.lock().unwrap();
                cache.insert(key.to_string(), (entry.value.clone(), entry.expires_at));
            }

            Ok(BooleanResponse { value: true })
        } else {
            Ok(BooleanResponse { value: false })
        }
    }

    /// Removes a value from the cache
    pub fn remove(&self, key: &str) -> crate::Result<EmptyResponse> {
        // Remove from in-memory cache first
        {
            let mut cache = self.value_cache.lock().unwrap();
            cache.remove(key);
        }

        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Load data from file
        let mut data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        // Remove item if exists
        if data.remove(key).is_some() {
            // Save changes to file
            Self::write_to_file(&self.cache_file_path, &data)
                .map_err(|e| Error::Cache(format!("Failed to write cache file: {}", e)))?;
        }

        Ok(EmptyResponse {})
    }

    /// Clears the entire cache
    pub fn clear(&self) -> crate::Result<EmptyResponse> {
        // Clear the in-memory cache
        {
            let mut cache = self.value_cache.lock().unwrap();
            cache.clear();
        }

        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Just write an empty cache
        Self::write_to_file(&self.cache_file_path, &HashMap::new())
            .map_err(|e| Error::Cache(format!("Failed to write cache file: {}", e)))?;

        Ok(EmptyResponse {})
    }

    /// Get the total number of items in the cache
    pub fn size(&self) -> crate::Result<usize> {
        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Load data from file
        let data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        Ok(data.len())
    }

    /// Get the number of non-expired items in the cache
    pub fn active_size(&self) -> crate::Result<usize> {
        // Acquire lock for file operations
        let _guard = self.file_mutex.lock().unwrap();

        // Load data from file
        let data = Self::read_from_file(&self.cache_file_path)
            .map_err(|e| Error::Cache(format!("Failed to read cache file: {}", e)))?;

        // Get current time
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| Error::Cache(e.to_string()))?
            .as_secs();

        // Count only non-expired items
        let active_count = data
            .iter()
            .filter(|(_, entry)| {
                if let Some(expires_at) = entry.expires_at {
                    expires_at > now
                } else {
                    true // Items without expiration are always active
                }
            })
            .count();

        Ok(active_count)
    }

    /// Get the path to the cache file
    pub fn get_cache_file_path(&self) -> PathBuf {
        self.cache_file_path.clone()
    }

    /// Configure the cache with compression settings
    pub fn init_with_config(
        &mut self,
        default_compression: bool,
        compression_level: Option<u32>,
        threshold: Option<usize>,
        compression_method: Option<CompressionMethod>,
    ) {
        self.compression = CompressionConfig {
            enabled: default_compression,
            level: compression_level.unwrap_or(6),
            threshold: threshold.unwrap_or(COMPRESSION_THRESHOLD),
            method: compression_method.unwrap_or(CompressionMethod::Zlib),
        };
    }
}