Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- The drop-in no longer stops the whole site when the Composer autoloader it names exists but the web server cannot open it: it tested `is_file()` and then `require_once` failed with a fatal error. It tests `is_readable()`, stays inert, and WordPress keeps its own cache.

### Added

- The drop-in says in the PHP error log, by path, when the autoloader it names cannot be read by the web server (for example a package installed with `wp package install`, which lands in the home directory of the user who ran it). Until now the cache stayed off without a word.
- `status` (`wp object-cache status`, `pollora:object-cache:status`) has an `Autoloader` line: the path, or that there is none, and whether this user can read it. A path in the home directory of the user who runs the command is flagged, since the web server usually cannot read it, and an autoloader that cannot be read makes `status` fail. `status` cannot test the web server's own account.

## [0.3.0] - 2026-11-24

### Changed
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ The package needs PHP and phpredis, nothing else: it runs on a classic WordPress
```bash
composer require pollora/object-cache
wp object-cache enable # writes object-cache.php in the content directory
wp object-cache status # drop-in, phpredis, Redis, key prefix
wp object-cache status # drop-in, phpredis, Redis, autoloader, key prefix
wp object-cache flush # empties this site's keys, nothing else
wp object-cache disable # removes the drop-in
```

`enable` and `disable` are idempotent. They only touch a drop-in this package wrote: another object cache's `object-cache.php` is left alone, and `enable --force` replaces it. A drop-in from an older version is updated by running `enable` again. The drop-in carries the path of the site's `vendor/autoload.php`, so a WordPress that does not load Composer's autoloader itself can still find the package.
`enable` and `disable` are idempotent. They only touch a drop-in this package wrote: another object cache's `object-cache.php` is left alone, and `enable --force` replaces it. A drop-in from an older version is updated by running `enable` again. The drop-in carries the path of the site's `vendor/autoload.php`, so a WordPress that does not load Composer's autoloader itself can still find the package. The web server must be able to read that path: a package installed with `wp package install` lands in the home directory of the user who ran it, which a web request usually cannot open. The drop-in then stays inert, WordPress keeps its own cache, and the PHP error log says so; `status` shows the path and flags one in the home directory.

If phpredis is not loaded, or nothing configures the cache, the drop-in defines nothing and WordPress runs on its own in-memory cache, with no error. If Redis stops answering during a request, the request carries on from its request cache, stops asking Redis, and the failure goes to the PHP error log once.

Expand Down
10 changes: 8 additions & 2 deletions resources/drop-in/object-cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@
use Pollora\ObjectCache\Infrastructure\WordPress\DropIn;

// Written by the installer: the Composer autoloader of the site, for a WordPress that has not loaded it yet.
// Readable, not just a file: a file the web server may not open would otherwise stop the whole site with a fatal error.
$pollora_object_cache_autoload = '__POLLORA_OBJECT_CACHE_AUTOLOAD__';

if (! class_exists(DropIn::class, false) && is_file($pollora_object_cache_autoload)) {
require_once $pollora_object_cache_autoload;
if (! class_exists(DropIn::class, false) && $pollora_object_cache_autoload !== '') {
if (is_readable($pollora_object_cache_autoload)) {
require_once $pollora_object_cache_autoload;
} else {
// Not silent: the cache stays off, and this is the only place that can say why (`wp object-cache status` runs as another user).
error_log('Pollora object cache: the Composer autoloader '.$pollora_object_cache_autoload.' cannot be read by the web server, so WordPress keeps its own in-memory cache. Run `wp object-cache enable` again, or make the path readable.');
}
}

unset($pollora_object_cache_autoload);
Expand Down
31 changes: 30 additions & 1 deletion src/Infrastructure/Management/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,45 @@ public function status(?Settings $settings): StatusReport
$dropIn = $this->installer->status();
$extension = extension_loaded('redis');
$redis = $settings instanceof Settings ? $this->redis($settings, $extension) : 'not configured: define WP_OBJECT_CACHE_CONFIG';
$autoload = $this->installer->autoload();
$reachable = $autoload === '' || is_readable($autoload);

return new StatusReport([
'Drop-in' => $dropIn->value.' ('.$this->installer->target().')',
'phpredis' => $extension ? 'loaded' : 'missing',
'Autoloader' => $this->autoloadLine($autoload, $reachable),
'Redis' => $redis,
'Key prefix' => $settings instanceof Settings ? EngineBuilder::prefix($settings, $this->environment) : '-',
'Serializer' => $settings instanceof Settings ? $settings->serializer : '-',
'Prefetch' => $settings instanceof Settings && $settings->prefetchEnabled ? 'on' : 'off',
'Used by this process' => ($GLOBALS['wp_object_cache'] ?? null) instanceof WordPressObjectCache ? 'yes' : 'no',
], $dropIn === DropInStatus::Current && $extension && str_starts_with($redis, 'reachable'));
], $dropIn === DropInStatus::Current && $extension && $reachable && str_starts_with($redis, 'reachable'));
}

