Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions CHANGELOG.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ composer test
composer test-coverage
```

All pull requests must pass the existing test suite (605 tests) before merging. If you add a new feature, include corresponding test cases.
All pull requests must pass the existing test suite (678 tests) before merging. If you add a new feature, include corresponding test cases.

## Coding Style

Expand Down
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ SmartCache is built for the painful cases that appear after an application grows

- **Data shape is preserved.** Chunked payloads keep associative keys and sparse numeric keys intact, so ID-keyed arrays do not come back reindexed.
- **Partial chunk loss is recoverable.** If a chunk is missing or corrupted, SmartCache treats the entry as a cache miss, evicts the broken metadata, and lets `remember()` regenerate a clean value.
- **Readers never mix versions (v1.16.0+).** Every chunked write stores its chunks under new keys and deletes the replaced entry's chunks only after the new entry is stored, so a concurrent reader gets the old value or the new one, never a mix. A chunked value that shrinks leaves no trailing chunks behind, and the chunks of values stored without expiry are registered so `smart-cache:cleanup-chunks` can remove them if their entry is evicted, deleted outside SmartCache, or replaced by a value that is not chunked.
- **Null remains a valid cached value.** Stored `null` is distinguished from a miss, preserving Laravel cache semantics while still enabling self-healing.
- **Raw repository access is still available.** Use `SmartCache::repository()` when a package or one-off operation needs the underlying Laravel cache store directly.

Expand Down Expand Up @@ -214,6 +215,8 @@ $users = $memo->remember('users', 3600, fn() => User::all());
$users = $memo->get('users'); // instant — served from memory
```

By default each `memo()` call creates its own memo layer, so keep the instance in a variable. Set `smart-cache.memo.native = true` (v1.16.0+, Laravel 12.9+) to build `memo()` on Laravel's `Cache::memo()` instead. There is then one memo layer per store, shared with `Cache::memo()` and every other `memo()` call, and Laravel clears it between requests and queued jobs. SmartCache still compresses, chunks, and restores above it, and SmartCache tags work on it: `SmartCache::memo()->tags(['reports'])->remember(...)`. Like `Cache::memo()`, a key the request already read as missing keeps reading as missing until the request writes it. `add()` stays atomic: it writes to the store directly, and SmartCache reads that key from the store for the rest of the request (Laravel's own `Cache::memo()` still remembers its earlier miss). SmartCache's own bookkeeping (deduplication records, tag indexes, the managed-key index) is never memoized in either mode.

### Atomic Locks

```php
Expand Down Expand Up @@ -244,7 +247,9 @@ SmartCache::tags(['users'])->put('user_1', $user, 3600);
SmartCache::flushTags(['users']);
```

Use `flushTags()` to invalidate by tag; `flush()` clears the entire store. By default, tags set with `tags()` stay active until a write uses them, so after a tagged `get()` that misses they also tag the next write, whatever its key. That only causes extra invalidation. New applications can set `smart-cache.tags.scoped = true` (v1.15.0+). Then, after a tagged lookup, the tags only apply to a later write of a key looked up while they were pending. The "read, then write on a miss" pattern stays tagged, and unrelated writes are not. In that mode, compute values before calling `tags()`, or use `tags()->remember()`.
Use `flushTags()` to invalidate by tag. Since v1.16.0, `SmartCache::tags(['users'])->flush()` does the same, like Laravel's `Cache::tags()->flush()`: it removes only the tagged entries, with their chunks and metadata, and `tags([])->flush()` removes nothing. A plain `flush()` still clears the entire store. Like pending tags in general, a `tags()` call left unused (for example, when computing the value throws) applies to the next `flush()` on the facade in the same request too. Tags work on every store, including file and database, because SmartCache keeps its own tag index, and `tags('a', 'b')`, enum tag names, and `tags(...)->putMany()` (which tags every key) behave as in Laravel. By default, tags set with `tags()` stay active until a write uses them, so after a tagged `get()` that misses they also tag the next write, whatever its key. That only causes extra invalidation. New applications can set `smart-cache.tags.scoped = true` (v1.15.0+). Then, after a tagged lookup, the tags only apply to a later write of a key looked up while they were pending. The "read, then write on a miss" pattern stays tagged, and unrelated writes are not. In that mode, compute values before calling `tags()`, or use `tags()->remember()`.

Dependencies follow the active namespace (v1.16.0+). Tenants that use the same key names keep their own edges, so invalidating `user_profile` in one tenant never stops another tenant's `invalidate('user_profile')` from clearing its `user_posts`.

### Model Auto-Invalidation

