-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStarCacheAdapter.php
More file actions
669 lines (585 loc) · 23.4 KB
/
Copy pathStarCacheAdapter.php
File metadata and controls
669 lines (585 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
<?php
declare(strict_types=1);
namespace StarCache;
use Exception;
/**
* StarCacheAdapter
*
* Auto-detects and initialises the best available cache backend:
* Redis → Memcached → Memcache → WordPress object cache (APCu / file / DB).
* OPcache is reported but managed by PHP itself; this class exposes a helper
* to check its status.
*
* Connection parameters are read from WordPress constants when defined:
* WP_REDIS_HOST, WP_REDIS_PORT, WP_REDIS_PASSWORD, WP_REDIS_DATABASE
* MEMCACHED_SERVERS (array of ['host', 'port'] pairs)
* MEMCACHE_SERVER_HOST / MEMCACHE_SERVER_PORT
*
* @package StarCache
* @author MaximillianGroup (Max Barrett) <maximilliangroup@gmail.com>
* @version 2.1.1
* @license Apache 2.0
*/
class StarCacheAdapter
{
public const BACKEND_REDIS = 'redis';
public const BACKEND_MEMCACHED = 'memcached';
public const BACKEND_MEMCACHE = 'memcache';
public const BACKEND_WP = 'wp';
private const DEFAULT_GROUP = 'default';
private const PONG_TRIM_CHARS = " \t\n\r\0\x0B+";
/** @var \Redis|\Predis\Client|\Memcached|\Memcache|null */
private static $connection = null;
/** @var string */
private static string $detectedBackend = self::BACKEND_WP;
/** @var bool */
private static bool $initialised = false;
/** @var array<string,string> */
private static array $groupHashCache = [];
/**
* Initialise the adapter (idempotent – safe to call multiple times).
*/
public static function init(): void
{
if (self::$initialised) {
return;
}
self::$initialised = true;
try {
if (self::tryRedis()) {
return;
}
} catch (Exception $e) {
self::logError('StarCacheAdapter init redis probe error', $e);
}
try {
if (self::tryPredis()) {
return;
}
} catch (Exception $e) {
self::logError('StarCacheAdapter init predis probe error', $e);
}
try {
if (self::tryMemcached()) {
return;
}
} catch (Exception $e) {
self::logError('StarCacheAdapter init memcached probe error', $e);
}
try {
if (self::tryMemcache()) {
return;
}
} catch (Exception $e) {
self::logError('StarCacheAdapter init memcache probe error', $e);
}
// Fallback: WordPress built-in object cache (wp_cache_*)
self::$detectedBackend = self::BACKEND_WP;
}
// -------------------------------------------------------------------------
// Public API
// -------------------------------------------------------------------------
/**
* Returns the name of the active backend.
*/
public static function getBackend(): string
{
return self::$detectedBackend;
}
/**
* Returns the raw connection object (backend-specific) or null when the
* WordPress object cache fallback is used.
*
* @return object|null
*/
public static function getConnection(): object|null
{
return self::$connection;
}
/**
* Return backend capability information for operational visibility.
*
* @return array<string,bool|string>
*/
public static function getBackendCapabilities(): array
{
return [
'phpredis_available' => extension_loaded('redis'),
'predis_available' => class_exists('\Predis\Client'),
'memcached_available' => extension_loaded('memcached'),
'memcache_available' => extension_loaded('memcache'),
'wp_object_cache_add' => function_exists('wp_cache_add'),
'wp_object_cache_flush' => function_exists('wp_cache_flush'),
'wp_object_cache_mode' => self::detectWpObjectCacheMode(),
'active_backend' => self::getBackend(),
];
}
/**
* Returns true when OPcache is enabled and functioning.
*/
public static function isOpcacheEnabled(): bool
{
if (!function_exists('opcache_get_status')) {
return false;
}
$status = @opcache_get_status(false);
return is_array($status) && !empty($status['opcache_enabled']);
}
/**
* Retrieve a value from the active cache backend.
*
* @param string $key
* @param string $group Used for namespacing across all cache backends; maps to a WP cache group for the WP object cache backend.
* @return mixed
*/
public static function get(string $key, string $group = ''): mixed
{
$result = self::getWithFound($key, $group);
return $result['found'] ? $result['value'] : false;
}
/**
* Retrieve a value plus an explicit hit/miss indicator.
*
* @param string $key
* @param string $group Used for namespacing across all cache backends; maps to a WP cache group for the WP object cache backend.
* @return array{found: bool, value: mixed}
*/
public static function getWithFound(string $key, string $group = ''): array
{
try {
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
$storageKey = self::buildStorageKey($key, $group);
$value = self::$connection->get($storageKey);
if ($value === false || $value === null) {
return ['found' => false, 'value' => false];
}
if (!is_string($value)) {
return ['found' => false, 'value' => false];
}
$unserialized = unserialize($value, ['allowed_classes' => false]);
if ($unserialized === false && $value !== serialize(false)) {
return ['found' => false, 'value' => false];
}
return ['found' => true, 'value' => $unserialized];
case self::BACKEND_MEMCACHED:
$storageKey = self::buildStorageKey($key, $group);
$value = self::$connection->get($storageKey);
if ($value === false && self::$connection->getResultCode() === \Memcached::RES_NOTFOUND) {
return ['found' => false, 'value' => false];
}
// Value was stored as a serialized string; unserialize to recover the original.
if (!is_string($value)) {
return ['found' => false, 'value' => false];
}
$unserialized = unserialize($value, ['allowed_classes' => false]);
if ($unserialized === false && $value !== serialize(false)) {
return ['found' => false, 'value' => false];
}
return ['found' => true, 'value' => $unserialized];
case self::BACKEND_MEMCACHE:
// Memcache::get() returns false on miss AND when the stored value is literally
// false. Values are stored serialized so a retrieved string is always a hit.
$storageKey = self::buildStorageKey($key, $group);
$value = self::$connection->get($storageKey); // @phpstan-ignore-line
if ($value === false) {
return ['found' => false, 'value' => false]; // cache miss (serialized values are strings, never false)
}
if (!is_string($value)) {
return ['found' => false, 'value' => false];
}
$unserialized = unserialize($value, ['allowed_classes' => false]);
if ($unserialized === false && $value !== serialize(false)) {
return ['found' => false, 'value' => false];
}
return ['found' => true, 'value' => $unserialized];
default:
$found = false;
$value = wp_cache_get($key, $group, false, $found);
return ['found' => $found, 'value' => $found ? $value : false];
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::getWithFound', $e);
return ['found' => false, 'value' => false];
}
}
/**
* Store a value in the active cache backend.
*
* @param string $key
* @param mixed $value
* @param int $expiration Seconds (0 = no expiry for WP/Redis).
* @param string $group Used for namespacing across all cache backends; maps to a WP cache group for the WP object cache backend.
* @return bool
*/
public static function set(string $key, mixed $value, int $expiration = 3600, string $group = ''): bool
{
try {
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
$storageKey = self::buildStorageKey($key, $group);
$serialised = serialize($value);
if ($expiration > 0) {
if (self::isPredisConnection()) {
return self::isSuccessfulSetResult(self::$connection->setex($storageKey, $expiration, $serialised));
}
return (bool) self::$connection->setEx($storageKey, $expiration, $serialised);
}
if (self::isPredisConnection()) {
return self::isSuccessfulSetResult(self::$connection->set($storageKey, $serialised));
}
return (bool) self::$connection->set($storageKey, $serialised);
case self::BACKEND_MEMCACHED:
// Serialize to mirror the Redis strategy and allow any PHP value
// (including boolean false) to be stored and retrieved unambiguously.
return self::$connection->set(
self::buildStorageKey($key, $group),
serialize($value),
$expiration
);
case self::BACKEND_MEMCACHE:
// Memcache::set($key, $value, $flags, $expire) — 0 = no compression.
// Serialize for the same reason as Memcached above.
return self::$connection->set(
self::buildStorageKey($key, $group),
serialize($value),
0,
$expiration
); // @phpstan-ignore-line
default:
return wp_cache_set($key, $value, $group, $expiration);
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::set', $e);
return false;
}
}
/**
* Delete a cached value.
*
* @param string $key
* @param string $group Used for namespacing across all cache backends; maps to a WP cache group for the WP object cache backend.
*/
public static function delete(string $key, string $group = ''): bool
{
try {
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
return (bool) self::$connection->del(self::buildStorageKey($key, $group));
case self::BACKEND_MEMCACHED:
return self::$connection->delete(self::buildStorageKey($key, $group));
case self::BACKEND_MEMCACHE:
return self::$connection->delete(self::buildStorageKey($key, $group));
default:
return wp_cache_delete($key, $group);
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::delete', $e);
return false;
}
}
/**
* Flush all cache entries (dangerous; intended for local dev/test only).
*/
public static function flush(): bool
{
if (!defined('STARCACHE_ALLOW_DANGEROUS_FLUSH') || STARCACHE_ALLOW_DANGEROUS_FLUSH !== true) {
self::logMessage(
'StarCacheAdapter::flush blocked. This is intended for development/testing only; use version bumps in production. Define STARCACHE_ALLOW_DANGEROUS_FLUSH=true in wp-config.php to enable.'
);
return false;
}
try {
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
if (self::isPredisConnection()) {
return self::isSuccessfulSetResult(self::$connection->flushdb());
}
return (bool) self::$connection->flushDB();
case self::BACKEND_MEMCACHED:
return self::$connection->flush();
case self::BACKEND_MEMCACHE:
return self::$connection->flush();
default:
return wp_cache_flush();
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::flush', $e);
return false;
}
}
/**
* Atomically set only when absent where backend supports add/NX semantics.
*
* @param mixed $value
*/
public static function add(string $key, mixed $value, int $expiration = 30, string $group = ''): bool
{
try {
$storageKey = self::buildStorageKey($key, $group);
$serialised = serialize($value);
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
if (self::isPredisConnection()) {
$options = ['NX'];
if ($expiration > 0) {
$options['EX'] = $expiration;
}
return self::isSuccessfulSetResult(self::$connection->set($storageKey, $serialised, $options));
}
$options = ['NX'];
if ($expiration > 0) {
$options['EX'] = $expiration;
}
$result = self::$connection->set($storageKey, $serialised, $options);
return self::isSuccessfulSetResult($result);
case self::BACKEND_MEMCACHED:
return self::$connection->add($storageKey, $serialised, $expiration);
case self::BACKEND_MEMCACHE:
return self::$connection->add($storageKey, $serialised, 0, $expiration); // @phpstan-ignore-line
default:
if (function_exists('wp_cache_add')) {
return wp_cache_add($key, $value, $group, $expiration);
}
$hit = self::getWithFound($key, $group);
if ($hit['found']) {
return false;
}
return self::set($key, $value, $expiration, $group);
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::add', $e);
return false;
}
}
/**
* Close the underlying connection (no-op for WP cache).
*/
public static function close(): void
{
if (self::$connection === null) {
return;
}
try {
switch (self::$detectedBackend) {
case self::BACKEND_REDIS:
if (self::isPredisConnection()) {
if (method_exists(self::$connection, 'disconnect')) {
self::$connection->disconnect();
}
} else {
self::$connection->close();
}
break;
case self::BACKEND_MEMCACHED:
case self::BACKEND_MEMCACHE:
self::$connection->close();
break;
}
} catch (Exception $e) {
self::logError('StarCacheAdapter::close', $e);
}
self::$connection = null;
}
// -------------------------------------------------------------------------
// Backend detection
// -------------------------------------------------------------------------
private static function tryRedis(): bool
{
if (!extension_loaded('redis')) {
return false;
}
$host = defined('WP_REDIS_HOST') ? WP_REDIS_HOST : '127.0.0.1';
$port = defined('WP_REDIS_PORT') ? (int) WP_REDIS_PORT : 6379;
$password = defined('WP_REDIS_PASSWORD') ? WP_REDIS_PASSWORD : null;
$database = defined('WP_REDIS_DATABASE') ? (int) WP_REDIS_DATABASE : 0;
$redis = new \Redis();
if (!@$redis->connect($host, $port, 1.0)) {
return false;
}
if ($password && !$redis->auth($password)) {
return false;
}
if ($database !== 0) {
$redis->select($database);
}
self::$connection = $redis;
self::$detectedBackend = self::BACKEND_REDIS;
return true;
}
private static function tryPredis(): bool
{
if (!class_exists('\Predis\Client')) {
return false;
}
$host = defined('WP_REDIS_HOST') ? WP_REDIS_HOST : '127.0.0.1';
$port = defined('WP_REDIS_PORT') ? (int) WP_REDIS_PORT : 6379;
$password = defined('WP_REDIS_PASSWORD') ? WP_REDIS_PASSWORD : null;
$database = defined('WP_REDIS_DATABASE') ? (int) WP_REDIS_DATABASE : 0;
$params = [
'scheme' => 'tcp',
'host' => $host,
'port' => $port,
'database' => $database,
];
if (is_string($password) && $password !== '') {
$params['password'] = $password;
}
try {
$client = new \Predis\Client($params, ['exceptions' => false]);
$pong = $client->ping();
} catch (Exception $e) {
self::logError('StarCacheAdapter::tryPredis', $e);
return false;
}
if (!self::isSuccessfulPredisPing($pong)) {
return false;
}
self::$connection = $client;
self::$detectedBackend = self::BACKEND_REDIS;
return true;
}
private static function tryMemcached(): bool
{
if (!extension_loaded('memcached')) {
return false;
}
$memcached = new \Memcached();
if (defined('MEMCACHED_SERVERS') && is_array(MEMCACHED_SERVERS)) {
foreach (MEMCACHED_SERVERS as $server) {
$memcached->addServer(
$server['host'] ?? '127.0.0.1',
(int) ($server['port'] ?? 11211)
);
}
} else {
$memcached->addServer('127.0.0.1', 11211);
}
// Verify connectivity via a trivial set/get
$testKey = 'starcache_probe_' . wp_generate_password(8, false);
$memcached->set($testKey, 1, 5);
if ($memcached->getResultCode() !== \Memcached::RES_SUCCESS) {
return false;
}
$memcached->delete($testKey);
self::$connection = $memcached;
self::$detectedBackend = self::BACKEND_MEMCACHED;
return true;
}
private static function tryMemcache(): bool
{
if (!extension_loaded('memcache')) {
return false;
}
$host = defined('MEMCACHE_SERVER_HOST') ? MEMCACHE_SERVER_HOST : '127.0.0.1';
$port = defined('MEMCACHE_SERVER_PORT') ? (int) MEMCACHE_SERVER_PORT : 11211;
$memcache = new \Memcache();
if (!@$memcache->connect($host, $port)) {
return false;
}
self::$connection = $memcache;
self::$detectedBackend = self::BACKEND_MEMCACHE;
return true;
}
// -------------------------------------------------------------------------
// Logging
// -------------------------------------------------------------------------
/**
* Build backend-internal namespaced key from logical key+group.
*/
private static function buildStorageKey(string $key, string $group): string
{
$normalizedGroup = self::normaliseGroup($group);
if (!array_key_exists($normalizedGroup, self::$groupHashCache)) {
self::$groupHashCache[$normalizedGroup] = substr(hash('sha256', $normalizedGroup), 0, 16);
}
return 'scg:' . self::$groupHashCache[$normalizedGroup] . ':' . $key;
}
private static function normaliseGroup(string $group): string
{
$group = strtolower(trim($group));
$sanitized = '';
$length = strlen($group);
for ($i = 0; $i < $length; $i++) {
$char = $group[$i];
if (
($char >= 'a' && $char <= 'z')
|| ($char >= '0' && $char <= '9')
|| $char === '_'
|| $char === '-'
|| $char === ':'
) {
$sanitized .= $char;
}
}
$group = $sanitized;
return $group !== '' ? $group : self::DEFAULT_GROUP;
}
private static function isPredisConnection(): bool
{
return class_exists('\Predis\Client') && self::$connection instanceof \Predis\Client;
}
private static function detectWpObjectCacheMode(): string
{
if (function_exists('wp_using_ext_object_cache') && wp_using_ext_object_cache()) {
return 'persistent';
}
return 'runtime';
}
private static function isSuccessfulSetResult(mixed $result): bool
{
// PhpRedis returns bool; Predis may return "OK" or status response objects.
if ($result === true) {
return true;
}
if (is_string($result)) {
return strtoupper(trim($result, self::PONG_TRIM_CHARS)) === 'OK';
}
if (is_object($result) && method_exists($result, 'getPayload')) {
$payload = $result->getPayload();
if (is_string($payload)) {
return strtoupper(trim($payload, self::PONG_TRIM_CHARS)) === 'OK';
}
}
if (is_object($result) && method_exists($result, '__toString')) {
return strtoupper(trim((string) $result, self::PONG_TRIM_CHARS)) === 'OK';
}
return false;
}
private static function isSuccessfulPredisPing(mixed $pong): bool
{
if ($pong === true) {
return true;
}
if (is_string($pong)) {
return strtoupper(trim($pong, self::PONG_TRIM_CHARS)) === 'PONG';
}
if (!is_object($pong)) {
return false;
}
if (method_exists($pong, 'getPayload')) {
$payload = $pong->getPayload();
if (is_string($payload)) {
return strtoupper(trim($payload, self::PONG_TRIM_CHARS)) === 'PONG';
}
}
if (method_exists($pong, '__toString')) {
return strtoupper(trim((string) $pong, self::PONG_TRIM_CHARS)) === 'PONG';
}
return false;
}
private static function logError(string $context, Exception $e): void
{
if (class_exists('\StarExceptionHandler')) {
$logger = \StarExceptionHandler::star_getInstance();
$logger->star_handleException($e);
} else {
error_log("[StarCache] {$context}: {$e->getMessage()}");
}
}
private static function logMessage(string $message): void
{
$exception = new \RuntimeException($message);
self::logError('StarCacheAdapter', $exception);
}
}