Usage | laravel-responsecache-rust | Spatie       

 SPATIE  

laravel-responsecache-rust
==========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-responsecache-rust](https://spatie.be/docs/laravel-responsecache-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-responsecache-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-responsecache-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-responsecache-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-responsecache-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-responsecache-rust/v1/usage)
- [ Configuration and hooks ](https://spatie.be/docs/laravel-responsecache-rust/v1/configuration-and-hooks)
- [ Testing ](https://spatie.be/docs/laravel-responsecache-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-responsecache-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Register routes ](#content-register-routes)
2. [ Invalidate after writes ](#content-invalidate-after-writes)
3. [ Response and key boundaries ](#content-response-and-key-boundaries)
4. [ Tags and specific URLs ](#content-tags-and-specific-urls)
5. [ Flexible caching ](#content-flexible-caching)

Register routes
-----------------------------------------------------------------------------------------------------

Create one cache handle for related responses. Clones use the same named framework cache store and namespace. Use `routing.routes` for stateless routes or `routing.web` for native sessions and CSRF protection. Authentication and authorization must run before the cache; middleware inside a cache hit will not run.

```
use std::time::Duration;
use spatie_responsecache::ResponseCache;

let cache = ResponseCache::new("database", "blog")
    .lifetime(Duration::from_secs(604_800))
    .max_body_bytes(2 * 1024 * 1024)
    .exclude_path("login")
    .exclude_path("register")
    .exclude_path("password/*")
    .exclude_path("search")
    .exclude_path("community*")
    .exclude_path("newsletter/testimonial")
    .exclude_query_parameter("draft");
```

Attach `cache.clone()` to a route or `route.middleware(cache.clone()).group(...)`. The README has an executable application example. Path exclusions use the framework's `Request::resembles` matching. Query exclusions decode names and detect bracketed parameters. An excluded request neither reads nor writes the cache. A zero lifetime disables both operations.

The default profile caches non-AJAX GETs with status 200–399 and text or JSON content types. It partitions authenticated users using the native user type and ID; all guests share a partition. Session cookies do not create separate entries. Customize the profile's suffix when guest output depends on other state, such as a shopping cart. Put private/session-specific values other than CSRF tokens behind a suitable suffix, replacer or uncached route.

The default `CsrfTokenReplacer` replaces every native session token occurrence before storage and restores the current session's token on hits, including stale hits. The initial response retains its body, cookies and extensions. Stored responses strip `Set-Cookie`; outer native session middleware still issues current cookies on hits. Changed bodies lose ETag and Content-Length. This does not replace the framework's CSRF validation middleware.

Use `DoNotCacheResponse` before the cache to bypass reads and writes. It can also run inside the cache to veto storage of a miss, but it cannot affect an existing hit. `Cache-Control: no-store` is not a veto: profiles decide whether those responses are eligible.

Views can use the same middleware. To render explicitly:

```
use laravel::http::Response;

async fn index() -> laravel::Result<Response> {
    Ok(Response::new(laravel::view("posts.index", ()).render()?))
}
```

Only the rendered HTTP representation is stored, not arbitrary view metadata in extensions.

Invalidate after writes
-----------------------------------------------------------------------------------------------------------------------------

Call `clear` after the database transaction commits, from save/publish actions and scheduled ad changes. A cache handle constructed separately with the same store and namespace works too.

```
use spatie_responsecache::ResponseCache;

ResponseCache::new("memory", "public-pages").clear().await?;
```

In requests and framework jobs the application context is already active. For external tools, use `Application::scope`, as the example's test setup does. Failures are returned as `laravel::Error`; handle or propagate them rather than claim an invalidation succeeded.

Invalidation rotates a random generation in the cache. It never calls `flush` and needs no tag support. A handler already in flight can finish writing its old generation, but future requests cannot reach it. Obsolete entries expire using their original TTL. The generation expires after 30 days; a missing generation gets a new random value, so expired or evicted generation metadata cannot resurrect old responses. Requests already reading a hit when `clear` runs may finish returning that hit; this is not a global request barrier.

Use a single authoritative cache backend. A failover store can expose previously invalidated entries when its primary returns. Read replicas and request memoization can also hide a clear. Never configure those for this middleware. Use separate namespaces for independent sites, and the same namespace for all representations that a content change must invalidate.

Response and key boundaries
-----------------------------------------------------------------------------------------------------------------------------------------

The default limit is 2 MiB. Unknown-length streams, bodies with trailers and oversized bodies bypass storage. Eligible responses retain status, header values other than cookies, and body bytes. Serialization is binary-safe through the framework repository. Arbitrary response extensions are not serializable and are not restored on hits.

The default profile accepts `text/*`, `/json` and `+json` content types, including charset parameters. Use a custom profile for XML feeds served as `application/atom+xml` or `application/rss+xml`, binary responses or non-GET methods. Headers such as Cache-Control, Age and Expires do not override the profile. Put downstream freshness policy outside the cache so it runs again on hits.

The default length-framed SHA-256 key includes URL, HTTP method and profile suffix. Scheme, host, port, raw query order and duplicates remain distinct after removing configured ignored query keys. Headers and cookies are not included. Supply a custom hasher for language or other header-dependent output. The cache cannot infer dependencies on IP, time, randomness, service bindings or custom extensions. Clear the namespace when deploying changed representations.

Stored response and generation-metadata keys are SHA-256 digests with a short prefix, always 78 ASCII bytes regardless of tag count, namespace length or custom hasher output. Admission counters use 87 bytes; native flexible-cache metadata uses up to 103 bytes. For a database store with `VARCHAR(255)` keys, keep the application's cache prefix at most 152 bytes so all of these keys fit. The v4 key namespace starts cold automatically when upgrading; existing entries expire normally without a schema change or whole-store flush.

There is no terminable middleware hook in framework 0.1.0: the cache captures the final inner pipeline response, not changes made by outer middleware after it returns. Keep representation changes inside the cache and hit-time policies outside it. Ordinary entry read/decode failures are reported through the framework and treated as misses. Metadata, write, serialization, replacer, body-read and synchronous flexible-cache failures propagate as framework errors.

Cloud edge cache control and purge calls are separate application concerns. This package does not call Cloudflare, enqueue jobs, or register production schedules. Its optional `responsecache:clear` command invalidates only its own configured namespace, never a whole store.

Tags and specific URLs
--------------------------------------------------------------------------------------------------------------------------

Use `.tags(["posts", "homepage"])` on a route cache handle. `clear_tags(&["posts"]).await?`invalidates any response carrying that tag, preserving unrelated tags and untagged responses. Global tags in `Config` are included alongside route tags. `clear()` invalidates every tag partition in the namespace. Native repositories do not expose tags, so this package rotates tag generations through the existing repository instead of introducing another cache backend.

`forget("/posts/42").await?` invalidates all methods, suffixes and tag partitions of that URL. Relative URLs resolve against the native application's configured URL. Absolute URLs must use the same origin and raw query as incoming requests. Ignored query keys are removed too. `forget_urls(&["/posts/42", "/"]).await?` handles several URLs. Use `clear_tags` for groups instead of wildcard URL scans.

`forget_request(&request).await?` invalidates only the given request's method, hasher inputs and suffix, across tags. `hash_for(&request).await?` exposes the same identity. A synthetic native request can carry `extensions::CacheNameSuffix(String)` to override the profile suffix, for example when invalidating a specific user's entry without an authenticated request.

Both `clear_tags` and `forget_urls` borrow slices of `String` or `&str`. Pass a `Vec<String>`by reference without mapping it to another collection. Empty collections need an explicit element type, such as `Vec::<String>::new()`. For example, after publishing posts:

```
let tags = vec![String::from("posts")];
cache.clear_tags(&tags).await?;
let urls = vec![String::from("/posts/42")];
cache.forget_urls(&urls).await?;
```

Flexible caching
--------------------------------------------------------------------------------------------------------

```
use std::time::Duration;
use spatie_responsecache::ResponseCache;

let cache = ResponseCache::new("memory", "public-pages")
    .lifetime(Duration::from_secs(60))
    .flexible(Duration::from_secs(300));
```

The response is fresh for 60 seconds, then stale for another 300. During grace, the native repository returns the old response and refreshes it under its own lock in a framework background task. Beyond grace, the request waits for a new response. Clear operations also isolate in-flight refreshes in their old generation. This is process-local background work, not a durable job. Profiles, hooks, body limits and admission rules still apply. An ineligible synchronous result is returned unchanged and not stored. A rejected background refresh leaves the old response until expiry and the framework reports the rejected refresh. Do not rely on background refresh to persist session mutations: the outer session middleware may already have saved the session before background work finishes.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