Expand Down Expand Up @@ -421,6 +426,7 @@ return [
'metadata_lock' => ['enabled' => true, 'ttl' => 5, 'wait' => 1],
'model_invalidation' => ['after_commit' => true],
'tags' => ['scoped' => false], // v1.15.0: opt-in scoped tags (recommended for new apps)
'memo' => ['native' => false], // v1.16.0: build memo() on Laravel's Cache::memo() (Laravel 12.9+)
'dashboard' => ['enabled' => false, 'prefix' => 'smart-cache', 'middleware' => ['web']],
'warmers' => [], // Cache warmer classes for smart-cache:warm
];
Expand All @@ -430,6 +436,8 @@ return [

SmartCache is registered as a singleton, which means per-request state (active tags, namespaces, in-memory metric buffers) would normally leak between requests on **Laravel Octane**, **Swoole**, **FrankenPHP** or **RoadRunner**. Since **v1.12.0** the service provider's `terminating()` hook calls `SmartCache::reset()` and `OrphanChunkCleanupService::flush()` at the end of every request, so there is **nothing extra to configure**. If you embed SmartCache in your own long-running runtime, call `app(\SmartCache\Contracts\SmartCache::class)->reset()` between iterations.

Queue workers never terminate between jobs. Since **v1.16.0**, `queue:work` calls `SmartCache::refreshState()` before each job. Pending bookkeeping is persisted, the managed-key index and dependency map are re-read on next use, and pending tags are dropped, so `flushPatterns()` and model invalidation in a job see keys that other processes added. The namespace and runtime settings (jitter, circuit breaker) are kept, and sync-queue jobs are not affected.

## Cache Clearing Semantics

SmartCache 1.x preserves its historical managed-only behavior for `clear()`. Prefer the explicit method in new code:
Expand Down Expand Up @@ -457,14 +465,24 @@ $users = SmartCache::get('users');

Review calls to `clear()` during migration and choose `clearManaged()` or `flush()` explicitly. For incremental adoption, keep Laravel's `Cache` facade alongside SmartCache and migrate only large or operationally sensitive keys.

Since v1.16.0 the rest of Laravel 13's `Repository` API works through SmartCache too:
- enum keys (`SmartCache::get(CacheKey::Users)`);
- the typed getters `string()`, `integer()`, `float()`, `boolean()`, `array()`;
- `missing()` and `rememberWithWarmth()`;
- Closure TTLs in `remember()`;
- `DateInterval` durations in `flexible()`;
- `tags(...)->flush()`.

These read optimized entries and honor the namespace.

## Documentation

[Full documentation →](https://iazaran.github.io/smart-cache/) — Installation, API reference, SWR patterns, and more.

## Testing

```bash
composer test # 605 tests, 2,251 assertions
composer test # 678 tests, 2,475 assertions
composer test-coverage # with code coverage
```

Expand Down
6 changes: 3 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

## Supported Versions

Only the latest SmartCache minor line receives routine security fixes. We recommend `^1.15` for existing 1.x installations.
Only the latest SmartCache minor line receives routine security fixes. We recommend `^1.16` for existing 1.x installations.

| SmartCache Version | Maintained? | Package Compatibility |
| ------------------ | ----------- | --------------------- |
| 1.15.x | :white_check_mark: | PHP 8.1–8.5, Laravel 8–13 |
| 1.9.x–1.14.x | :warning: | Upgrade required; security backports are not guaranteed |
| 1.16.x | :white_check_mark: | PHP 8.1–8.5, Laravel 8–13 |
| 1.9.x–1.15.x | :warning: | Upgrade required; security backports are not guaranteed |
| < 1.9.0 | :x: | Unsupported |

Package compatibility does not extend the security lifetime of PHP, Laravel, or the selected cache backend. Enterprise deployments should use a [currently supported PHP release](https://www.php.net/supported-versions.php) and a Laravel version inside the [official Laravel support window](https://laravel.com/docs/releases#support-policy).
Expand Down
2 changes: 1 addition & 1 deletion TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ vendor/bin/phpunit
Current suite size:

```bash
# 605 tests, 2,251 assertions
# 678 tests, 2,475 assertions
```

### Run Specific Test Suites
Expand Down
36 changes: 31 additions & 5 deletions config/smart-cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,21 +262,47 @@
| calling tags(): a cache lookup inside tags('t')->put('k', $service->build())
| runs after tags(). Or use tags('t')->remember().
|
| Since 1.16.0, tags('t')->flush() removes only the entries tagged 't' (like
| flushTags('t') and Laravel's Cache::tags('t')->flush()); a plain flush()
| still clears the whole store.
|
*/
'tags' => [
'scoped' => false,
],

/*
|--------------------------------------------------------------------------
| Memoization
|--------------------------------------------------------------------------
|
| SmartCache::memo() keeps values read during a request or job in memory.
| By default every memo() call creates its own memo layer.
|
| 'native' => true (Laravel 12.9+, since 1.16.0) builds memo() on Laravel's
| Cache::memo() instead: one memo layer per store, shared with Cache::memo()
| and with every other memo() call, which Laravel clears between requests
| and queued jobs. On older Laravel versions memo() keeps its own layer.
| In that mode add() writes to the store directly (it stays atomic), and
| SmartCache then reads that key from the store for as long as the memo
| layer lives.
|
*/
'memo' => [
'native' => false,
],

/*
|--------------------------------------------------------------------------
| Chunk Registry
|--------------------------------------------------------------------------
|
| The orphan-chunk cleanup service persists its registry every time a
| chunked entry is written. On extremely write-heavy workloads this
| can dominate cache I/O. Increase `persist_every` to batch writes —
| the registry is still flushed on `cleanupOrphanChunks()` and on
| service shutdown. Default `1` matches the historical behaviour.
| Since 1.16.0 SmartCache registers the chunks of every chunked value stored
| without expiry, and `smart-cache:cleanup-chunks` removes the ones whose
| entry is gone or was replaced. Chunks of values with a TTL expire with
| them. SmartCache updates the registry right away, under a metadata lock;
| `persist_every` only batches OrphanChunkCleanupService::registerChunks()
| calls made by your own code. Default `1` persists every change.
|
*/
'chunk_registry' => [
Expand Down
Loading
Loading