Skip to content

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

super_cache

pub package Dart SDK License: MIT pub points codecov CI Publisher


Production-ready LRU + TTL cache for Flutter and Dart. Add caching to any repository in 3 lines. Prevent duplicate API calls. Persist to disk. Observe live metrics. Optional AES-256-GCM encryption.

⚡ Fast, production-ready cache for Flutter & Dart
💨 L1 Memory: O(1) LRU + TTL, synchronous reads
🔒 L2 Secure: AES-256-GCM in-memory encryption
💾 L3 Disk: file-per-entry persistence, integrity checks
🚀 1 mixin + 1 method → stampede protection, live metrics
🛠 Integrates with repository pattern in 3 lines

Quick Example

class ProductRepository with CacheRepositoryMixin<String, Product> {
  @override
  final cache = MemoryCache<String, Product>(
    maxEntries: 200,
    defaultTTL: const Duration(minutes: 5),
  );

  Future<Product?> getProduct(String id) =>
      fetchWithCache(id, onMiss: () => api.fetchProduct(id));
}

✅ One mixin. One method. LRU, TTL, stampede protection, and metrics — automatically.


🗂 Package Family

Package Description Depends on
super_cache Core LRU engine, orchestrator, repository mixin Zero external deps
super_cache_secure AES-256-GCM encrypted in-memory cache flutter_secure_storage
super_cache_disk Persistent file-per-entry cache with integrity checks Pure Dart
super_cache_testing FakeCache + ManualClock for deterministic tests Pure Dart

🚀 Why super_cache?

  • Stampede protection: multiple simultaneous requests for the same key only trigger one network call.
  • Layered caching: L1 → L2 → L3; hits promote upward automatically.
  • Mobile-first: memory pressure integration, live metrics, background sweep, and optional encrypted memory.
  • Production-ready: tested, benchmarked, and deterministic with FakeCache + ManualClock.
Without super_cache:                With super_cache:
Widget A ──► API call ──► response   Widget A ──► API call ──► response
Widget B ──► API call ──► response   Widget B ──────────────► (same future)
Widget C ──► API call ──► response   Widget C ──────────────► (same future)
           3 network calls                      1 network call

🔧 Installation

Core only

dependencies:
  super_cache: ^1.1.0

Full stack

dependencies:
  super_cache: ^1.1.0
  super_cache_secure: ^1.1.0 # optional: AES-256-GCM
  super_cache_disk: ^1.1.0 # optional: disk persistence

dev_dependencies:
  super_cache_testing: ^1.1.0 # deterministic tests

⚙️ Choose Your Setup

Path A — In-memory only
final cache = MemoryCache<String, Product>(
  maxEntries: 200,
  defaultTTL: const Duration(minutes: 5),
);
Path B — Offline persistence
final disk = DiskCache<String, Product>(
  directory: await getApplicationCacheDirectory(),
  codec: JsonCacheCodec(fromJson: Product.fromJson, toJson: (p) => p.toJson()),
  defaultTTL: const Duration(hours: 24),
);
await disk.initialize();

final cache = CacheOrchestrator<String, Product>(
  l1: MemoryCache(maxEntries: 200),
  l3: disk,
);
Path C — Encryption + persistence
final cache = CacheOrchestrator<String, Product>(
  l1: MemoryCache(maxEntries: 200, defaultTTL: Duration(minutes: 5)),
  l2: SecureCache(keyStore: FlutterSecureKeyStore()),
  l3: disk,
);

🏗 Architecture (Quick View)

Repository
   │
   ▼ fetchWithCache() → stampede protection + cache policies
   │
   ▼ CacheOrchestrator<K,V>
      L1: MemoryCache  💨  O(1) LRU + TTL
      L2: SecureCache 🔒  AES-256-GCM
      L3: DiskCache   💾  File-per-entry persistence

⚡ Features at a glance

  • O(1) LRU + TTL (absolute/sliding)
  • Byte-based eviction via sizeEstimator
  • Stampede protection (single network call per key)
  • Layer promotion: L3 → L2 → L1
  • Cache policies: CacheAside, WriteThrough, RefreshAhead
  • Live metrics: snapshot + stream
  • Memory pressure hooks (evictFraction())
  • FutureOr<V?> API — memory hits synchronous
  • Test utilities: FakeCache + ManualClock

🧪 Testing

final clock = ManualClock();
final cache = FakeCache<String, int>(clock: clock);

cache.put('score', 42, ttl: Duration(minutes: 5));
clock.advance(Duration(minutes: 6));
assert(cache.get('score') == null);

⚠️ When Not to Use

Situation Recommendation
Tiny apps (<5 cached values) Use a plain Map
Multi-isolate caching Implement your own bridge on top of DiskCache
Large blobs (>50 MB or >50k entries) Use a local database
Hardware secure enclave required SecureCache keeps decrypted values in memory only
No lifecycle / never calls dispose() Use a simpler ephemeral cache

📊 Metrics & Observability

final m = cache.metrics;
print('Hit rate: ${(m.hitRate*100).toStringAsFixed(1)}%');
cache.metricsStream.listen((m) {
  analytics.record('cache_hit_rate', m.hitRate);
});

🏎 Benchmarks (Highlights)

Layer Get hit Put Notes
MemoryCache 0.04 µs 0.11 µs 25M hits/sec
CacheOrchestrator L1+L2 0.22 µs 0.52 µs async overhead ~180 ns
DiskCache (SSD) 108 µs 2.23 µs async write-back
Full benchmark table …includes TTL expired, putAll, removeWhere, etc.

🏠 Repository Structure

super_cache/
├─ packages/
│  ├─ super_cache/
│  ├─ super_cache_secure/
│  ├─ super_cache_disk/
│  └─ super_cache_testing/
├─ example/super_cache_demo/
└─ analysis_options.yaml

🔗 Links


⚖️ License

MIT — see individual package LICENSE files. Published by jihedmrouki.com

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages