fcache 0.2.0

File caching library with lazy creation, automatic refresh, and callback-based initialization
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! This crate provides a simple file caching mechanism with a straightforward interface for creating, retrieving, and managing cached files efficiently.
//!
//! # Features
//!
//! - **Temporary and Persistent Caches**: Create caches in temporary directories or specified paths.
//! - **Lazy File Creation**: Files are created only when accessed, reducing unnecessary disk operations.
//! - **Automatic Refresh**: Files can be automatically refreshed based on a specified interval.
//! - **Callback Functions**: Custom logic can be executed when files are created or accessed.
//!
//! # Setup
//!
//! To use this crate, add the following entry to your `Cargo.toml` file in the `dependencies` section:
//!
//! ```toml
//! [dependencies]
//! fcache = "0.2.0"
//! ```
//!
//! Alternatively, you can use the [`cargo add`](https://doc.rust-lang.org/cargo/commands/cargo-add.html) subcommand:
//!
//! ```sh
//! cargo add fcache
//! ```
//!
//! # Usage
//!
//! Use the [`new`] function to create a new cache instance in a temporary directory.
//!
//! ```rust
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance
//! let cache = fcache::new()?;
//!
//! // Get or create a cached file
//! let cache_file = cache.get("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     Ok(())
//! })?;
//! // File is created and can be used...
//!
//! // Open the cached file
//! let mut file = cache_file.open()?;
//!
//! // Read the content of the file
//! let mut content = String::new();
//! file.read_to_string(&mut content)?;
//! // Assert the content matches what was written
//! assert_eq!(content, "Hello, world!");
//! # Ok(())
//! # }
//! ```
//!
//! Use the [`with_dir`] function to create a cache in a specified directory.
//!
//! ```rust,no_run
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance in a specified directory
//! let cache = fcache::with_dir("/path/to/cache")?;
//!
//! // Get or create a cached file
//! let cache_file = cache.get("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     Ok(())
//! })?;
//! // File is created and can be used...
//!
//! // Open the cached file
//! let mut file = cache_file.open()?;
//!
//! // Read the content of the file
//! let mut content = String::new();
//! file.read_to_string(&mut content)?;
//! // Assert the content matches what was written
//! assert_eq!(content, "Hello, world!");
//! # Ok(())
//! # }
//! ```
//!
//! ## Lazy files
//!
//! Lazy files are a special type of file that is not created until it is accessed. This can be useful for reducing unnecessary disk operations, especially when the file may not be needed immediately.
//!
//! See [`Cache::get_lazy`], and [`CacheLazyFile`] for more details on how to use lazy files.
//!
//! ```rust
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance in a specified directory
//! let cache = fcache::new()?;
//!
//! // Get or create a lazy cached file
//! let cache_file = cache.get_lazy("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     Ok(())
//! })?;
//! // File isn't created until opened...
//!
//! // Open the cached file
//! let mut file = cache_file.open()?; // File is created here
//!
//! // Read the content of the file
//! let mut content = String::new();
//! file.read_to_string(&mut content)?;
//! // Assert the content matches what was written
//! assert_eq!(content, "Hello, world!");
//! # Ok(())
//! # }
//! ```
//!
//! ## Force Refresh
//!
//! Files in the cache can be forcefully refreshed to regenerate their content, even if they are still within their refresh interval. This is useful when you need to ensure the file content is updated immediately.
//!
//! See [`CacheFile::force_refresh`], and [`CacheLazyFile::force_refresh`] for more details.
//!
//! ```rust
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance
//! let cache = fcache::new()?;
//!
//! // Create a file with initial content
//! let cache_file = cache.get("data.txt", |mut file| {
//!     file.write_all(b"Initial content")?;
//!     Ok(())
//! })?;
//!
//! // Force refresh the file with new content
//! let cache_file = cache.get("data.txt", |mut file| {
//!     file.write_all(b"Updated content")?;
//!     Ok(())
//! })?;
//! cache_file.force_refresh()?;
//!
//! // The file now contains the updated content
//! let mut file = cache_file.open()?;
//! let mut content = String::new();
//! file.read_to_string(&mut content)?;
//! assert_eq!(content, "Updated content");
//! # Ok(())
//! # }
//! ```
//!
//! ## Locking and unlocking
//!
//! Files can be locked and unlocked to prevent refreshing or modifying them while they are in use. This is useful for ensuring that the file remains consistent during operations.
//!
//! See [`CacheFile::lock`]/[`CacheFile::unlock`], and [`CacheLazyFile::lock`]/[`CacheLazyFile::unlock`] for more details.
//!
//! This is not a thread-safe operation.
//!
//! ```rust
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance in a specified directory
//! let cache = fcache::new()?;
//!
//! // Get or create a cached file
//! let mut cache_file = cache.get("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     Ok(())
//! })?;
//! // File is created and can be used...
//!
//! // Lock the file to prevent refreshing
//! cache_file.lock()?; // Lock the file to prevent refreshing
//!
//! // Perform operations on the file
//!
//! // Unlock the file to allow refreshing
//! cache_file.unlock()?; // Unlock the file to allow refreshing
//!
//! // ...
//! # Ok(())
//! # }
//! ```
//!
//! ## Thread Safety
//!
//! The cache system is designed to be thread-safe for most operations. Cache instances can be safely shared across multiple threads using [`Arc`](std::sync::Arc) or similar synchronization primitives.
//!
//! ```rust
//! use std::sync::Arc;
//! use std::thread;
//!
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a cache instance that can be shared across threads
//! let cache = Arc::new(fcache::new()?);
//!
//! // Spawn multiple threads that use the same cache
//! let handles: Vec<_> = (0..4)
//!     .map(|i| {
//!         let cache = Arc::clone(&cache);
//!         thread::spawn(move || {
//!             // Each thread can safely create files in the cache
//!             let cache_file = cache.get(&format!("thread_{}.txt", i), move |mut file| {
//!                 file.write_all(format!("Content from thread {}", i).as_bytes())?;
//!                 Ok(())
//!             })?;
//!
//!             // And read from them
//!             let mut content = String::new();
//!             cache_file.open()?.read_to_string(&mut content)?;
//!             println!("Thread {}: {}", i, content);
//!
//!             Ok::<(), fcache::Error>(())
//!         })
//!     })
//!     .collect();
//!
//! // Wait for all threads to complete
//! for handle in handles {
//!     handle
//!         .join()
//!         .expect("Thread should complete successfully")?;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Thread Safety Guarantees
//!
//! - **Cache instances**: Safe to share across threads using [`Arc`](std::sync::Arc).
//! - **File creation**: Multiple threads can safely create different files simultaneously.
//! - **File operations**: Reading and writing operations are thread-safe at the filesystem level.
//!
//! ### Thread Safety Limitations
//!
//! - **File locking**: The built-in locking mechanism is **not** thread-safe and should not be relied upon for inter-thread synchronization (see [Locking and unlocking](#locking-and-unlocking) for more details).
//! - **Concurrent access**: Users must implement their own synchronization using external mechanisms like [`Mutex`](std::sync::Mutex) or [`RwLock`](std::sync::RwLock) when multiple threads access the same file path, as the cache does not provide automatic protection against race conditions.
//!
//! # Tips and tricks
//!
//! ## Always refresh
//!
//! Use [`Duration::ZERO`] to ensure the cache is always refreshed.
//!
//! ```rust
//! use std::time::Duration;
//!
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance
//! let cache = fcache::new()?.with_refresh_interval(Duration::ZERO);
//!
//! // Get or create a cached file
//! let mut cache_file = cache.get("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     // Inform about the refresh
//!     println!("Refreshing file");
//!     Ok(())
//! })?;
//!
//! // File refreshes on every access
//! let file = cache_file.open()?;
//! let file = cache_file.open()?;
//! let file = cache_file.open()?;
//! // ...
//! # Ok(())
//! # }
//! ```
//!
//! ## Never refresh
//!
//! Use [`Duration::MAX`] to disable automatic refresh. Use `force_refresh` for manual control.
//!
//! ```rust
//! use std::time::Duration;
//!
//! use fcache::prelude::*;
//!
//! # fn wrapper() -> fcache::Result<()> {
//! // Create a new cache instance
//! let cache = fcache::new()?.with_refresh_interval(Duration::MAX);
//!
//! // Get or create a cached file
//! let mut cache_file = cache.get("hello.txt", |mut file| {
//!     // Write data to the file
//!     file.write_all(b"Hello, world!")?;
//!     // Inform about the refresh
//!     println!("Refreshing file");
//!     Ok(())
//! })?;
//!
//! // File never refreshes automatically
//! let file = cache_file.open()?;
//! let file = cache_file.open()?;
//! let file = cache_file.open()?;
//! // ...
//!
//! // Manual refresh when needed
//! cache_file.force_refresh()?;
//! # Ok(())
//! # }
//! ```
//!
//! # License
//!
//! This crate is licensed under the MIT License.

