feat(cache): Tool lit/cache-clear zum gezielten Leeren des Caches

lit/cache-clear leert den Seiten-Cache von WP Super Cache für die ganze Website (scope all, Recht manage_options) oder einen Beitrag (scope post, Recht edit_post); Probelauf ohne confirm, Ausführen mit confirm: true. Das CapabilityGate sperrt das Tool, wenn WP Super Cache bricht; eine Sperre zur Laufzeit wird als Fehler gemeldet. Listener und Tool teilen die 30-s-Drosselung mit Nachlauf (SuperCachePurger); der Listener ignoriert die Einträge des Tools. Behoben vor dem Commit: die Verdrahtung des Purgers erfasste die Registry zu früh (immer gesperrt), jetzt per Referenz und mit Test über Plugin::integrations().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan-Niclas Loosen
2026-11-06 19:05:21 +01:00
co-authored by Claude Opus 5.5
parent d3e5d4fac0
commit 1ac347e76f
12 changed files with 883 additions and 86 deletions
+41
View File
@@ -295,6 +295,47 @@ cache_file_gone || fail "the trailing purge did not empty the cache"
[ "$(wp transient get "$PURGED_AT")" -gt "$LAST" ] || fail "the trailing purge must store a new purge time"
pass "trailing purge by cron: cache emptied, event gone, purge time renewed"
# 8b. lit/cache-clear: the dry run changes nothing, confirm empties the post's page / the whole cache
fill_cache
for ARGS in "{\"scope\":\"post\",\"post_id\":$POST_ID}" '{"scope":"all"}'; do
DRY=$(ability lit/cache-clear "$ARGS")
[ "$(error_code "$DRY")" = confirm_required ] || fail "lit/cache-clear dry run $ARGS must ask for confirm: $DRY"
echo "$DRY" | jq -e '(.__error | fromjson | .cache_enabled) == true' >/dev/null || fail "dry run must report the cache as on: $DRY"
done
sleep 2
cache_file_exists || fail "the dry runs of lit/cache-clear emptied the cache"
[ "$(event_count)" = 0 ] || fail "a dry run must not schedule anything"
pass "lit/cache-clear without confirm: asks for confirmation, reports the cache as on, cache file stays"
CLEARED=$(ability lit/cache-clear "{\"scope\":\"post\",\"post_id\":$POST_ID,\"confirm\":true}")
echo "$CLEARED" | jq -e '.ok == true and .outcome == "purged" and .log_id != null' >/dev/null || fail "lit/cache-clear post: $CLEARED"
wait_for "the cache file of the post is gone after lit/cache-clear scope post" cache_file_gone
[ "$(event_count)" = 0 ] || fail "a single-post purge must not schedule a trailing purge"
pass "lit/cache-clear scope post with confirm: the page of the post is emptied"
# The whole-cache purge needs the lock time of the earlier steps to be over.
WAIT=$(($(wp transient get "$PURGED_AT") + 32 - $(date +%s))); [ "$WAIT" -gt 0 ] && sleep "$WAIT"
fill_cache
CLEARED=$(ability lit/cache-clear '{"scope":"all","confirm":true}')
echo "$CLEARED" | jq -e '.ok == true and .outcome == "purged" and .log_id != null' >/dev/null || fail "lit/cache-clear all: $CLEARED"
wait_for "the cache is empty after lit/cache-clear scope all" cache_file_gone
sleep 2
# Its own change log entry must not purge a second time (that would be throttled and leave a trailing event).
[ "$(event_count)" = 0 ] || fail "the change log entry of lit/cache-clear triggered a second purge"
LAST=$(wp transient get "$PURGED_AT")
pass "lit/cache-clear scope all with confirm: whole cache emptied once, own log entry purges nothing"
fill_cache
THROTTLED=$(ability lit/cache-clear '{"scope":"all","confirm":true}')
echo "$THROTTLED" | jq -e '.ok == true and .outcome == "throttled"' >/dev/null || fail "lit/cache-clear all inside the lock time: $THROTTLED"
[ "$(event_count)" = 1 ] || fail "a throttled lit/cache-clear must schedule exactly one trailing purge"
cache_file_exists || fail "throttled: the cache file must stay"
[ "$(wp transient get "$PURGED_AT")" = "$LAST" ] || fail "a throttled purge must not move the purge time"
WAIT=$((LAST + 32 - $(date +%s))); [ "$WAIT" -gt 0 ] && sleep "$WAIT"
wp cron event run "$TRAILING_HOOK" >/dev/null 2>&1 || fail "wp cron event run $TRAILING_HOOK"
cache_file_gone || fail "the trailing purge did not empty the cache"
pass "lit/cache-clear scope all inside 30 s: throttled, one trailing event, cron run empties the cache"
# 9. Everything back as before (the EXIT trap would do it too; here it is part of the verdict)
restore
verify_restored || fail "the state before the run was not restored"
@@ -0,0 +1,288 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\SuperCache;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Annotations;
use LIT\MCP\Abilities\DeclaresRequirements;
use LIT\MCP\Integrations\SuperCache\CacheClearAbility;
use LIT\MCP\Integrations\SuperCache\SuperCacheFeature;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Support\FakeChangeLog;
use LIT\MCP\Tests\Unit\TestCase;
use WP_Error;
use WP_Post;
final class CacheClearAbilityTest extends TestCase
{
/** @var list<string> */
private array $purges = [];
/** @var list<string> */
private array $scheduled = [];
private int|false $lastPurge = false;
protected function setUp(): void
{
parent::setUp();
$this->purges = [];
$this->scheduled = [];
$this->lastPurge = false;
Functions\when('is_multisite')->justReturn(false);
Functions\when('get_transient')->alias(fn (): int|false => $this->lastPurge);
Functions\when('set_transient')->justReturn(true);
Functions\when('wp_next_scheduled')->justReturn(false);
Functions\when('wp_schedule_single_event')->alias(function (int $at, string $hook): bool {
$this->scheduled[] = $hook;
return true;
});
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_post')->alias(
static fn (int $id): ?WP_Post => $id === 7
? new WP_Post(['ID' => 7, 'post_type' => 'page', 'post_title' => 'Start', 'post_status' => 'publish'])
: ($id === 8
? new WP_Post(['ID' => 8, 'post_type' => 'page', 'post_title' => 'Idee', 'post_status' => 'draft'])
: null)
);
}
protected function tearDown(): void
{
unset($GLOBALS['cache_enabled']);
parent::tearDown();
}
private function ability(?FakeChangeLog $log = null, bool $cacheOn = true, bool $usable = true): CacheClearAbility
{
$purger = new SuperCachePurger(
static fn (SuperCacheFeature $feature): bool => $usable,
static fn (): bool => $cacheOn,
function (int $id): void {
$this->purges[] = 'post:' . $id;
},
function (int $blog): void {
$this->purges[] = 'all:' . $blog;
}
);
return new CacheClearAbility($purger, $log ?? FakeChangeLog::forbidden());
}
public function testDescribesItselfLikeAGuardedWriteTool(): void
{
$ability = $this->ability();
self::assertInstanceOf(Ability::class, $ability);
self::assertSame('lit/cache-clear', $ability->name());
self::assertFalse($ability->isDirect());
self::assertSame(Annotations::write(true), $ability->annotations());
self::assertStringContainsString('confirm: true', $ability->description());
self::assertStringContainsString('WP Super Cache', $ability->description());
$schema = $ability->inputSchema();
self::assertSame(['scope'], $schema['required']);
self::assertFalse($schema['additionalProperties']);
self::assertSame(['all', 'post'], $schema['properties']['scope']['enum']);
self::assertSame(['scope', 'post_id', 'confirm'], array_keys($schema['properties']));
self::assertArrayHasKey('outcome', $ability->outputSchema()['properties']);
}
public function testDeclaresTheCapabilityOfTheScope(): void
{
$ability = $this->ability();
self::assertInstanceOf(DeclaresRequirements::class, $ability);
self::assertSame(['wpsc-purge-all'], $ability->requirements(['scope' => 'all']));
self::assertSame(['wpsc-purge-post'], $ability->requirements(['scope' => 'post', 'post_id' => 7]));
self::assertSame([], $ability->requirements(['scope' => 'x']));
self::assertSame([], $ability->requirements([]));
}
public function testAllNeedsManageOptions(): void
{
$asked = [];
Functions\when('current_user_can')->alias(function (string $cap) use (&$asked): bool {
$asked[] = $cap;
return false;
});
self::assertToolError($this->ability()->permission(['scope' => 'all']), 'forbidden');
self::assertSame(['manage_options'], $asked);
Functions\when('current_user_can')->justReturn(true);
self::assertTrue($this->ability()->permission(['scope' => 'all']));
}
public function testPostNeedsEditPostForThatId(): void
{
$asked = [];
Functions\when('current_user_can')->alias(function (string $cap, int $id) use (&$asked): bool {
$asked[] = [$cap, $id];
return false;
});
self::assertToolError($this->ability()->permission(['scope' => 'post', 'post_id' => 7]), 'forbidden');
self::assertSame([['edit_post', 7]], $asked);
Functions\when('current_user_can')->justReturn(true);
self::assertTrue($this->ability()->permission(['scope' => 'post', 'post_id' => 7]));
}
public function testAnUnknownPostIsNotFound(): void
{
self::assertToolError($this->ability()->permission(['scope' => 'post', 'post_id' => 99]), 'not_found');
self::assertToolError($this->ability()->execute(['scope' => 'post', 'post_id' => 99, 'confirm' => true]), 'not_found');
self::assertSame([], $this->purges);
}
/** @return array<string, array{array<string, mixed>}> */
public static function invalidInputs(): array
{
return [
'no scope' => [[]],
'unknown scope' => [['scope' => 'site']],
'post without id' => [['scope' => 'post']],
'post with zero' => [['scope' => 'post', 'post_id' => 0]],
'post with text' => [['scope' => 'post', 'post_id' => 'abc']],
];
}
/**
* @dataProvider invalidInputs
* @param array<string, mixed> $input
*/
public function testInvalidInputIsRefusedWithoutEffect(array $input): void
{
self::assertToolError($this->ability()->permission($input), 'validation_failed');
self::assertToolError($this->ability()->execute($input + ['confirm' => true]), 'validation_failed');
self::assertSame([], $this->purges);
}
public function testTheDryRunClearsNothingAndReportsTheState(): void
{
$GLOBALS['cache_enabled'] = true;
$this->lastPurge = time() - 5;
$payload = self::assertToolError($this->ability()->execute(['scope' => 'all']), 'confirm_required');
self::assertSame([], $this->purges);
self::assertSame([], $this->scheduled);
self::assertSame('all', $payload['scope']);
self::assertTrue($payload['cache_enabled']);
self::assertTrue($payload['throttled']);
self::assertStringContainsString('Probelauf', $payload['message']);
}
public function testTheDryRunOfAPostNamesThePostAndIgnoresAConfirmThatIsNotTrue(): void
{
$payload = self::assertToolError(
$this->ability(cacheOn: false)->execute(['scope' => 'post', 'post_id' => 7, 'confirm' => 'true']),
'confirm_required'
);
self::assertSame([], $this->purges);
self::assertSame(7, $payload['post_id']);
self::assertFalse($payload['cache_enabled']);
self::assertStringContainsString('Start', $payload['message']);
self::assertStringContainsString('ausgeschaltet', $payload['message']);
}
public function testConfirmClearsThePageOfThePostAndLogsIt(): void
{
$log = new FakeChangeLog(4);
$result = $this->ability($log)->execute(['scope' => 'post', 'post_id' => 7, 'confirm' => true]);
self::assertSame(['post:7'], $this->purges);
self::assertTrue($result['ok']);
self::assertSame('purged', $result['outcome']);
self::assertSame(4, $result['log_id']);
$log->assertRecorded(['ability' => 'lit/cache-clear', 'object_type' => 'wpsc', 'object_id' => '7']);
}
public function testADraftHasNothingToClear(): void
{
$GLOBALS['cache_enabled'] = true;
$result = $this->ability()->execute(['scope' => 'post', 'post_id' => 8, 'confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame('nothing', $result['outcome']);
self::assertStringContainsString('Entwurf', $result['summary']);
}
public function testConfirmClearsTheWholeCacheAtOnce(): void
{
$log = new FakeChangeLog(1);
$result = $this->ability($log)->execute(['scope' => 'all', 'confirm' => true]);
self::assertSame(['all:0'], $this->purges);
self::assertSame('purged', $result['outcome']);
$log->assertRecorded(['ability' => 'lit/cache-clear', 'object_type' => 'wpsc', 'object_id' => 'all']);
}
public function testAWholePurgeInsideTheLockTimeIsThrottledWithATrailingPurge(): void
{
$this->lastPurge = time() - 5;
$result = $this->ability(new FakeChangeLog(1))->execute(['scope' => 'all', 'confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame([SuperCachePurger::TRAILING_HOOK], $this->scheduled);
self::assertSame('throttled', $result['outcome']);
self::assertStringContainsString('Nachlauf', $result['summary']);
}
/** @return array<string, array{array<string, mixed>}> */
public static function scopes(): array
{
return ['all' => [['scope' => 'all']], 'post' => [['scope' => 'post', 'post_id' => 7]]];
}
/**
* @dataProvider scopes
* @param array<string, mixed> $input
*/
public function testWithTheCacheOffNothingHappensAndNothingIsLogged(array $input): void
{
$result = $this->ability(FakeChangeLog::forbidden(), cacheOn: false)->execute($input + ['confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame('cache_off', $result['outcome']);
self::assertNull($result['log_id']);
}
/**
* @dataProvider confirmedScopes
* @param array<string, mixed> $input
*/
public function testALockedPurgeIsReportedAsAnErrorAndNeitherPurgesNorLogs(array $input): void
{
$previous = ini_set('error_log', '/dev/null');
$result = $this->ability(FakeChangeLog::forbidden(), usable: false)->execute($input);
ini_set('error_log', (string) $previous);
self::assertInstanceOf(WP_Error::class, $result);
self::assertSame('lit_compat_incompatible', $result->get_error_code());
self::assertStringContainsString(
'WP Super Cache ist gesperrt (siehe Reiter Kompatibilität). Es wurde nichts geleert.',
$result->get_error_message()
);
self::assertSame([], $this->purges);
}
/** @return array<string, array{array<string, mixed>}> */
public static function confirmedScopes(): array
{
return [
'all' => [['scope' => 'all', 'confirm' => true]],
'post' => [['scope' => 'post', 'post_id' => 7, 'confirm' => true]],
];
}
}
@@ -11,30 +11,37 @@ use LIT\MCP\Integrations\Bootable;
use LIT\MCP\Integrations\Integration;
use LIT\MCP\Integrations\SuperCache\SuperCacheCompatibility;
use LIT\MCP\Integrations\SuperCache\SuperCacheIntegration;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Support\FakeChangeLog;
use LIT\MCP\Tests\Unit\TestCase;
final class SuperCacheIntegrationTest extends TestCase
{
public function testIsAnIntegrationWithoutAbilitiesThatProvidesItsProfile(): void
private static function purger(): SuperCachePurger
{
$integration = new SuperCacheIntegration();
return new SuperCachePurger(static fn (): bool => true);
}
public function testIsAnIntegrationThatProvidesItsProfileAndTheCacheClearTool(): void
{
$integration = new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden());
self::assertInstanceOf(Integration::class, $integration);
self::assertInstanceOf(ProvidesCompatibility::class, $integration);
self::assertSame('wpsc', $integration->id());
self::assertSame('WP Super Cache', $integration->label());
self::assertSame([], $integration->abilities());
self::assertEquals(['lit/cache-clear'], array_map(static fn ($a): string => $a->name(), $integration->abilities()));
self::assertEquals([SuperCacheCompatibility::profile()], $integration->compatibilities());
}
public function testIsAvailableOnlyWithSuperCache(): void
{
self::assertSame(defined('WPCACHEHOME'), (new SuperCacheIntegration())->isAvailable());
self::assertSame(defined('WPCACHEHOME'), (new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden()))->isAvailable());
}
public function testBootHooksTheOrphanCleanupIntoTheProfileLoad(): void
{
$integration = new SuperCacheIntegration();
$integration = new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden());
$integration->boot();
self::assertInstanceOf(Bootable::class, $integration);
@@ -45,11 +52,11 @@ final class SuperCacheIntegrationTest extends TestCase
{
Functions\expect('get_posts')->never();
Functions\when('current_user_can')->justReturn(true);
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('pods');
(new SuperCacheIntegration(static fn (): bool => false))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('pods');
(new SuperCacheIntegration(static fn (): bool => false, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
Functions\when('current_user_can')->justReturn(false);
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
$this->addToAssertionCount(1);
}
@@ -63,6 +70,6 @@ final class SuperCacheIntegrationTest extends TestCase
return [];
});
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
}
}
@@ -200,6 +200,18 @@ final class SuperCacheListenerTest extends TestCase
self::assertSame([], $this->purges);
}
/** lit/cache-clear purges itself; its change log entry must not trigger a second purge. */
public function testTheCacheClearToolsOwnEntriesPurgeNothing(): void
{
$listener = $this->listener();
$listener->onChange('lit/cache-clear', 'wpsc', 'all', 1);
$listener->onChange('lit/cache-clear', 'wpsc', '12', 2);
$listener->flush();
self::assertSame([], $this->purges);
self::assertFalse(has_action('shutdown', [$listener, 'flush']));
}
public function testNothingHappensWhileTheCacheIsOff(): void
{
$listener = $this->listener(cacheOn: false);
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\SuperCache;
use Brain\Monkey\Functions;
use LIT\MCP\Integrations\SuperCache\SuperCacheFeature;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Unit\TestCase;
final class SuperCachePurgerTest extends TestCase
{
public function testALockedWholePurgeDoesNothingAndSaysSo(): void
{
$previous = ini_set('error_log', '/dev/null');
Functions\expect('get_transient')->never();
$purger = new SuperCachePurger(
static fn (SuperCacheFeature $feature): bool => false,
static fn (): bool => true,
static fn (int $id) => self::fail('no post purge'),
static fn (int $blog) => self::fail('no whole purge')
);
self::assertSame(SuperCachePurger::LOCKED, $purger->everything());
self::assertFalse($purger->post(3));
ini_set('error_log', (string) $previous);
}
public function testThrottledReadsTheStamp(): void
{
$stamp = false;
Functions\when('get_transient')->alias(static function () use (&$stamp) {
return $stamp;
});
$purger = new SuperCachePurger(static fn (): bool => true);
self::assertFalse($purger->throttled());
$stamp = (string) (time() - 5);
self::assertTrue($purger->throttled());
$stamp = time() - 31;
self::assertFalse($purger->throttled());
}
/** The stamp is read once: a transient expiring between two reads must not schedule the trailing purge in 1970. */
public function testEverythingReadsTheStampOnceAndSchedulesTheTrailingPurgeInTheFuture(): void
{
$reads = 0;
$scheduledAt = [];
Functions\when('get_transient')->alias(static function () use (&$reads) {
return ++$reads === 1 ? time() - 5 : false;
});
Functions\when('wp_next_scheduled')->justReturn(false);
Functions\when('wp_schedule_single_event')->alias(static function (int $at) use (&$scheduledAt): bool {
$scheduledAt[] = $at;
return true;
});
$purger = new SuperCachePurger(static fn (): bool => true);
self::assertSame(SuperCachePurger::THROTTLED, $purger->everything());
self::assertSame(1, $reads);
self::assertCount(1, $scheduledAt);
self::assertGreaterThanOrEqual(time(), $scheduledAt[0]);
}
}
+41 -5
View File
@@ -34,11 +34,13 @@ use Mockery;
/** The wiring of the composition root: Plugin::integrations() and the steps Plugin::boot() takes with it. */
final class PluginTest extends TestCase
{
private static function registry(ToolAvailability $tools = new ToolAvailability()): IntegrationRegistry
{
private static function registry(
ToolAvailability $tools = new ToolAvailability(),
?FakeChangeLog $log = null
): IntegrationRegistry {
return Plugin::integrations(
Mockery::mock(ContentSchema::class),
FakeChangeLog::forbidden(),
$log ?? FakeChangeLog::forbidden(),
new Limits(),
$tools
);
@@ -95,8 +97,8 @@ final class PluginTest extends TestCase
self::assertArrayNotHasKey('pods', $registry->grouped());
}
/** WP Super Cache has no tools either: registered for its profile only. */
public function testSuperCacheIsRegisteredWithoutBecomingAToolGroup(): void
/** WP Super Cache is registered with its profile; its tool group appears only while the plugin is loaded. */
public function testSuperCacheIsRegisteredAndNoToolGroupWithoutTheCachePlugin(): void
{
$registry = self::registry();
@@ -104,6 +106,40 @@ final class PluginTest extends TestCase
self::assertArrayNotHasKey('wpsc', $registry->grouped());
}
/**
* The purger of the real wiring asks the registry's Compatibility at call time: with WP Super Cache loaded and
* its manifest met, the whole-cache purge runs (a registry captured by value would still be null: always locked).
*
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testTheWiredPurgerAsksTheCompatibilityOfTheRegistry(): void
{
define('WPCACHEHOME', '/plugins/wp-super-cache/');
eval('function wp_cache_post_edit($id) { $GLOBALS["wpsc_calls"][] = "post:" . $id; }'
. 'function wp_cache_clear_cache($blog = 0) { $GLOBALS["wpsc_calls"][] = "all:" . $blog; }');
$GLOBALS['wpsc_calls'] = [];
$GLOBALS['cache_path'] = '/cache/';
$GLOBALS['blog_cache_dir'] = '/cache/blogs/';
$GLOBALS['cache_enabled'] = true;
Functions\when('get_file_data')->justReturn(['Version' => '3.1.5']);
Functions\when('get_option')->justReturn(false);
Functions\when('get_transient')->justReturn(false);
Functions\when('set_transient')->justReturn(true);
Functions\when('is_multisite')->justReturn(false);
Functions\when('current_user_can')->justReturn(true);
$integrations = (new ReflectionProperty(IntegrationRegistry::class, 'integrations'))->getValue(self::registry(log: new FakeChangeLog(1)));
$wpsc = array_values(array_filter(
$integrations,
static fn ($integration): bool => $integration->id() === 'wpsc'
))[0];
$result = $wpsc->abilities()[0]->execute(['scope' => 'all', 'confirm' => true]);
self::assertSame('purged', $result['outcome']);
self::assertSame(['all:0'], $GLOBALS['wpsc_calls']);
}
/** lit-site-status keeps its order: Divi, Pods, WP Super Cache, The Events Calendar. */
public function testSiteStatusListsDiviPodsSuperCacheAndTheEventsCalendarInThatOrder(): void
{