/**
* What `status` says of the autoloader the drop-in loads.
*
* Only this user can be asked whether the path is readable. A path under the home directory of
* the user who runs the command (where `wp package install` puts a package) is flagged,
* because the web server usually cannot read it, and the cache then stays off without an error.
*/
private function autoloadLine(string $autoload, bool $reachable): string
{
if ($autoload === '') {
return 'none (WordPress must load the package itself)';
}

if (! $reachable) {
return $autoload.' (not readable by this user)';
}

$home = $this->environment->server['HOME'] ?? null;

if (is_string($home) && $home !== '' && str_starts_with($autoload, rtrim($home, '/').'/')) {
return $autoload.' (in the home directory: the web server must be able to read it, or the cache stays off without an error)';
}

return $autoload;
}

private function redis(Settings $settings, bool $extension): string
Expand Down
8 changes: 8 additions & 0 deletions src/Infrastructure/WordPress/DropInInstaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ public function uninstall(): DropInStatus
return $before;
}

/**
* The path of the Composer autoloader the drop-in loads, or an empty string when it names none.
*/
public function autoload(): string
{
return $this->autoload;
}

/**
* The drop-in as it is written: the shipped file, with the path of the autoloader.
*/
Expand Down
89 changes: 86 additions & 3 deletions tests/Unit/DropInFileTest.php
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
<?php

declare(strict_types=1);
use Pollora\ObjectCache\Infrastructure\WordPress\DropInInstaller;

/*
* The drop-in file, loaded the way WordPress loads it: in a PHP process of its
* own, where nothing has defined a wp_cache_* function.
*/
function runDropIn(string $mode, bool $withExtensions): array
function runDropIn(string $mode, bool $withExtensions, ?string $dropIn = null, ?string $errorLog = null): array
{
$root = dirname(__DIR__, 2);
$command = sprintf(
'%s %s %s %s %s %s',
'%s %s %s %s %s %s %s',
escapeshellarg(PHP_BINARY),
$withExtensions ? '' : '-n',
$errorLog === null ? '' : '-d '.escapeshellarg('error_log='.$errorLog),
escapeshellarg($root.'/tests/Support/dropin-runner.php'),
escapeshellarg($root),
escapeshellarg($root.'/resources/drop-in/object-cache.php'),
escapeshellarg($dropIn ?? $root.'/resources/drop-in/object-cache.php'),
$mode,
);

Expand Down Expand Up @@ -63,3 +65,84 @@ function runDropIn(string $mode, bool $withExtensions): array
it('carries the marker the installer recognises it by', function (): void {
expect(file_get_contents(dirname(__DIR__, 2).'/resources/drop-in/object-cache.php'))->toContain('Pollora-Object-Cache-Drop-In: 2');
});

it('stays inert, instead of stopping the site, when the autoloader it names cannot be read', function (): void {
if (! extension_loaded('redis')) {
$this->markTestSkipped('phpredis is not loaded.');
}

$dir = sys_get_temp_dir().'/dropin-unreadable-'.bin2hex(random_bytes(4));
mkdir($dir);
$autoload = $dir.'/autoload.php';
file_put_contents($autoload, '<?php throw new RuntimeException("must not be loaded");');
chmod($autoload, 0000);

try {
if (is_readable($autoload) || (function_exists('posix_geteuid') && posix_geteuid() === 0)) {
$this->markTestSkipped('This user can read any file (root): the case cannot be set up.');
}

$root = dirname(__DIR__, 2);
(new DropInInstaller($root.'/resources/drop-in/object-cache.php', $dir.'/object-cache.php', $autoload))->install();

expect(runDropIn('load', withExtensions: true, dropIn: $dir.'/object-cache.php'))->toBe(['init' => false]);
} finally {
chmod($autoload, 0600);
unlink($autoload);

if (is_file($dir.'/object-cache.php')) {
unlink($dir.'/object-cache.php');
}

rmdir($dir);
}
});

/**
* What the drop-in says in the error log when it names the given autoloader (null: names none).
*
* @return array{result: array<string, mixed>, log: string}
*/
function dropInNaming(?string $autoload): array
{
$dir = sys_get_temp_dir().'/dropin-log-'.bin2hex(random_bytes(4));
mkdir($dir);
$root = dirname(__DIR__, 2);
(new DropInInstaller($root.'/resources/drop-in/object-cache.php', $dir.'/object-cache.php', $autoload ?? ''))->install();
$result = runDropIn('load', withExtensions: true, dropIn: $dir.'/object-cache.php', errorLog: $dir.'/php.log');
$log = is_file($dir.'/php.log') ? (string) file_get_contents($dir.'/php.log') : '';

foreach (glob($dir.'/*') ?: [] as $file) {
unlink($file);
}

rmdir($dir);

return ['result' => $result, 'log' => $log];
}

it('says in the error log, once and by name, that the autoloader it names cannot be read', function (): void {
if (! extension_loaded('redis')) {
$this->markTestSkipped('phpredis is not loaded.');
}

$said = dropInNaming('/no/such/home/vendor/autoload.php');

expect($said['result'])->toBe(['init' => false])
->and($said['log'])->toContain('Pollora object cache: the Composer autoloader /no/such/home/vendor/autoload.php cannot be read by the web server')
->and($said['log'])->toContain('wp object-cache enable')
->and(substr_count($said['log'], 'Pollora object cache'))->toBe(1);
});

it('says nothing when the autoloader is readable, or when the drop-in names none', function (): void {
if (! extension_loaded('redis')) {
$this->markTestSkipped('phpredis is not loaded.');
}

$readable = dropInNaming(dirname(__DIR__, 2).'/vendor/autoload.php');
$none = dropInNaming(null);

expect($readable['log'])->toBe('')
->and($none['log'])->toBe('')
->and($none['result'])->toBe(['init' => false]);
});
5 changes: 5 additions & 0 deletions tests/Unit/DropInInstallerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,8 @@

expect(file_get_contents($this->target))->toContain("\$a = '';");
});