#![forbid(unsafe_code)]

mod callback;
mod file;
pub mod prelude;
mod result;

use std::fmt::Debug;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

use tempfile::TempDir;

pub use crate::callback::CallbackFn;
pub use crate::file::{CacheFile, CacheLazyFile};
use crate::result::Ok;
pub use crate::result::{Error, Result};

/// Default refresh interval for the cache.
pub const DEFAULT_REFRESH_INTERVAL: Duration = Duration::from_secs(5);

/// Creates a new cache instance within a temporary directory.
///
/// For more information on how to use the cache, refer to the [`Cache`] documentation.
///
/// # Example
///
/// ```rust
/// # fn wrapper() -> fcache::Result<()> {
/// // Create a new cache instance
/// let cache = fcache::new()?;
///
/// // Use the cache...
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// This function will return an error if the temporary directory cannot be created or if there are issues with the underlying filesystem operations.
pub fn new() -> Result<Cache> {
    Cache::new()
}

/// Creates a new cache instance within a temporary directory with a specified prefix.
///
/// For more information on how to use the cache, refer to the [`Cache`] documentation.
///
/// # Example
///
/// ```rust
/// # fn wrapper() -> fcache::Result<()> {
/// // Create a new cache instance with a custom prefix
/// let cache = fcache::with_prefix("my_cache")?;
/// assert!(cache.path().to_string_lossy().starts_with("/tmp/my_cache"));
///
/// // Use the cache...
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// This function will return an error if the temporary directory cannot be created or there are issues with the underlying filesystem operations.
pub fn with_prefix(prefix: &str) -> Result<Cache> {
    Cache::with_prefix(prefix)
}

