feat(cache): WP Fastest Cache statt WP Super Cache
Die Cache-Integration war für WP Super Cache gebaut, eingesetzt wird aber WP Fastest Cache. Profil (wpfc), Listener, Drosselung, lit/cache-clear und Leeren-Probe laufen jetzt über die öffentlichen WPFC-Funktionen wpfc_clear_post_cache_by_id/wpfc_clear_all_cache; die Probe leert nur die Wegwerf-Seite (singleDeleteCache ohne Elternseiten) und prüft, dass WPFC den Hook noch verarbeitet. Smoke fastest-cache-smoke.sh ersetzt den WPSC-Smoke. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e1fad3dffe
commit
bee9da3a86
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Annotations;
|
||||
use LIT\MCP\Abilities\DeclaresRequirements;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Abilities\FollowUp;
|
||||
use LIT\MCP\Abilities\ToolResult;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* lit/cache-clear: empties the WP Fastest Cache on request – for changes made outside this plugin (the plugin's own
|
||||
* writes empty it anyway, FastestCacheListener). Dry run without confirm; with confirm: true the whole cache goes
|
||||
* through the same throttle and trailing purge as the listener (FastestCachePurger), a post through
|
||||
* wpfc_clear_post_cache_by_id (any status: WPFC also finds the address of a trashed post). The change log entry is
|
||||
* ignored by the listener (NAME).
|
||||
*/
|
||||
final class CacheClearAbility implements Ability, DeclaresRequirements
|
||||
{
|
||||
public const NAME = 'lit/cache-clear';
|
||||
|
||||
private const OUTCOMES = ['purged', 'throttled', 'cache_off'];
|
||||
|
||||
public function __construct(private FastestCachePurger $purger, private ChangeLog $log)
|
||||
{
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return self::NAME;
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Seiten-Cache leeren';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Leert den Seiten-Cache von WP Fastest Cache: scope "all" den ganzen Cache, scope "post" nur die Seite '
|
||||
. 'eines Beitrags (post_id). Änderungen durch LIT MCP leeren ihn ohnehin automatisch – das Tool ist für '
|
||||
. 'Fälle, in denen etwas außerhalb von LIT MCP geändert wurde. Ohne confirm nur Probelauf (nichts wird '
|
||||
. 'geleert); mit confirm: true nach Rückfrage beim Nutzer ausführen. Das Leeren des ganzen Caches ist auf '
|
||||
. 'alle 30 Sekunden gedrosselt (ein Nachlauf folgt).';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'scope' => ['type' => 'string', 'enum' => ['all', 'post']],
|
||||
'post_id' => ['type' => 'integer', 'minimum' => 1, 'description' => 'Pflicht bei scope "post".'],
|
||||
'confirm' => ['type' => 'boolean', 'description' => 'true nach Bestätigung durch den Nutzer.'],
|
||||
],
|
||||
'required' => ['scope'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return ToolResult::schema(
|
||||
[
|
||||
'scope' => ['type' => 'string', 'enum' => ['all', 'post']],
|
||||
'outcome' => ['type' => 'string', 'enum' => self::OUTCOMES],
|
||||
],
|
||||
['scope', 'outcome']
|
||||
);
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return Annotations::write(true);
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function requirements(array $input): array
|
||||
{
|
||||
return match ($input['scope'] ?? null) {
|
||||
'all' => [FastestCacheFeature::PurgeAll->id()],
|
||||
'post' => [FastestCacheFeature::PurgePost->id()],
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
$target = $this->target($input);
|
||||
|
||||
return $target instanceof WP_Error ? $target : true;
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$target = $this->target($input);
|
||||
if ($target instanceof WP_Error) {
|
||||
return $target;
|
||||
}
|
||||
|
||||
$post = $target instanceof WP_Post ? $target : null;
|
||||
$scope = $post === null ? 'all' : 'post';
|
||||
$what = $post === null
|
||||
? 'den ganzen Seiten-Cache'
|
||||
: sprintf('die Seite von "%s" (ID %d)', $post->post_title, $post->ID);
|
||||
$enabled = $this->purger->cacheEnabled();
|
||||
|
||||
if (($input['confirm'] ?? false) !== true) {
|
||||
return $this->dryRun($scope, $post, $what, $enabled);
|
||||
}
|
||||
if (! $enabled) {
|
||||
return $this->result(
|
||||
$scope,
|
||||
'cache_off',
|
||||
'Der Seiten-Cache von WP Fastest Cache ist ausgeschaltet; nichts zu leeren.'
|
||||
);
|
||||
}
|
||||
|
||||
if ($post !== null) {
|
||||
$outcome = $this->purger->post((int) $post->ID) ? FastestCachePurger::PURGED : FastestCachePurger::LOCKED;
|
||||
} else {
|
||||
$outcome = $this->purger->everything();
|
||||
}
|
||||
if ($outcome === FastestCachePurger::LOCKED) {
|
||||
return Errors::make(
|
||||
'compat_incompatible',
|
||||
'WP Fastest Cache ist gesperrt (siehe Reiter Kompatibilität). Es wurde nichts geleert.',
|
||||
'Den Nutzer informieren, dass die Kompatibilität von WP Fastest Cache geprüft werden muss.',
|
||||
423
|
||||
);
|
||||
}
|
||||
|
||||
$summary = match ($outcome) {
|
||||
FastestCachePurger::THROTTLED => 'Der ganze Seiten-Cache wurde vor weniger als 30 Sekunden geleert; das '
|
||||
. 'Leeren folgt als Nachlauf per WP-Cron.',
|
||||
default => ucfirst($what) . ' wurde geleert.',
|
||||
};
|
||||
|
||||
return $this->result($scope, $outcome, $summary, $post);
|
||||
}
|
||||
|
||||
private function dryRun(string $scope, ?WP_Post $post, string $what, bool $enabled): WP_Error
|
||||
{
|
||||
$throttled = $scope === 'all' && $this->purger->throttled();
|
||||
$note = '';
|
||||
if (! $enabled) {
|
||||
$note = ' Der Cache ist ausgeschaltet; es würde nichts geleert.';
|
||||
} elseif ($throttled) {
|
||||
$note = ' Das Leeren wäre gerade gedrosselt und folgt als Nachlauf.';
|
||||
}
|
||||
|
||||
return Errors::confirmRequired(
|
||||
sprintf('Probelauf: %s leeren?%s Nichts wurde geleert.', ucfirst($what), $note),
|
||||
array_filter(
|
||||
['scope' => $scope, 'post_id' => $post?->ID, 'cache_enabled' => $enabled, 'throttled' => $throttled],
|
||||
static fn (mixed $value): bool => $value !== null
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function result(string $scope, string $outcome, string $summary, ?WP_Post $post = null): array
|
||||
{
|
||||
$result = ToolResult::ok($summary)->with('scope', $scope)->with('outcome', $outcome);
|
||||
if (in_array($outcome, ['purged', 'throttled'], true)) {
|
||||
$warnings = [];
|
||||
$logId = FollowUp::run(
|
||||
fn () => $this->log->record(
|
||||
self::NAME,
|
||||
'wpfc',
|
||||
$post === null ? 'all' : (string) $post->ID,
|
||||
$summary
|
||||
),
|
||||
self::NAME . ' change log',
|
||||
'Änderungsprotokoll konnte nicht geschrieben werden; der Cache wurde trotzdem behandelt.',
|
||||
$warnings
|
||||
);
|
||||
$result->logId(is_int($logId) ? $logId : null)->warnings($warnings);
|
||||
}
|
||||
|
||||
return $result->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* The checked target: the WP_Post of scope "post", true for "all" – or the error. Input is not schema-validated
|
||||
* yet when permission() runs.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
*/
|
||||
private function target(array $input): WP_Post|true|WP_Error
|
||||
{
|
||||
$scope = $input['scope'] ?? null;
|
||||
if ($scope === 'all') {
|
||||
return current_user_can('manage_options')
|
||||
? true
|
||||
: Errors::forbidden('Keine Berechtigung, den ganzen Seiten-Cache zu leeren (manage_options).');
|
||||
}
|
||||
if ($scope !== 'post') {
|
||||
return Errors::invalidInput('scope fehlt oder ist ungültig.', ['scope' => '"all" oder "post"']);
|
||||
}
|
||||
|
||||
$id = $input['post_id'] ?? null;
|
||||
if (! is_int($id) || $id < 1) {
|
||||
return Errors::invalidInput(
|
||||
'post_id fehlt oder ist ungültig.',
|
||||
['post_id' => 'positive Ganzzahl erwartet']
|
||||
);
|
||||
}
|
||||
$post = get_post($id);
|
||||
if (! $post instanceof WP_Post) {
|
||||
return Errors::notFound(sprintf('Eintrag %d nicht gefunden.', $id));
|
||||
}
|
||||
|
||||
return current_user_can('edit_post', $id)
|
||||
? $post
|
||||
: Errors::forbidden(sprintf('Keine Berechtigung, Eintrag %d zu bearbeiten.', $id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use Closure;
|
||||
use LIT\MCP\Compatibility\CheckStep;
|
||||
use LIT\MCP\Compatibility\ProbeStep;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/** The check step only WP Fastest Cache has (the purge probe, FastestCacheProbe) and its labels. */
|
||||
final class FastestCacheCheckSteps
|
||||
{
|
||||
public const PROBE = 'probe';
|
||||
|
||||
private const LABEL = 'Leeren-Test an einer Wegwerf-Seite im Cache';
|
||||
private const LABEL_CACHE_OFF = self::LABEL . ' (Cache ist ausgeschaltet, nicht geprüft)';
|
||||
|
||||
/**
|
||||
* The Profile::$extraSteps of WP Fastest Cache. A switched-off cache is a green step that says so: a skipped step
|
||||
* would lock the purge on a site that caches nothing.
|
||||
*
|
||||
* @param Closure(): (list<string>|null) $probe FastestCacheProbe::run().
|
||||
* @return Closure(bool): list<CheckStep>
|
||||
*/
|
||||
public static function extra(Closure $probe): Closure
|
||||
{
|
||||
return ProbeStep::extra(self::PROBE, self::LABEL, self::LABEL_CACHE_OFF, $probe);
|
||||
}
|
||||
|
||||
public static function label(CheckStep $step): string
|
||||
{
|
||||
// Reports saved before labels were stored have none.
|
||||
return $step->label
|
||||
?? ($step->key === self::PROBE ? self::LABEL : null)
|
||||
?? CheckStep::genericLabel($step->key, FastestCacheCompatibility::LABEL)
|
||||
?? $step->key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use LIT\MCP\Compatibility\Call;
|
||||
use LIT\MCP\Compatibility\ConstantRequirement;
|
||||
use LIT\MCP\Compatibility\GlobalRequirement;
|
||||
use LIT\MCP\Compatibility\Manifest;
|
||||
use LIT\MCP\Compatibility\Profile;
|
||||
use LIT\MCP\Compatibility\Tier;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* WP Fastest Cache as a compatibility profile: the two public purge functions FastestCacheListener calls, checked
|
||||
* against 1.5.5 (wpFastestCache.php). Both only fire an action the WpFastestCache instance hooks in its constructor
|
||||
* (singleDeleteCache, deleteCache); the probe exercises singleDeleteCache and checks that hook (FastestCacheProbe).
|
||||
* The cache switch lives in the global $wp_fastest_cache_options (the decoded option WpFastestCache).
|
||||
*/
|
||||
final class FastestCacheCompatibility
|
||||
{
|
||||
public const LABEL = 'WP Fastest Cache';
|
||||
|
||||
public static function profile(): Profile
|
||||
{
|
||||
$all = FastestCacheFeature::cases();
|
||||
|
||||
return new Profile(
|
||||
id: 'wpfc',
|
||||
label: self::LABEL,
|
||||
tier: Tier::LockOnFailure,
|
||||
capabilities: $all,
|
||||
manifests: [new Manifest(
|
||||
'WP Fastest Cache',
|
||||
calls: [
|
||||
new Call('wpfc_clear_post_cache_by_id', 1, [FastestCacheFeature::PurgePost]),
|
||||
new Call('wpfc_clear_all_cache', 0, [FastestCacheFeature::PurgeAll]),
|
||||
new Call('WpFastestCache::singleDeleteCache', 3, [FastestCacheFeature::PurgePost]),
|
||||
new Call('WpFastestCache::getWpContentDir', 1, [FastestCacheFeature::PurgePost]),
|
||||
],
|
||||
constants: [new ConstantRequirement('WPFC_MAIN_PATH', $all)],
|
||||
globals: [
|
||||
new GlobalRequirement('wp_fastest_cache', $all),
|
||||
new GlobalRequirement('wp_fastest_cache_options', $all),
|
||||
]
|
||||
)],
|
||||
active: static fn (): bool => defined('WPFC_MAIN_PATH'),
|
||||
version: static function (): ?string {
|
||||
if (! defined('WPFC_MAIN_PATH')) {
|
||||
return null;
|
||||
}
|
||||
$header = get_file_data(WPFC_MAIN_PATH . 'wpFastestCache.php', ['Version' => 'Version']);
|
||||
$version = $header['Version'] ?? '';
|
||||
|
||||
return $version === '' ? null : $version;
|
||||
},
|
||||
testedVersions: ['1.5.5'],
|
||||
extraSteps: FastestCacheCheckSteps::extra(static fn (): ?array => (new FastestCacheProbe())->run()),
|
||||
stepLabel: FastestCacheCheckSteps::label(...)
|
||||
);
|
||||
}
|
||||
|
||||
/** WPFC caches only while its switch is on (wpFastestCacheStatus in the decoded option, an object or []). */
|
||||
public static function cacheEnabled(): bool
|
||||
{
|
||||
$options = $GLOBALS['wp_fastest_cache_options'] ?? null;
|
||||
|
||||
return is_object($options) && ! empty($options->wpFastestCacheStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use LIT\MCP\Compatibility\Capability;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
// The installed PHPCompatibility sniffs predate enums (PHP 8.1) and read their methods as plain functions.
|
||||
// phpcs:disable PHPCompatibility.Variables.ForbiddenThisUseContexts.OutsideObjectContext
|
||||
|
||||
/** What the plugin does to WP Fastest Cache: empty its cache for one post or entirely. */
|
||||
enum FastestCacheFeature: string implements Capability
|
||||
{
|
||||
case PurgePost = 'wpfc-purge-post';
|
||||
case PurgeAll = 'wpfc-purge-all';
|
||||
|
||||
public function id(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PurgePost => 'Cache eines Beitrags leeren',
|
||||
self::PurgeAll => 'Gesamten Cache leeren',
|
||||
};
|
||||
}
|
||||
|
||||
public function isWrite(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use LIT\MCP\Admin\CompatibilityTab;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use LIT\MCP\Compatibility\ProvidesCompatibility;
|
||||
use LIT\MCP\Integrations\Bootable;
|
||||
use LIT\MCP\Integrations\Integration;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* WP Fastest Cache: the compatibility profile (FastestCacheListener purges after writes, wired by Plugin), the
|
||||
* cleanup of probe pages a dead check left behind and the tool lit/cache-clear – a tool group only while WP Fastest
|
||||
* Cache is loaded.
|
||||
*/
|
||||
final class FastestCacheIntegration implements Integration, ProvidesCompatibility, Bootable
|
||||
{
|
||||
/** @var callable(): bool */
|
||||
private $available;
|
||||
|
||||
/** @param callable(): bool|null $available Whether WP Fastest Cache is loaded; null = WPFC_MAIN_PATH is defined. */
|
||||
public function __construct(
|
||||
?callable $available,
|
||||
private FastestCachePurger $purger,
|
||||
private ChangeLog $log
|
||||
) {
|
||||
$this->available = $available ?? static fn (): bool => defined('WPFC_MAIN_PATH');
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
add_action(CompatibilityTab::LOAD_ACTION, [$this, 'removeOrphans']);
|
||||
}
|
||||
|
||||
/**
|
||||
* lit_mcp_compat_profile_load('wpfc'), before any output: deletes probe pages a dead check left behind
|
||||
* (FastestCacheProbe::removeOrphans()). A GET without nonce on purpose: only the plugin's own leftovers,
|
||||
* idempotent.
|
||||
*/
|
||||
public function removeOrphans(string $profileId): void
|
||||
{
|
||||
if ($profileId === 'wpfc' && $this->isAvailable() && current_user_can('manage_options')) {
|
||||
FastestCacheProbe::removeOrphans();
|
||||
}
|
||||
}
|
||||
|
||||
public function id(): string
|
||||
{
|
||||
return 'wpfc';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return FastestCacheCompatibility::LABEL;
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
return ($this->available)();
|
||||
}
|
||||
|
||||
public function abilities(): array
|
||||
{
|
||||
return [new CacheClearAbility($this->purger, $this->log)];
|
||||
}
|
||||
|
||||
public function compatibilities(): array
|
||||
{
|
||||
return [FastestCacheCompatibility::profile()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use Closure;
|
||||
use LIT\MCP\Admin\CompatibilityTab;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use LIT\MCP\Compatibility\Compatibility;
|
||||
use LIT\MCP\Log;
|
||||
use Throwable;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* Empties the WP Fastest Cache after a write of this plugin (hook lit_mcp_changed). WPFC purges on its own only on
|
||||
* post status transitions (and only with its "new post"/"update post" settings on) and term edits: field, term and
|
||||
* featured-image updates, options, menu locations, Divi design, theme builder and global library modules it never
|
||||
* sees.
|
||||
*
|
||||
* Purge with trailing run: the listener only collects, one purge runs at the end of the request (shutdown). A post
|
||||
* of a public post type (not attachment) that still exists: that post (wpfc_clear_post_cache_by_id, which also
|
||||
* clears the home page, feeds, sitemap, neighbours and term archives of the post). More than one post, or anything
|
||||
* else: the whole cache of this site, once. The whole-cache purge runs at most every THROTTLE seconds (a client
|
||||
* looping over media updates must not keep the cache empty): a purge inside the lock time schedules exactly one
|
||||
* trailing purge (TRAILING_HOOK) at its end (FastestCachePurger, shared with lit/cache-clear). Single-post purges are
|
||||
* never throttled. The release/withdraw entries of the check workflow change nothing on the site and purge nothing;
|
||||
* the entries of lit/cache-clear purged themselves.
|
||||
*/
|
||||
final class FastestCacheListener
|
||||
{
|
||||
public const TRAILING_HOOK = FastestCachePurger::TRAILING_HOOK;
|
||||
public const PURGED_AT = FastestCachePurger::PURGED_AT;
|
||||
|
||||
private FastestCachePurger $purger;
|
||||
private Closure $postIdFor;
|
||||
/** @var array<int, true> posts changed in this request */
|
||||
private array $posts = [];
|
||||
private bool $everything = false;
|
||||
private bool $queued = false;
|
||||
|
||||
/**
|
||||
* Defaults are the real WPFC and WordPress functions; closures only for tests.
|
||||
*
|
||||
* @param Closure(FastestCacheFeature): bool $usable Compatibility::usable().
|
||||
* @param (Closure(): bool)|null $cacheEnabled WPFC caching switched on.
|
||||
* @param (Closure(int): void)|null $purgePost wpfc_clear_post_cache_by_id($postId).
|
||||
* @param (Closure(): void)|null $purgeAll wpfc_clear_all_cache().
|
||||
* @param (Closure(string, string): ?int)|null $postIdFor Post ID if objectType/objectId name an existing
|
||||
* post of a public type but attachment.
|
||||
*/
|
||||
public function __construct(
|
||||
Closure $usable,
|
||||
?Closure $cacheEnabled = null,
|
||||
?Closure $purgePost = null,
|
||||
?Closure $purgeAll = null,
|
||||
?Closure $postIdFor = null
|
||||
) {
|
||||
$this->purger = new FastestCachePurger($usable, $cacheEnabled, $purgePost, $purgeAll);
|
||||
$this->postIdFor = $postIdFor ?? self::publicPostId(...);
|
||||
}
|
||||
|
||||
public static function create(Compatibility $compatibility): self
|
||||
{
|
||||
return new self($compatibility->usable(...));
|
||||
}
|
||||
|
||||
public function register(): void
|
||||
{
|
||||
add_action(ChangeLog::CHANGED_ACTION, [$this, 'onChange'], 10, 4);
|
||||
add_action(self::TRAILING_HOOK, [$this, 'trailingPurge']);
|
||||
}
|
||||
|
||||
/** lit_mcp_changed: only collects, see flush(). Never throws. */
|
||||
public function onChange(string $ability, string $objectType, string $objectId, ?int $logId = null): void
|
||||
{
|
||||
try {
|
||||
$ignored = CompatibilityTab::isReleaseAbility($ability) || $ability === CacheClearAbility::NAME;
|
||||
if ($ignored || ! $this->purger->cacheEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$postId = ($this->postIdFor)($objectType, $objectId);
|
||||
if ($postId === null) {
|
||||
$this->everything = true;
|
||||
} else {
|
||||
$this->posts[$postId] = true;
|
||||
}
|
||||
if (! $this->queued) {
|
||||
$this->queued = true;
|
||||
add_action('shutdown', [$this, 'flush']);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::failure('WP Fastest Cache purge', $e);
|
||||
}
|
||||
}
|
||||
|
||||
/** shutdown: the one purge of the request. Never throws: a failed purge must not break the response. */
|
||||
public function flush(): void
|
||||
{
|
||||
$posts = array_keys($this->posts);
|
||||
$everything = $this->everything;
|
||||
$this->posts = [];
|
||||
$this->everything = false;
|
||||
|
||||
try {
|
||||
if ($everything || count($posts) > 1) {
|
||||
$this->purger->everything();
|
||||
} elseif ($posts !== []) {
|
||||
$this->purger->post($posts[0]);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::failure('WP Fastest Cache purge', $e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Cron TRAILING_HOOK: the whole-cache purge a throttled one postponed. Same checks as the first try. */
|
||||
public function trailingPurge(): void
|
||||
{
|
||||
try {
|
||||
if ($this->purger->cacheEnabled()) {
|
||||
$this->purger->everything();
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::failure('WP Fastest Cache trailing purge', $e);
|
||||
}
|
||||
}
|
||||
|
||||
private static function publicPostId(string $objectType, string $objectId): ?int
|
||||
{
|
||||
if ($objectType === 'attachment' || ! ctype_digit($objectId)) {
|
||||
return null;
|
||||
}
|
||||
$type = get_post_type_object($objectType);
|
||||
if ($type === null || empty($type->public)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return get_post((int) $objectId) instanceof \WP_Post ? (int) $objectId : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use Closure;
|
||||
use LIT\MCP\Compatibility\ThrowawayPost;
|
||||
use LIT\MCP\Log;
|
||||
use WP_Post;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* Purge probe of the WP Fastest Cache check: a marked throwaway page gets a cache file where WPFC keeps the cache of
|
||||
* that page (cache/all/<path of its address>/index.html, WPFC's own getWpContentDir), WpFastestCache::
|
||||
* singleDeleteCache – the method behind wpfc_clear_post_cache_by_id, which FastestCacheListener calls – runs for it,
|
||||
* and the file must be gone (WPFC moves the directory to cache/tmpWpfc, which it empties itself). The probe also
|
||||
* checks that WPFC still hooks wpfc_clear_post_cache_by_id to that method: without the hook the public function does
|
||||
* nothing, silently. The page and the cache directory are always removed (ThrowawayPost); entries a dead check left
|
||||
* behind are deleted by removeOrphans(). The whole-cache purge (wpfc_clear_all_cache) is not probed: it would empty
|
||||
* the live cache of the site on every check. Runs only from the check route (Compatibility::check).
|
||||
*
|
||||
* The purge is narrowed to the page ($to_clear_parents = false; otherwise WPFC also empties the home page, author
|
||||
* page, sitemap, neighbours and term archives). NOT avoidable: WPFC still empties the two feed caches and purges the
|
||||
* external caches configured in WPFC (Varnish, Cloudflare) on every call; creating and deleting the page fire the
|
||||
* hooks of every other plugin (Divi 5 empties caches on insert and delete of a page).
|
||||
*
|
||||
* The page stays a draft; WPFC takes the address a draft would have once published. The draft gets a fixed slug
|
||||
* straight in the database, without hooks: an empty slug would make its address the home page.
|
||||
*
|
||||
* shortcut: needs a pretty permalink structure (a "?page_id=" address has no cache directory, nothing to probe then).
|
||||
*/
|
||||
final class FastestCacheProbe
|
||||
{
|
||||
private const SLUG_PREFIX = 'lit-mcp-check-';
|
||||
private const PURGE_HOOK = 'wpfc_clear_post_cache_by_id';
|
||||
|
||||
private const ABORTED = 'Fastest-Cache-Probe abgebrochen (Details im PHP-Error-Log).';
|
||||
private const NOT_HOOKED = 'WP Fastest Cache verarbeitet wpfc_clear_post_cache_by_id nicht mehr; das Leeren eines '
|
||||
. 'Beitrags bliebe wirkungslos.';
|
||||
private const NOT_PURGED = 'Die Testdatei im Cache blieb nach dem Leeren durch WP Fastest Cache bestehen.';
|
||||
private const NO_SLUG = 'Die Adresse der Testseite konnte nicht gesetzt werden (Details im PHP-Error-Log).';
|
||||
private const NOT_WRITTEN = 'Die Testdatei konnte nicht im Cache-Verzeichnis angelegt werden '
|
||||
. '(Details im PHP-Error-Log).';
|
||||
|
||||
private Closure $enabled;
|
||||
private Closure $hooked;
|
||||
private Closure $cacheDir;
|
||||
private Closure $purge;
|
||||
private Closure $setSlug;
|
||||
|
||||
/**
|
||||
* Defaults are the real WPFC and WordPress calls; closures only for tests.
|
||||
*
|
||||
* @param (Closure(): bool)|null $enabled WPFC caching switched on.
|
||||
* @param (Closure(): bool)|null $hooked WPFC hooks wpfc_clear_post_cache_by_id to singleDeleteCache.
|
||||
* @param (Closure(int): ?string)|null $cacheDir Cache directory (with trailing slash) of a page; null = none.
|
||||
* @param (Closure(int): void)|null $purge singleDeleteCache for this page only.
|
||||
* @param (Closure(int): bool)|null $setSlug Sets the probe slug without hooks; false = not changed.
|
||||
*/
|
||||
public function __construct(
|
||||
?Closure $enabled = null,
|
||||
?Closure $hooked = null,
|
||||
?Closure $cacheDir = null,
|
||||
?Closure $purge = null,
|
||||
?Closure $setSlug = null
|
||||
) {
|
||||
$this->enabled = $enabled ?? FastestCacheCompatibility::cacheEnabled(...);
|
||||
$this->hooked = $hooked ?? static fn (): bool
|
||||
=> has_action(self::PURGE_HOOK, [$GLOBALS['wp_fastest_cache'] ?? null, 'singleDeleteCache']) !== false;
|
||||
$this->cacheDir = $cacheDir ?? self::cacheDirFor(...);
|
||||
$this->purge = $purge ?? static function (int $id): void {
|
||||
$GLOBALS['wp_fastest_cache']->singleDeleteCache(false, $id, false);
|
||||
};
|
||||
$this->setSlug = $setSlug ?? self::writeSlug(...);
|
||||
}
|
||||
|
||||
/** @return list<string>|null German problems, [] = green; null = nothing to probe (cache off, no usable path). */
|
||||
public function run(): ?array
|
||||
{
|
||||
if (! ($this->enabled)()) {
|
||||
return null;
|
||||
}
|
||||
if (! ($this->hooked)()) {
|
||||
return [self::NOT_HOOKED];
|
||||
}
|
||||
|
||||
$unchecked = false;
|
||||
$problems = self::throwaway()->run('page', function (int $id) use (&$unchecked): array {
|
||||
if (! ($this->setSlug)($id)) {
|
||||
Log::line('wpfc probe: the database did not set the slug of page ' . $id);
|
||||
|
||||
return [self::NO_SLUG];
|
||||
}
|
||||
$dir = ($this->cacheDir)($id);
|
||||
if ($dir === null) {
|
||||
$unchecked = true;
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->exercise($id, $dir);
|
||||
});
|
||||
|
||||
return $unchecked && $problems === [] ? null : $problems;
|
||||
}
|
||||
|
||||
/** @return list<int> IDs of probe pages a dead check left behind, deleted now. */
|
||||
public static function removeOrphans(): array
|
||||
{
|
||||
return self::throwaway()->removeOrphans('page');
|
||||
}
|
||||
|
||||
private static function throwaway(): ThrowawayPost
|
||||
{
|
||||
return new ThrowawayPost(
|
||||
ThrowawayPost::MARKER,
|
||||
ThrowawayPost::TITLE,
|
||||
self::ABORTED,
|
||||
'Die Probe-Seite konnte nicht angelegt werden (Details im PHP-Error-Log).',
|
||||
'Die Probe-Seite %d konnte nicht gelöscht werden; bitte endgültig löschen (Titel „'
|
||||
. ThrowawayPost::TITLE . ' …“).',
|
||||
'wpfc probe'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* WPFC's cache directory of the probe page, computed the way singleDeleteCache does (the path of the published
|
||||
* address), or null when it is not exactly <path>/<probe slug>/: a plain "?page_id=" address, a path with "..".
|
||||
*/
|
||||
public static function cacheDirFor(int $postId): ?string
|
||||
{
|
||||
$post = get_post($postId);
|
||||
if (! $post instanceof WP_Post) {
|
||||
return null;
|
||||
}
|
||||
$published = clone $post;
|
||||
$published->post_status = 'publish';
|
||||
$address = urldecode((string) get_permalink($published));
|
||||
if (preg_match('#^https?://[^/]+/(.+)$#', $address, $match) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$path = trim($match[1], '/');
|
||||
$slug = self::SLUG_PREFIX . $postId;
|
||||
if (str_contains($path, '..') || ($path !== $slug && ! str_ends_with($path, '/' . $slug))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $GLOBALS['wp_fastest_cache']->getWpContentDir('/cache/all/') . $path . '/';
|
||||
}
|
||||
|
||||
// The probe's own file in WPFC's own cache directory, written the way WPFC does it (plain PHP, no WP_Filesystem).
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions
|
||||
|
||||
/** @return list<string> */
|
||||
private function exercise(int $id, string $dir): array
|
||||
{
|
||||
$file = $dir . 'index.html';
|
||||
try {
|
||||
if (! wp_mkdir_p($dir) || file_put_contents($file, '<!-- lit-mcp purge probe -->') === false) {
|
||||
Log::line('wpfc probe: could not write the test file ' . $file);
|
||||
|
||||
return [self::NOT_WRITTEN];
|
||||
}
|
||||
|
||||
($this->purge)($id);
|
||||
clearstatcache(true, $file);
|
||||
if (! file_exists($file)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
Log::line('wpfc probe: singleDeleteCache left the test file ' . $file . ' in place.');
|
||||
|
||||
return [self::NOT_PURGED];
|
||||
} finally {
|
||||
@unlink($file);
|
||||
@rmdir($dir);
|
||||
}
|
||||
}
|
||||
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions
|
||||
|
||||
/** A fixed slug (an empty one would make the page's address the home page) – no hooks, no clean_post_cache. */
|
||||
private static function writeSlug(int $id): bool
|
||||
{
|
||||
global $wpdb;
|
||||
|
||||
$rows = $wpdb->update($wpdb->posts, ['post_name' => self::SLUG_PREFIX . $id], ['ID' => $id]);
|
||||
wp_cache_delete($id, 'posts');
|
||||
|
||||
return $rows !== false && (int) $rows > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\FastestCache;
|
||||
|
||||
use Closure;
|
||||
use LIT\MCP\Log;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* The two purges of WP Fastest Cache, shared by FastestCacheListener (after every write) and lit/cache-clear: the
|
||||
* capability check, the 30 s throttle of the whole-cache purge with its one trailing purge (TRAILING_HOOK) and the
|
||||
* stamp (PURGED_AT). The state lives in the transient and the cron event, so any number of instances share it.
|
||||
*/
|
||||
final class FastestCachePurger
|
||||
{
|
||||
public const TRAILING_HOOK = 'lit_mcp_wpfc_trailing_purge';
|
||||
/** Transient with the time of the last whole-cache purge (also in Uninstaller). */
|
||||
public const PURGED_AT = 'lit_mcp_wpfc_purged_at';
|
||||
/** Seconds between two whole-cache purges. */
|
||||
private const THROTTLE = 30;
|
||||
|
||||
public const PURGED = 'purged';
|
||||
public const THROTTLED = 'throttled';
|
||||
public const LOCKED = 'locked';
|
||||
|
||||
private Closure $usable;
|
||||
private Closure $cacheEnabled;
|
||||
private Closure $purgePost;
|
||||
private Closure $purgeAll;
|
||||
private bool $warned = false;
|
||||
|
||||
/**
|
||||
* Defaults are the real WPFC functions; closures only for tests.
|
||||
*
|
||||
* @param Closure(FastestCacheFeature): bool $usable Compatibility::usable().
|
||||
* @param (Closure(): bool)|null $cacheEnabled WPFC caching switched on.
|
||||
* @param (Closure(int): void)|null $purgePost wpfc_clear_post_cache_by_id($postId).
|
||||
* @param (Closure(): void)|null $purgeAll wpfc_clear_all_cache().
|
||||
*/
|
||||
public function __construct(
|
||||
Closure $usable,
|
||||
?Closure $cacheEnabled = null,
|
||||
?Closure $purgePost = null,
|
||||
?Closure $purgeAll = null
|
||||
) {
|
||||
$this->usable = $usable;
|
||||
$this->cacheEnabled = $cacheEnabled ?? FastestCacheCompatibility::cacheEnabled(...);
|
||||
$this->purgePost = $purgePost ?? static function (int $id): void {
|
||||
wpfc_clear_post_cache_by_id($id);
|
||||
};
|
||||
$this->purgeAll = $purgeAll ?? static function (): void {
|
||||
wpfc_clear_all_cache();
|
||||
};
|
||||
}
|
||||
|
||||
public function cacheEnabled(): bool
|
||||
{
|
||||
return ($this->cacheEnabled)();
|
||||
}
|
||||
|
||||
/** Whether a whole-cache purge now would only be postponed. */
|
||||
public function throttled(): bool
|
||||
{
|
||||
return self::within($this->lastPurge());
|
||||
}
|
||||
|
||||
private static function within(?int $last): bool
|
||||
{
|
||||
return $last !== null && time() - $last < self::THROTTLE;
|
||||
}
|
||||
|
||||
/** Time of the last whole-cache purge; null = none within the lock time. Transients may come back as strings. */
|
||||
private function lastPurge(): ?int
|
||||
{
|
||||
$last = get_transient(self::PURGED_AT);
|
||||
|
||||
return is_numeric($last) ? (int) $last : null;
|
||||
}
|
||||
|
||||
/** wpfc_clear_post_cache_by_id for one post; false = locked. Never throttled. */
|
||||
public function post(int $postId): bool
|
||||
{
|
||||
if (! $this->allowed(FastestCacheFeature::PurgePost)) {
|
||||
return false;
|
||||
}
|
||||
($this->purgePost)($postId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole cache, at most every THROTTLE seconds. Inside the lock time one trailing purge is scheduled (cron events
|
||||
* are per site: the callback runs on this blog).
|
||||
*
|
||||
* @return self::PURGED|self::THROTTLED|self::LOCKED
|
||||
*/
|
||||
public function everything(): string
|
||||
{
|
||||
if (! $this->allowed(FastestCacheFeature::PurgeAll)) {
|
||||
return self::LOCKED;
|
||||
}
|
||||
|
||||
$last = $this->lastPurge();
|
||||
if ($last !== null && self::within($last)) {
|
||||
if (wp_next_scheduled(self::TRAILING_HOOK) === false) {
|
||||
wp_schedule_single_event($last + self::THROTTLE, self::TRAILING_HOOK);
|
||||
}
|
||||
|
||||
return self::THROTTLED;
|
||||
}
|
||||
|
||||
($this->purgeAll)();
|
||||
set_transient(self::PURGED_AT, time(), self::THROTTLE);
|
||||
|
||||
return self::PURGED;
|
||||
}
|
||||
|
||||
private function allowed(FastestCacheFeature $feature): bool
|
||||
{
|
||||
if (($this->usable)($feature)) {
|
||||
return true;
|
||||
}
|
||||
if (! $this->warned) {
|
||||
$this->warned = true;
|
||||
Log::line(sprintf('WP Fastest Cache not purged: %s not usable (see tab Compatibility)', $feature->id()));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user