it('tells the autoloader path it writes, empty when it has none', function (): void {
expect((new DropInInstaller($this->source, $this->target, '/srv/site/vendor/autoload.php'))->autoload())->toBe('/srv/site/vendor/autoload.php')
->and((new DropInInstaller($this->source, $this->target))->autoload())->toBe('');
});
52 changes: 52 additions & 0 deletions tests/Unit/ManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,58 @@ function liveSettings(): Settings
expect($this->manager->flush($dead))->toBeFalse();
});

/**
* A manager whose drop-in names the given autoloader, in an environment of the given home directory.
*/
function managerWithAutoload(string $dir, string $source, string $autoload, ?string $home = null): Manager
{
return new Manager(new DropInInstaller($source, $dir.'/object-cache.php', $autoload), Environments::make(server: $home === null ? [] : ['HOME' => $home]));
}

it('says there is no autoloader to load when the drop-in names none', function (): void {
$report = $this->manager->status(null);

expect($report->lines['Autoloader'])->toBe('none (WordPress must load the package itself)');
});

it('names a readable autoloader, and does not blame a home directory it is not in', function (): void {
$autoload = $this->dir.'/vendor/autoload.php';
mkdir($this->dir.'/vendor');
file_put_contents($autoload, '<?php');
$elsewhere = managerWithAutoload($this->dir, $this->source, $autoload, '/home/someone-else');
$nowhere = managerWithAutoload($this->dir, $this->source, $autoload);

expect($elsewhere->status(null)->lines['Autoloader'])->toBe($autoload)
->and($nowhere->status(null)->lines['Autoloader'])->toBe($autoload)
->and(managerWithAutoload($this->dir, $this->source, $autoload, '')->status(null)->lines['Autoloader'])->toBe($autoload);
});

it('warns about an autoloader in the home directory, where the web server usually cannot read', function (): void {
$autoload = $this->dir.'/home/vendor/autoload.php';
mkdir($this->dir.'/home/vendor', 0777, true);
file_put_contents($autoload, '<?php');

$inHome = managerWithAutoload($this->dir, $this->source, $autoload, $this->dir.'/home')->status(null)->lines['Autoloader'];
$slash = managerWithAutoload($this->dir, $this->source, $autoload, $this->dir.'/home/')->status(null)->lines['Autoloader'];
$sibling = managerWithAutoload($this->dir, $this->source, $autoload, $this->dir.'/hom')->status(null)->lines['Autoloader'];

expect($inHome)->toBe($autoload.' (in the home directory: the web server must be able to read it, or the cache stays off without an error)')
->and($slash)->toBe($inHome)
->and($sibling)->toBe($autoload);
});

it('is not healthy when the autoloader it names cannot be read', function (): void {
(new RedisHarness)->store();
$manager = managerWithAutoload($this->dir, $this->source, $this->dir.'/gone/autoload.php');
$manager->enable();
$report = $manager->status(liveSettings());

expect($report->lines['Autoloader'])->toBe($this->dir.'/gone/autoload.php (not readable by this user)')
->and($report->lines['Redis'])->toStartWith('reachable')
->and($report->lines['Drop-in'])->toStartWith('current')
->and($report->healthy)->toBeFalse();
});

/**
* A package directory under a vendor directory, with a drop-in to ship; the test directory holds it all.
*/
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/ObjectCacheCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
it('shows the status, and fails when the cache does not work', function (): void {
($this->command)($this->settings)->status();

expect($this->output->lines)->toHaveCount(7)
expect($this->output->lines)->toHaveCount(8)
->and($this->output->lines[0])->toStartWith('Drop-in:')
->and($this->output->error)->toBe(['The object cache is not working.']);
});
Expand Down