/// Creates a new cache instance within a specified directory.
///
/// For more information on how to use the cache, refer to the [`Cache`] documentation.
///
/// # Example
///
/// ```rust,no_run
/// # fn wrapper() -> fcache::Result<()> {
/// // Create a new cache instance
/// let cache = fcache::with_dir("/path/to/cache")?;
///
/// // Use the cache...
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// This function will return an error if the specified path exists but is not a directory, the specified path does not exist and directory creation fails, or there are other underlying filesystem operation issues.
pub fn with_dir(dir: impl AsRef<Path>) -> Result<Cache> {
    Cache::with_dir(dir)
}

/// Represents a cache instance.
///
/// # Example
///
/// ```rust
/// use fcache::prelude::*;
///
/// # fn wrapper() -> fcache::Result<()> {
/// // Create a new cache instance
/// let cache = Cache::new()?;
///
/// // Create a new file in the cache
/// let cache_file = cache.get("example.txt", |mut file| {
///     file.write_all(b"Hello, Cache!")?;
///     Ok(())
/// })?;
///
/// // Open the cached file
/// let mut file = cache_file.open()?;
/// // Read the content of the file
/// let mut content = String::new();
/// file.read_to_string(&mut content)?;
///
/// // Assert the content matches what was written
/// assert_eq!(content, "Hello, Cache!");
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Cache(InnerCache);

impl Cache {
    /// Creates a new cache instance within a temporary directory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?;
    ///
    /// // Use the cache...
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if the temporary directory cannot be created or if there are issues with the underlying filesystem operations.
    pub fn new() -> Result<Self> {
        InnerCache::temp().map(Self)
    }

    /// Creates a new cache instance within a temporary directory with a specified prefix.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance with a custom prefix
    /// let cache = Cache::with_prefix("my_cache")?;
    /// assert!(cache.path().to_string_lossy().starts_with("/tmp/my_cache"));
    ///
    /// // Use the cache...
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if the temporary directory cannot be created or there are issues with the underlying filesystem operations.
    pub fn with_prefix(prefix: &str) -> Result<Self> {
        InnerCache::temp_with_prefix(prefix).map(Self)
    }

