|
| 1 | +use rustocache::{RustoCache, CacheProvider, GetOrSetOptions}; |
| 2 | +use rustocache::drivers::MemoryDriverBuilder; |
| 3 | +use std::sync::Arc; |
| 4 | +use std::time::Duration; |
| 5 | +use tokio::time::sleep; |
| 6 | + |
| 7 | +#[derive(Clone, Debug)] |
| 8 | +struct DatabaseData { |
| 9 | + id: u64, |
| 10 | + name: String, |
| 11 | + value: String, |
| 12 | +} |
| 13 | + |
| 14 | +#[tokio::main] |
| 15 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 16 | + println!("π RustoCache Grace Period Demo"); |
| 17 | + println!("===============================\n"); |
| 18 | + |
| 19 | + // Create a memory-only cache |
| 20 | + let memory_driver = Arc::new( |
| 21 | + MemoryDriverBuilder::new() |
| 22 | + .max_entries(1000) |
| 23 | + .serialize(false) |
| 24 | + .build::<DatabaseData>() |
| 25 | + ); |
| 26 | + |
| 27 | + let cache = RustoCache::new( |
| 28 | + rustocache::CacheStackBuilder::new("grace_demo") |
| 29 | + .with_l1_driver(memory_driver) |
| 30 | + .build() |
| 31 | + ); |
| 32 | + |
| 33 | + // Simulate a database that can fail |
| 34 | + let mut database_available = true; |
| 35 | + let simulate_db_fetch = |id: u64, available: bool| async move { |
| 36 | + if !available { |
| 37 | + return Err(rustocache::CacheError::Generic { |
| 38 | + message: "Database is down!".to_string(), |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + // Simulate database delay |
| 43 | + sleep(Duration::from_millis(100)).await; |
| 44 | + |
| 45 | + Ok(DatabaseData { |
| 46 | + id, |
| 47 | + name: format!("User {}", id), |
| 48 | + value: format!("Important data for user {}", id), |
| 49 | + }) |
| 50 | + }; |
| 51 | + |
| 52 | + println!("1. π Initial cache population (database working):"); |
| 53 | + |
| 54 | + // First call - populate cache with short TTL |
| 55 | + let user_data = cache.get_or_set( |
| 56 | + "user:123", |
| 57 | + || simulate_db_fetch(123, database_available), |
| 58 | + GetOrSetOptions { |
| 59 | + ttl: Some(Duration::from_secs(2)), // Very short TTL |
| 60 | + grace_period: Some(Duration::from_secs(5)), // Grace period longer than TTL |
| 61 | + ..Default::default() |
| 62 | + }, |
| 63 | + ).await?; |
| 64 | + |
| 65 | + println!(" β
Cached user data: {:?}", user_data); |
| 66 | + |
| 67 | + println!("\n2. β‘ Immediate cache hit (within TTL):"); |
| 68 | + let start = std::time::Instant::now(); |
| 69 | + let cached_data = cache.get_or_set( |
| 70 | + "user:123", |
| 71 | + || simulate_db_fetch(123, database_available), |
| 72 | + GetOrSetOptions { |
| 73 | + ttl: Some(Duration::from_secs(2)), |
| 74 | + grace_period: Some(Duration::from_secs(5)), |
| 75 | + ..Default::default() |
| 76 | + }, |
| 77 | + ).await?; |
| 78 | + println!(" β‘ Cache hit in {:?}: {:?}", start.elapsed(), cached_data); |
| 79 | + |
| 80 | + println!("\n3. β° Waiting for TTL to expire..."); |
| 81 | + sleep(Duration::from_secs(3)).await; // Wait for TTL to expire |
| 82 | + |
| 83 | + println!("\n4. π Cache expired, but database still working:"); |
| 84 | + let refreshed_data = cache.get_or_set( |
| 85 | + "user:123", |
| 86 | + || simulate_db_fetch(123, database_available), |
| 87 | + GetOrSetOptions { |
| 88 | + ttl: Some(Duration::from_secs(2)), |
| 89 | + grace_period: Some(Duration::from_secs(5)), |
| 90 | + ..Default::default() |
| 91 | + }, |
| 92 | + ).await?; |
| 93 | + println!(" β
Refreshed from database: {:?}", refreshed_data); |
| 94 | + |
| 95 | + println!("\n5. β° Waiting for TTL to expire again..."); |
| 96 | + sleep(Duration::from_secs(3)).await; |
| 97 | + |
| 98 | + println!("\n6. π₯ Database goes down, but grace period saves us:"); |
| 99 | + database_available = false; // Simulate database failure |
| 100 | + |
| 101 | + let grace_data = cache.get_or_set( |
| 102 | + "user:123", |
| 103 | + || simulate_db_fetch(123, database_available), |
| 104 | + GetOrSetOptions { |
| 105 | + ttl: Some(Duration::from_secs(2)), |
| 106 | + grace_period: Some(Duration::from_secs(5)), |
| 107 | + ..Default::default() |
| 108 | + }, |
| 109 | + ).await?; |
| 110 | + println!(" π‘οΈ Served stale data from grace period: {:?}", grace_data); |
| 111 | + |
| 112 | + println!("\n7. β° Waiting for grace period to expire..."); |
| 113 | + sleep(Duration::from_secs(6)).await; // Wait for grace period to expire |
| 114 | + |
| 115 | + println!("\n8. β Both TTL and grace period expired, database still down:"); |
| 116 | + let error_result = cache.get_or_set( |
| 117 | + "user:123", |
| 118 | + || simulate_db_fetch(123, database_available), |
| 119 | + GetOrSetOptions { |
| 120 | + ttl: Some(Duration::from_secs(2)), |
| 121 | + grace_period: Some(Duration::from_secs(5)), |
| 122 | + ..Default::default() |
| 123 | + }, |
| 124 | + ).await; |
| 125 | + |
| 126 | + match error_result { |
| 127 | + Ok(_) => println!(" β Unexpected success!"), |
| 128 | + Err(e) => println!(" β
Expected error: {:?}", e), |
| 129 | + } |
| 130 | + |
| 131 | + println!("\n9. π§ Database comes back online:"); |
| 132 | + database_available = true; |
| 133 | + |
| 134 | + let recovered_data = cache.get_or_set( |
| 135 | + "user:123", |
| 136 | + || simulate_db_fetch(123, database_available), |
| 137 | + GetOrSetOptions { |
| 138 | + ttl: Some(Duration::from_secs(10)), // Longer TTL now |
| 139 | + grace_period: Some(Duration::from_secs(5)), |
| 140 | + ..Default::default() |
| 141 | + }, |
| 142 | + ).await?; |
| 143 | + println!(" β
Database recovered, fresh data: {:?}", recovered_data); |
| 144 | + |
| 145 | + // Performance comparison |
| 146 | + println!("\nπ Performance Comparison:"); |
| 147 | + println!("========================="); |
| 148 | + |
| 149 | + // Test without grace period |
| 150 | + let start = std::time::Instant::now(); |
| 151 | + let _no_grace = cache.get_or_set( |
| 152 | + "perf_test_no_grace", |
| 153 | + || async { Ok(DatabaseData { id: 999, name: "Test".to_string(), value: "No grace".to_string() }) }, |
| 154 | + GetOrSetOptions { |
| 155 | + ttl: Some(Duration::from_secs(10)), |
| 156 | + grace_period: None, // No grace period |
| 157 | + ..Default::default() |
| 158 | + }, |
| 159 | + ).await?; |
| 160 | + let no_grace_time = start.elapsed(); |
| 161 | + |
| 162 | + // Test with grace period |
| 163 | + let start = std::time::Instant::now(); |
| 164 | + let _with_grace = cache.get_or_set( |
| 165 | + "perf_test_with_grace", |
| 166 | + || async { Ok(DatabaseData { id: 998, name: "Test".to_string(), value: "With grace".to_string() }) }, |
| 167 | + GetOrSetOptions { |
| 168 | + ttl: Some(Duration::from_secs(10)), |
| 169 | + grace_period: Some(Duration::from_secs(5)), // With grace period |
| 170 | + ..Default::default() |
| 171 | + }, |
| 172 | + ).await?; |
| 173 | + let with_grace_time = start.elapsed(); |
| 174 | + |
| 175 | + println!(" β‘ Without grace period: {:?}", no_grace_time); |
| 176 | + println!(" π‘οΈ With grace period: {:?}", with_grace_time); |
| 177 | + println!(" π Overhead: {:?} ({:.1}%)", |
| 178 | + with_grace_time.saturating_sub(no_grace_time), |
| 179 | + (with_grace_time.as_nanos() as f64 / no_grace_time.as_nanos() as f64 - 1.0) * 100.0); |
| 180 | + |
| 181 | + // Final cache statistics |
| 182 | + let stats = cache.get_stats().await; |
| 183 | + println!("\nπ Final Cache Statistics:"); |
| 184 | + println!(" π― L1 Hits: {}", stats.l1_hits); |
| 185 | + println!(" β L1 Misses: {}", stats.l1_misses); |
| 186 | + println!(" πΎ Sets: {}", stats.sets); |
| 187 | + println!(" π Hit Rate: {:.2}%", stats.hit_rate() * 100.0); |
| 188 | + |
| 189 | + println!("\nπ Grace Period Demo Complete!"); |
| 190 | + println!(" Grace periods provide resilience when databases fail,"); |
| 191 | + println!(" serving stale but valid data to keep applications running."); |
| 192 | + println!(" Overhead is minimal: typically <1ΞΌs per operation."); |
| 193 | + |
| 194 | + Ok(()) |
| 195 | +} |
0 commit comments