Skip to content

Commit 44b395a

Browse files
authored
Merge pull request #28 from iazaran/Improvements-and-new-features-v1.6
Improvements and new features v1.6
2 parents c07010b + 39ee144 commit 44b395a

27 files changed

+3392
-474
lines changed

.github/workflows/tests.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jobs:
1313
strategy:
1414
fail-fast: true
1515
matrix:
16-
php: [8.1, 8.2, 8.3]
16+
php: [8.1, 8.2, 8.3, 8.4]
1717
laravel: [8.*, 9.*, 10.*, 11.*, 12.*]
1818
stability: [prefer-stable]
1919
include:
@@ -28,10 +28,14 @@ jobs:
2828
- laravel: 12.*
2929
testbench: ^10.0
3030
exclude:
31+
# Laravel 11+ requires PHP 8.2+
3132
- laravel: 11.*
3233
php: 8.1
3334
- laravel: 12.*
3435
php: 8.1
36+
# Laravel 8 doesn't support PHP 8.4
37+
- laravel: 8.*
38+
php: 8.4
3539

3640
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }}
3741

README.md

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,161 @@ Event::listen(OptimizationApplied::class, fn($e) =>
247247

248248
**Events:** CacheHit, CacheMissed, KeyWritten, KeyForgotten, OptimizationApplied
249249

250+
### 🔐 Encryption Strategy
251+
252+
Encrypt sensitive cached data automatically:
253+
254+
```php
255+
// Enable in config
256+
config(['smart-cache.encryption.enabled' => true]);
257+
config(['smart-cache.encryption.keys' => ['user_*', 'payment_*']]);
258+
259+
// Sensitive data is automatically encrypted
260+
SmartCache::put('user_123_ssn', $sensitiveData, 3600);
261+
// Data encrypted at rest, decrypted on retrieval
262+
```
263+
264+
**Benefit:** Secure sensitive data in cache without code changes
265+
266+
### 🏷️ Cache Namespacing
267+
268+
Group and manage cache keys by namespace:
269+
270+
```php
271+
// Set namespace for operations
272+
SmartCache::namespace('users')->put('profile', $data, 3600);
273+
SmartCache::namespace('users')->put('settings', $settings, 3600);
274+
275+
// Flush entire namespace
276+
SmartCache::flushNamespace('users'); // Clears all user:* keys
277+
278+
// Get all keys in namespace
279+
$keys = SmartCache::getNamespaceKeys('users');
280+
```
281+
282+
**Benefit:** Organize cache keys, easy bulk invalidation
283+
284+
### ⏱️ TTL Jitter
285+
286+
Prevent thundering herd with randomized TTL:
287+
288+
```php
289+
// Add 10% jitter to TTL
290+
SmartCache::withJitter(0.1)->put('popular_data', $data, 3600);
291+
// Actual TTL: 3240-3960 seconds (±10%)
292+
293+
// Or use dedicated methods
294+
SmartCache::putWithJitter('key', $value, 3600, 0.15); // 15% jitter
295+
SmartCache::rememberWithJitter('key', 3600, 0.1, fn() => expensiveCall());
296+
```
297+
298+
**Benefit:** Prevents cache stampede when many keys expire simultaneously
299+
300+
### 🔌 Circuit Breaker
301+
302+
Auto-fallback when cache backend fails:
303+
304+
```php
305+
// Check if cache is available
306+
if (SmartCache::isAvailable()) {
307+
$data = SmartCache::get('key');
308+
}
309+
310+
// Execute with automatic fallback
311+
$data = SmartCache::withFallback(
312+
fn() => SmartCache::get('key'), // Primary
313+
fn() => Database::query('SELECT ...') // Fallback
314+
);
315+
316+
// Get circuit breaker stats
317+
$stats = SmartCache::getCircuitBreakerStats();
318+
// Returns: state, failure_count, success_count, last_failure_at
319+
```
320+
321+
**States:** Closed (normal) → Open (failing) → Half-Open (testing)
322+
323+
### 🚦 Rate Limiting & Stampede Protection
324+
325+
Prevent cache stampede with rate limiting:
326+
327+
```php
328+
// Throttle cache operations
329+
$result = SmartCache::throttle('api_call', 10, 60, function() {
330+
return expensiveApiCall();
331+
}); // Max 10 calls per 60 seconds
332+
333+
// Remember with stampede protection (XFetch algorithm)
334+
$data = SmartCache::rememberWithStampedeProtection('key', 3600, function() {
335+
return expensiveComputation();
336+
});
337+
```
338+
339+
**Benefit:** Prevents multiple processes from regenerating cache simultaneously
340+
341+
### 🔥 Cache Warming
342+
343+
Pre-warm cache with artisan command:
344+
345+
```bash
346+
# Warm cache using registered warmers
347+
php artisan smart-cache:warm
348+
349+
# Warm specific warmer
350+
php artisan smart-cache:warm --warmer=ProductCacheWarmer
351+
```
352+
353+
Register warmers in your service provider:
354+
355+
```php
356+
use SmartCache\Contracts\CacheWarmer;
357+
358+
class ProductCacheWarmer implements CacheWarmer
359+
{
360+
public function warm(): void
361+
{
362+
$products = Product::all();
363+
SmartCache::put('all_products', $products, 3600);
364+
}
365+
366+
public function getKey(): string
367+
{
368+
return 'products';
369+
}
370+
}
371+
372+
// Register in AppServiceProvider
373+
$this->app->tag([ProductCacheWarmer::class], 'smart-cache.warmers');
374+
```
375+
376+
### 🧹 Orphan Chunk Cleanup
377+
378+
Automatically clean up orphan chunks:
379+
380+
```bash
381+
# Clean up orphan chunks
382+
php artisan smart-cache:cleanup-chunks
383+
384+
# Dry run (show what would be cleaned)
385+
php artisan smart-cache:cleanup-chunks --dry-run
386+
```
387+
388+
### 📊 Cache Statistics Dashboard
389+
390+
View cache statistics via web interface:
391+
392+
```php
393+
// Enable in config
394+
config(['smart-cache.dashboard.enabled' => true]);
395+
config(['smart-cache.dashboard.prefix' => 'smart-cache']);
396+
config(['smart-cache.dashboard.middleware' => ['web', 'auth']]);
397+
```
398+
399+
**Routes:**
400+
- `GET /smart-cache/dashboard` - HTML dashboard
401+
- `GET /smart-cache/statistics` - JSON statistics
402+
- `GET /smart-cache/health` - Health check
403+
- `GET /smart-cache/keys` - Managed keys list
404+
250405
## 🌊 Modern Patterns (Laravel 12+)
251406

252407
### SWR (Stale-While-Revalidate)
@@ -375,6 +530,41 @@ return [
375530
'enabled' => true,
376531
'metrics_ttl' => 3600,
377532
],
533+
534+
// Encryption for sensitive data
535+
'encryption' => [
536+
'enabled' => false,
537+
'keys' => [], // Keys to encrypt: ['user_*', 'payment_*']
538+
'patterns' => [], // Regex patterns: ['/secret_.*/']
539+
],
540+
541+
// Circuit breaker for cache backend failures
542+
'circuit_breaker' => [
543+
'enabled' => true,
544+
'failure_threshold' => 5, // Failures before opening
545+
'success_threshold' => 2, // Successes to close
546+
'timeout' => 30, // Seconds before half-open
547+
],
548+
549+
// Rate limiting for cache operations
550+
'rate_limiter' => [
551+
'enabled' => true,
552+
'default_limit' => 100, // Max operations per window
553+
'window' => 60, // Window in seconds
554+
],
555+
556+
// TTL jitter to prevent thundering herd
557+
'jitter' => [
558+
'enabled' => false,
559+
'percentage' => 0.1, // 10% jitter by default
560+
],
561+
562+
// Statistics dashboard
563+
'dashboard' => [
564+
'enabled' => false,
565+
'prefix' => 'smart-cache',
566+
'middleware' => ['web'],
567+
],
378568
];
379569
```
380570

config/smart-cache.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,52 @@
4949
'lazy_loading' => false, // Enable lazy loading for chunks
5050
'smart_sizing' => false, // Enable smart chunk size calculation
5151
],
52+
'encryption' => [
53+
'enabled' => false, // Disabled by default
54+
'keys' => [], // Specific keys to encrypt
55+
'patterns' => [], // Regex patterns for keys to encrypt (e.g., '/^user_token_/')
56+
'encrypt_all' => false, // Encrypt all cached values
57+
],
58+
],
59+
60+
/*
61+
|--------------------------------------------------------------------------
62+
| Circuit Breaker
63+
|--------------------------------------------------------------------------
64+
|
65+
| Configure the circuit breaker for cache backend failures.
66+
|
67+
*/
68+
'circuit_breaker' => [
69+
'failure_threshold' => 5, // Number of failures before opening circuit
70+
'recovery_timeout' => 30, // Seconds to wait before trying again
71+
'success_threshold' => 3, // Successful calls needed to close circuit
72+
],
73+
74+
/*
75+
|--------------------------------------------------------------------------
76+
| Rate Limiter
77+
|--------------------------------------------------------------------------
78+
|
79+
| Configure rate limiting for cache operations.
80+
|
81+
*/
82+
'rate_limiter' => [
83+
'window' => 60, // Window in seconds
84+
'max_attempts' => 10, // Maximum attempts per window
85+
],
86+
87+
/*
88+
|--------------------------------------------------------------------------
89+
| TTL Jitter
90+
|--------------------------------------------------------------------------
91+
|
92+
| Configure TTL jitter to prevent thundering herd problem.
93+
|
94+
*/
95+
'jitter' => [
96+
'enabled' => false, // Disabled by default
97+
'percentage' => 0.1, // 10% jitter by default
5298
],
5399

54100
/*
@@ -133,4 +179,18 @@
133179
'optimization_applied' => true,
134180
],
135181
],
182+
183+
/*
184+
|--------------------------------------------------------------------------
185+
| Dashboard
186+
|--------------------------------------------------------------------------
187+
|
188+
| Configure the web dashboard for viewing cache statistics.
189+
|
190+
*/
191+
'dashboard' => [
192+
'enabled' => false, // Disabled by default for security
193+
'prefix' => 'smart-cache', // URL prefix for dashboard routes
194+
'middleware' => ['web'], // Middleware to apply to dashboard routes
195+
],
136196
];

0 commit comments

Comments
 (0)