    /// Creates a new cache instance within a specified directory.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::with_dir("/path/to/cache")?;
    ///
    /// // Use the cache...
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if the specified path exists but is not a directory, the specified path does not exist and directory creation fails, or there are other underlying filesystem operation issues.
    pub fn with_dir(dir: impl AsRef<Path>) -> Result<Self> {
        InnerCache::dir(dir).map(Self)
    }

    /// Sets the refresh interval for the cache.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance with a custom refresh interval
    /// let cache = Cache::new()?.with_refresh_interval(Duration::from_secs(10));
    ///
    /// // Use the cache...
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_refresh_interval(self, refresh_interval: Duration) -> Self {
        let Self(inner) = self;
        inner.with_refresh_interval(refresh_interval).into()
    }

    /// Sets the refresh interval to the default value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?.with_refresh_interval(Duration::from_secs(60));
    ///
    /// // Use the cache...
    ///
    /// // Reset to default refresh interval
    /// let cache = cache.with_default_refresh_interval();
    ///
    /// // Use the cache...
    /// # Ok(())
    /// # }
    #[must_use]
    pub fn with_default_refresh_interval(self) -> Self {
        let Self(inner) = self;
        inner.with_default_refresh_interval().into()
    }

    /// Returns the path of the cache directory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?;
    ///
    /// // Print the cache path
    /// println!("Cache path: {}", cache.path().display());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn path(&self) -> &Path {
        let Self(inner) = self;
        inner.path()
    }

    /// Returns the refresh interval of the cache.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?;
    ///
    /// // Print the refresh interval
    /// println!("Refresh interval: {:?}", cache.refresh_interval());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn refresh_interval(&self) -> Duration {
        let Self(inner) = self;
        inner.refresh_interval()
    }

    /// Creates a file in the cache using a callback for initialization.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?;
    ///
    /// // Get or create a cached file
    /// let cache_file = cache.get("example.txt", |mut file| {
    ///     // Write data to the file
    ///     file.write_all(b"Hello, Cache!")?;
    ///     Ok(())
    /// })?;
    /// // File is created and can be used...
    ///
    /// // Open the cached file
    /// let mut file = cache_file.open()?;
    /// // Read data from the file
    /// let mut contents = String::new();
    /// file.read_to_string(&mut contents)?;
    /// println!("Cached file contents: {}", contents);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if the file already exists, file creation fails due to permissions or disk space, the callback function returns an error, path traversal is detected outside the cache directory, or parent directory creation fails.
    pub fn get<'a>(&'a self, path: impl AsRef<Path>, callback: impl CallbackFn + 'static) -> Result<CacheFile<'a>> {
        let Self(inner) = self;
        inner.get(path, callback)
    }

    /// Creates a file in the cache that is lazily created when accessed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fcache::prelude::*;
    ///
    /// # fn wrapper() -> fcache::Result<()> {
    /// // Create a new cache instance
    /// let cache = Cache::new()?;
    ///
    /// // Get or create a lazy cached file
    /// let cache_file = cache.get_lazy("lazy_file.txt", |mut file| {
    ///     // Write data to the file
    ///     file.write_all(b"Hello, Lazy Cache!")?;
    ///     Ok(())
    /// })?;
    ///
    /// // File isn't created until opened...
    /// assert!(!cache_file.path().exists());
    ///
    /// // Open the lazy cached file
    /// let mut file = cache_file.open()?;
    /// // Read data from the file
    /// let mut contents = String::new();
    /// file.read_to_string(&mut contents)?;
    /// println!("Lazy cached file contents: {}", contents);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if the file already exists, path traversal is detected outside the cache directory, parent directory creation fails, or there are issues with path resolution or filesystem operations.
    pub fn get_lazy<'a>(
        &'a self,
        path: impl AsRef<Path>,
        callback: impl CallbackFn + 'static,
    ) -> Result<CacheLazyFile<'a>> {
        let Self(inner) = self;
        inner.get_lazy(path, callback)
    }
}

impl From<InnerCache> for Cache {
    fn from(inner: InnerCache) -> Self {
        Self(inner)
    }
}

/// Represents the inner cache implementation, either directory-based or temporary.
#[derive(Debug)]
enum InnerCache {
    /// Directory cache implementation
    Dir(InnerDirCache),
    /// Temporary cache implementation
    Temp(InnerTempCache),
}

