Skip to content

Commit

Permalink
feat: status codes cache
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaucau committed Nov 21, 2024
1 parent dfbc2a4 commit 877deb2
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 4 deletions.
10 changes: 9 additions & 1 deletion extend.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@
LoginMiddleware,
LogoutMiddleware,
PurgeCacheMiddleware,
StatusCodesCacheMiddleware,
VaryCookieMiddleware
};
use Flarum\Extend;
use Flarum\Foundation\Event\ClearingCache;
use Flarum\Http\Middleware\CheckCsrfToken;
use Flarum\Http\Middleware\InjectActorReference;
use Flarum\Settings\Event\Saved;

return [
Expand All @@ -51,7 +53,8 @@
->default('acpl-lscache.cache_enabled', true)
->default('acpl-lscache.public_cache_ttl', 604_800)
->default('acpl-lscache.clearing_cache_listener', true)
->default('acpl-lscache.drop_qs', implode("\n", LSCache::DEFAULT_DROP_QS)),
->default('acpl-lscache.drop_qs', implode("\n", LSCache::DEFAULT_DROP_QS))
->default('acpl-lscache.status_codes_cache', "404 3600\n403 3600\n500 120"),
(new Extend\Event())->listen(Saved::class, Listener\UpdateSettingsListener::class),

// Vary cookie
Expand All @@ -67,6 +70,10 @@
(new Extend\Middleware('forum'))->add(CacheTagsMiddleware::class),
(new Extend\Middleware('api'))->add(CacheTagsMiddleware::class),

// Cache status codes
(new Extend\Middleware('forum'))->insertAfter(InjectActorReference::class, StatusCodesCacheMiddleware::class),
(new Extend\Middleware('api'))->insertAfter(InjectActorReference::class, StatusCodesCacheMiddleware::class),

// Cache routes
(new Extend\Middleware('forum'))->insertAfter(VaryCookieMiddleware::class, CacheControlMiddleware::class),
(new Extend\Middleware('api'))->insertAfter(VaryCookieMiddleware::class, CacheControlMiddleware::class),
Expand All @@ -88,6 +95,7 @@
(new Extend\Event)->subscribe(PostEventSubscriber::class),
(new Extend\Event)->subscribe(UserEventSubscriber::class),

// Extensions
(new Extend\Conditional)
->whenExtensionEnabled('flarum-likes', [
(new Extend\Event)->subscribe(LikesEventSubscriber::class),
Expand Down
6 changes: 6 additions & 0 deletions js/src/admin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ app.initializers.add('acpl-lscache', () => {
),
}),
type: 'textarea',
})
.registerSetting({
setting: 'acpl-lscache.status_codes_cache',
label: app.translator.trans('acpl-lscache.admin.status_codes_cache_label'),
help: app.translator.trans('acpl-lscache.admin.status_codes_cache_help'),
type: 'textarea',
});

addPurgeLSCacheButton();
Expand Down
3 changes: 3 additions & 0 deletions locale/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@ acpl-lscache:
Use this feature to drop specific query strings, like <code>fbclid</code> or <code>utm*</code>, when caching. This prevents redundant caching of pages with "junk" query strings such as UTM codes, which are used for tracking but don't affect page content. This requires LSWS v5.2.3 or newer. List the query strings to drop, one per line. <a>Learn more about dropping query strings</a>.<br></br>
⚠️ This setting will modify the .htaccess file.
status_codes_cache_label: "Default HTTP Status Code Page TTL"
status_codes_cache_help: "Specify an HTTP status code and the number of seconds to cache that page, separated by a space. One per line."

purge_all: "Purge All LSCache"
purge_all_success: "LiteSpeed Web Server has been notified to purge all LSCache entries"
4 changes: 1 addition & 3 deletions src/Middleware/CacheControlMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@

class CacheControlMiddleware implements MiddlewareInterface
{
private SettingsRepositoryInterface $settings;
private array $session;

public function __construct(SettingsRepositoryInterface $settings, ConfigRepository $config)
public function __construct(private readonly SettingsRepositoryInterface $settings, ConfigRepository $config)
{
$this->settings = $settings;
$this->session = $config->get('session');
}

Expand Down
51 changes: 51 additions & 0 deletions src/Middleware/StatusCodesCacheMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace ACPL\FlarumLSCache\Middleware;

use ACPL\FlarumLSCache\LSCacheHeader;
use Flarum\Http\RequestUtil;
use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};

class StatusCodesCacheMiddleware implements MiddlewareInterface
{
public function __construct(protected SettingsRepositoryInterface $settings) { }

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if ($response->hasHeader(LSCacheHeader::CACHE_CONTROL)) {
return $response;
}

$actor = RequestUtil::getActor($request);
// Guest-only cache
if (! $actor->isGuest()) {
return $response;
}

$settings = $this->settings->get('acpl-lscache.status_codes_cache');
$lines = array_filter(explode("\n", $settings));
if (empty($lines)) {
return $response;
}

$statusCode = $response->getStatusCode();

foreach ($lines as $line) {
// [0] - status code, [1] - cache ttl
$codeTtl = array_map('intval', explode(' ', trim($line)));
if (empty($codeTtl[0]) || empty($codeTtl[1])) {
continue;
}

if ($codeTtl[0] === $statusCode) {
return $response->withHeader(LSCacheHeader::CACHE_CONTROL, "public,max-age=$codeTtl[1]");
}
}

return $response;
}
}

0 comments on commit 877deb2

Please sign in to comment.