litespeedtech / lscache-laravel

LSCache for Laravel framework
GNU General Public License v3.0
51 stars 14 forks source link

Function to "Purge and Re-cache" immediately #3

Closed darkponyhq closed 4 years ago

darkponyhq commented 4 years ago

Hi,

Is there a way to extent the Purge function and once the requested slug e.g. "/" or "contact-us" is purged from the cache, to be re-cached immediately (and not wait for the first front-end user to hit it).

This will allow to purge and re-cache content that's updated and we want to serve it cached even for the 1st request.

Thanks

lucasRolff commented 4 years ago

Hi @darkponyhq

There's not really an optimal way to integrate this since purging allows purging specific URLs, tags or wildcards, and having to determine this within a purge and cache function adds complex logic.

Since you already know the URL you're going to purge within the function/route where you call the LSCache::purge function, you can simply use the guzzle HTTP client to then call the page again to recache it.

If I can think of another way, that simplifies this, it will surely get added into the package.

darkponyhq commented 4 years ago

Hi @lucasRolff

Thanks for your reply. Guzzle is the first thing we tried but for some reason it does not cache the url (probably something wrong from our end), we tried CURL direct as well but still not luck.

wget on terminal works but that's the ideal solution

lucasRolff commented 4 years ago

@darkponyhq,

There are two ways: 1: You purge the the page using LSCache::purge, return it, and call another URL right (such as the page that needs to be cached).

2: You can purge by using a PURGE request instead and then call the URL with guzzle right after.

Number 2, allows you to do this in a single route easily, because purging and warming up happens in the same request.

Let's say you have a route called /updatepost which updates post data, purges the page and recaches it, you could do something like this:

Route::post('/updatepost', function (Post $post) {

    // Do your post logic here

    $client = new GuzzleHttp\Client(['base_uri' => 'http://127.0.0.1']);
    $options = ['headers' => ['Host' => request()->getHost() ]];

    // Let's purge the request
    $response = $client->request('PURGE', $post->slug, $options);

    // Let's cache the page again
    $response = $client->request('GET', $post->slug, $options);
});

The reason why the base_uri gets set to 127.0.0.1 and then we use the Host header is that we want to enforce traffic to come from 127.0.0.1 as well which is trusted by default to do PURGE requests.

I might try to do something like above with a cache and/or purge_and_cache function that only accepts URLs.

The above code is tested on OLS and LSWS by the way.

darkponyhq commented 4 years ago

Thanks @lucasRolff we will give this a go and we will get back with feedback.