impl InnerCache {
    /// Creates a new cache instance within a specified directory.
    fn dir(dir: impl AsRef<Path>) -> Result<Self> {
        InnerDirCache::new(dir).map(Self::Dir)
    }

    /// Creates a new cache instance within a temporary directory.
    fn temp() -> Result<Self> {
        InnerTempCache::new().map(Self::Temp)
    }

    /// Creates a new cache instance within a temporary directory with a specified prefix.
    fn temp_with_prefix(prefix: &str) -> Result<Self> {
        InnerTempCache::with_prefix(prefix).map(Self::Temp)
    }

    /// Sets the refresh interval for the cache.
    fn with_refresh_interval(self, refresh_interval: Duration) -> Self {
        match self {
            Self::Dir(dir_cache) => dir_cache.with_refresh_interval(refresh_interval).into(),
            Self::Temp(temp_cache) => temp_cache.with_refresh_interval(refresh_interval).into(),
        }
    }

    /// Sets the refresh interval to the default value.
    fn with_default_refresh_interval(self) -> Self {
        match self {
            Self::Dir(dir_cache) => dir_cache.with_default_refresh_interval().into(),
            Self::Temp(temp_cache) => temp_cache.with_default_refresh_interval().into(),
        }
    }

    /// Returns the path of the cache directory.
    fn path(&self) -> &Path {
        match self {
            Self::Dir(dir_cache) => dir_cache.path(),
            Self::Temp(temp_cache) => temp_cache.path(),
        }
    }

    /// Returns the refresh interval of the cache.
    fn refresh_interval(&self) -> Duration {
        match self {
            Self::Dir(dir_cache) => dir_cache.refresh_interval(),
            Self::Temp(temp_cache) => temp_cache.refresh_interval(),
        }
    }

    /// Creates a file in the cache using a callback for initialization.
    fn get<'a>(&'a self, path: impl AsRef<Path>, callback: impl CallbackFn + 'static) -> Result<CacheFile<'a>> {
        match self {
            Self::Dir(dir_cache) => dir_cache.get(path, callback),
            Self::Temp(temp_cache) => temp_cache.get(path, callback),
        }
    }

    /// Creates a file in the cache that is lazily created when accessed.
    fn get_lazy<'a>(
        &'a self,
        path: impl AsRef<Path>,
        callback: impl CallbackFn + 'static,
    ) -> Result<CacheLazyFile<'a>> {
        match self {
            Self::Dir(dir_cache) => dir_cache.get_lazy(path, callback),
            Self::Temp(temp_cache) => temp_cache.get_lazy(path, callback),
        }
    }
}

impl From<InnerDirCache> for InnerCache {
    fn from(dir_cache: InnerDirCache) -> Self {
        Self::Dir(dir_cache)
    }
}

impl From<InnerTempCache> for InnerCache {
    fn from(temp_cache: InnerTempCache) -> Self {
        Self::Temp(temp_cache)
    }
}

/// Inner cache implementation for a specified directory.
#[derive(Debug)]
struct InnerDirCache {
    /// Directory where the cache is stored
    root: PathBuf,
    /// Refresh interval for the cache
    refresh_interval: Duration,
}

impl InnerDirCache {
    /// Creates a new cache instance within a specified directory.
    fn new(dir: impl AsRef<Path>) -> Result<Self> {
        let dir = dir.as_ref().to_path_buf();

        if dir.exists() && !dir.is_dir() {
            return Err(Error::NotADirectory { path: dir });
        } else if !dir.exists() {
            fs::create_dir_all(&dir)?;
        }

        // Canonicalize after ensuring the directory exists
        let root = dir.canonicalize()?;
        let refresh_interval = DEFAULT_REFRESH_INTERVAL;
        let inner_dir_cache = Self { root, refresh_interval };
        Ok(inner_dir_cache)
    }

    /// Sets the refresh interval for the cache.
    fn with_refresh_interval(self, refresh_interval: Duration) -> Self {
        let Self { root, .. } = self;
        Self { root, refresh_interval }
    }

    /// Sets the refresh interval to the default value.
    fn with_default_refresh_interval(self) -> Self {
        self.with_refresh_interval(DEFAULT_REFRESH_INTERVAL)
    }

    /// Returns the path of the cache directory.
    fn path(&self) -> &Path {
        let Self { root, .. } = self;
        root
    }

    /// Returns the refresh interval of the cache.
    fn refresh_interval(&self) -> Duration {
        let Self { refresh_interval, .. } = self;
        *refresh_interval
    }

    /// Creates a file in the cache using a callback for initialization.
    fn get<'a>(&'a self, path: impl AsRef<Path>, callback: impl CallbackFn + 'static) -> Result<CacheFile<'a>> {
        self.get_lazy(path, callback)?.init()
    }

    /// Creates a file in the cache that is lazily created when accessed.
    fn get_lazy<'a>(
        &'a self,
        path: impl AsRef<Path>,
        callback: impl CallbackFn + 'static,
    ) -> Result<CacheLazyFile<'a>> {
        let Self { root, refresh_interval } = self;
        let path = path.as_ref();

        // Ensure the path does not end with a slash
        if path.to_str().is_some_and(|path| path.ends_with('/')) {
            let path = path.to_path_buf();
            let error = Error::InvalidPath { path };
            return Err(error);
        }

        // Ensure the absolute path is within the cache directory to prevent path traversal attacks
        let mut components = path.components();
        let file_name = if let Some(component) = components.next_back()
            && let Component::Normal(file_name) = component
            && file_name.to_str().is_some_and(|file_name| file_name.trim() != "")
        {
            file_name
        } else {
            let path = path.to_path_buf();
            let error = Error::InvalidPath { path };
            return Err(error);
        };
        let mut path = root.clone();
        for component in components {
            path.push(component);
            if !path.exists() {
                fs::create_dir(&path)?;
            }
            let canonicalized_path = path.canonicalize()?;
            if !canonicalized_path.starts_with(root) {
                let cache_dir = root.clone();
                let error = Error::PathTraversal { path, cache_dir };
                return Err(error);
            }
        }

        let path = path.join(file_name);
        CacheLazyFile::new(path, callback, *refresh_interval, root, refresh_interval)
    }
}

/// Inner cache implementation for a temporary directory.
#[derive(Debug)]
struct InnerTempCache {
    /// Temporary directory for the cache
    temp_dir: TempDir, // Keep the temporary directory alive for the lifetime of the cache
    /// Directory cache implementation
    dir_cache: InnerDirCache,
}

impl InnerTempCache {
    const DEFAULT_PREFIX: &str = "fcache";

    /// Creates a new cache instance within a temporary directory.
    fn new() -> Result<Self> {
        Self::with_prefix(Self::DEFAULT_PREFIX)
    }

    /// Creates a new cache instance within a temporary directory with a specified prefix.
    fn with_prefix(prefix: &str) -> Result<Self> {
        let temp_dir = tempfile::Builder::new().prefix(prefix).tempdir()?;
        InnerDirCache::new(temp_dir.path()).map(|dir_cache| Self { temp_dir, dir_cache })
    }

    /// Sets the refresh interval for the cache.
    fn with_refresh_interval(self, refresh_interval: Duration) -> Self {
        let Self { temp_dir, dir_cache } = self;
        let dir_cache = dir_cache.with_refresh_interval(refresh_interval);
        Self { temp_dir, dir_cache }
    }

    /// Sets the refresh interval to the default value.
    fn with_default_refresh_interval(self) -> Self {
        self.with_refresh_interval(DEFAULT_REFRESH_INTERVAL)
    }

    /// Returns the path of the cache directory.
    fn path(&self) -> &Path {
        let Self { dir_cache, .. } = self;
        dir_cache.path()
    }

    /// Returns the refresh interval of the cache.
    fn refresh_interval(&self) -> Duration {
        let Self { dir_cache, .. } = self;
        dir_cache.refresh_interval()
    }

    /// Creates a file in the cache using a callback for initialization.
    fn get<'a>(&'a self, path: impl AsRef<Path>, callback: impl CallbackFn + 'static) -> Result<CacheFile<'a>> {
        let Self { dir_cache, .. } = self;
        dir_cache.get(path, callback)
    }

    /// Creates a file in the cache that is lazily created when accessed.
    fn get_lazy<'a>(
        &'a self,
        path: impl AsRef<Path>,
        callback: impl CallbackFn + 'static,
    ) -> Result<CacheLazyFile<'a>> {
        let Self { dir_cache, .. } = self;
        dir_cache.get_lazy(path, callback)
    }
}