-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathobject-cache.php
2274 lines (1964 loc) · 76.6 KB
/
object-cache.php
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Redis Object Cache (PHP 8+)
* Description: Lightweight, high-performance drop-in object cache using Redis.
* Version: 1.0.0
* Author: Openbrige Inc, Thomas Spicer
*/
defined('ABSPATH') || exit; // Prevent direct file access.
if (!defined('WP_REDIS_DISABLED') || !WP_REDIS_DISABLED) :
/** ===========================================================================
* PART 1: WordPress Function Definitions
* ============================================================================
*
* WordPress expects these `wp_cache_*()` functions to be globally defined.
* Do not rename or remove them, or the object cache will fail.
*/
/**
* Check whether the object cache supports a feature.
*/
function wp_cache_supports(string $feature): bool {
return match ($feature) {
'add_multiple',
'set_multiple',
'get_multiple',
'delete_multiple',
'flush_runtime',
'flush_group' => true,
default => false,
};
}
/**
* Adds a value to cache if the key does not exist.
*
* @param string $key
* @param mixed $value
* @param string $group
* @param int $expiration Number of seconds to store the value. 0 = permanent.
*/
function wp_cache_add(
string $key,
mixed $value,
string $group = '',
int $expiration = 0
): bool {
global $wp_object_cache;
return $wp_object_cache->add($key, $value, $group, $expiration);
}
/**
* Adds multiple values to cache in one call.
*/
function wp_cache_add_multiple(array $data, string $group = '', int $expire = 0): array {
global $wp_object_cache;
return $wp_object_cache->add_multiple($data, $group, $expire);
}
/**
* Close the cache. (No-op)
*/
function wp_cache_close(): bool {
return true;
}
/**
* Decrement a numeric item's value.
*/
function wp_cache_decr(string $key, int $offset = 1, string $group = ''): int|bool {
global $wp_object_cache;
return $wp_object_cache->decrement($key, $offset, $group);
}
/**
* Remove the item from the cache.
*/
function wp_cache_delete(string $key, string $group = '', int $time = 0): bool {
global $wp_object_cache;
return $wp_object_cache->delete($key, $group, $time);
}
/**
* Deletes multiple values from the cache in one call.
*/
function wp_cache_delete_multiple(array $keys, string $group = ''): array {
global $wp_object_cache;
return $wp_object_cache->delete_multiple($keys, $group);
}
/**
* Flush all cache. If WP_REDIS_SELECTIVE_FLUSH is set, flush only that prefix.
*/
function wp_cache_flush(): bool {
global $wp_object_cache;
return $wp_object_cache->flush();
}
/**
* Removes all cache items in a group.
*/
function wp_cache_flush_group(string $group): bool {
global $wp_object_cache;
return $wp_object_cache->flush_group($group);
}
/**
* Removes all items from the in-memory runtime cache only.
*/
function wp_cache_flush_runtime(): bool {
global $wp_object_cache;
return $wp_object_cache->flush_runtime();
}
/**
* Retrieve an object from cache.
*/
function wp_cache_get(string $key, string $group = '', bool $force = false, ?bool &$found = null): mixed {
global $wp_object_cache;
return $wp_object_cache->get($key, $group, $force, $found);
}
/**
* Retrieve multiple values from cache in one call.
*/
function wp_cache_get_multiple(array $keys, string $group = '', bool $force = false): array|false {
global $wp_object_cache;
return $wp_object_cache->get_multiple($keys, $group, $force);
}
/**
* Increment a numeric item's value.
*/
function wp_cache_incr(string $key, int $offset = 1, string $group = ''): int|bool {
global $wp_object_cache;
return $wp_object_cache->increment($key, $offset, $group);
}
/**
* Initialize the caching system and global $wp_object_cache.
*/
function wp_cache_init(): void {
global $wp_object_cache;
if (!defined('WP_REDIS_PREFIX') && getenv('WP_REDIS_PREFIX')) {
define('WP_REDIS_PREFIX', getenv('WP_REDIS_PREFIX'));
}
if (!defined('WP_REDIS_SELECTIVE_FLUSH') && getenv('WP_REDIS_SELECTIVE_FLUSH')) {
define('WP_REDIS_SELECTIVE_FLUSH', (bool) getenv('WP_REDIS_SELECTIVE_FLUSH'));
}
// Optional: WP_CACHE_KEY_SALT → WP_REDIS_PREFIX
if (defined('WP_CACHE_KEY_SALT') && !defined('WP_REDIS_PREFIX')) {
define('WP_REDIS_PREFIX', WP_CACHE_KEY_SALT);
}
if (!($wp_object_cache instanceof WP_Object_Cache)) {
$fail_gracefully = defined('WP_REDIS_GRACEFUL') && WP_REDIS_GRACEFUL;
$wp_object_cache = new WP_Object_Cache($fail_gracefully);
}
}
/**
* Replace a value in cache if the key already exists.
*/
function wp_cache_replace(string $key, mixed $value, string $group = '', int $expiration = 0): bool {
global $wp_object_cache;
return $wp_object_cache->replace($key, $value, $group, $expiration);
}
/**
* Set a value in cache (unconditionally).
*/
function wp_cache_set(string $key, mixed $value, string $group = '', int $expiration = 0): bool {
global $wp_object_cache;
return $wp_object_cache->set($key, $value, $group, $expiration);
}
/**
* Set multiple values to cache in one call.
*/
function wp_cache_set_multiple(array $data, string $group = '', int $expire = 0): array {
global $wp_object_cache;
return $wp_object_cache->set_multiple($data, $group, $expire);
}
/**
* Switch blog (multisite).
*/
function wp_cache_switch_to_blog(int $_blog_id): bool {
global $wp_object_cache;
return $wp_object_cache->switch_to_blog($_blog_id);
}
/**
* Make some groups global across sites.
*/
function wp_cache_add_global_groups(array|string $groups): void {
global $wp_object_cache;
$wp_object_cache->add_global_groups($groups);
}
/**
* Exclude certain groups from saving to Redis.
*/
function wp_cache_add_non_persistent_groups(array|string $groups): void {
global $wp_object_cache;
$wp_object_cache->add_non_persistent_groups($groups);
}
/** ===========================================================================
* PART 2: The WP_Object_Cache Class
* ============================================================================
*/
class WP_Object_Cache {
/**
* -----------------------------------------------------------------------
* Required Properties
* -----------------------------------------------------------------------
*/
// Declare prefix_cache at the top of your class properties:
private array $prefix_cache = [];
private int $max_runtime_entries = 1000;
private array $cache = [];
private \SplQueue $cacheEvictionQueue; // For eviction ordering of keys
private bool $redis_connected = false;
private bool $fail_gracefully = false;
private array $errors = [];
private array $global_groups = [];
private array $ignored_groups = [];
private array $unflushable_groups = [];
private string|int $blog_prefix = 1;
private string $global_prefix = 'global';
private array $group_type = [];
private array $diagnostics = [];
private ?\Redis $redis = null; // or \Relay\Relay or \Predis\Client at runtime
private ?string $redis_version = null;
private int $cache_hits = 0;
private int $cache_misses = 0;
private int $cache_calls = 0;
private float $cache_time = 0.0;
/**
* Compression-Related Properties
*/
private const COMPRESSION_PREFIX = 'C:';
private const COMPRESSION_ZLIB_PREFIX = 'Z:';
private const COMPRESSION_GZIP_PREFIX = 'G:';
private array $compression_stats = [];
private $runtime_lock;
private const LOCK_TIMEOUT = 0.5; // 500ms timeout
private array $cache_usage_tracking = [];
private int $last_cleanup_time = 0;
private const CLEANUP_INTERVAL = 3600; // 1 hour
private const MAX_DB_SWITCH_RETRIES = 3;
private array $db_switch_failures = [];
private ?int $fallback_database = null;
private bool $compression_enabled = true;
private int $min_compress_length = 1024;
private int $compression_level = 6; // gzip compression level (1-9)
private string $preferred_compression = 'gzip';
private array $preload_keys = [];
private const SCAN_COUNT = 1000;
private const MAX_PIPELINE_SIZE = 100;
private const FLUSH_BATCH_SIZE = 1000;
private const MAX_FLUSH_ATTEMPTS = 3;
private array $flush_stats = [];
private const MAX_SERIALIZED_LENGTH = 64 * 1024 * 1024; // 64MB
private const SERIALIZED_PATTERN = '/^((s|i|d|b|a|O|C|r|R|N):|{.*}$)/';
private array $serialization_stats = [];
private function attempt_reconnect(int $retries = 3, int $delay = 1): bool {
for ($i = 0; $i < $retries; $i++) {
try {
if ($i > 0) {
sleep($delay); // Wait before retry
}
// Rebuild connection based on original parameters
$client = $this->determine_client();
$params = $this->build_parameters();
switch ($client) {
case 'phpredis':
$this->connect_phpredis($params);
break;
case 'relay':
$this->connect_relay($params);
break;
default:
$this->connect_predis($params);
}
// Verify connection
$this->redis->ping();
$this->redis_connected = true;
$this->fetch_info();
// Restore original database if needed
if ($this->current_database !== null) {
$this->redis->select($this->current_database);
}
return true;
} catch (\Exception $e) {
continue; // Try next iteration
}
}
return false;
}
/**
* Check if compression should be used for this value
*/
private function should_compress(string $data): bool {
// Check for existing compression markers
if (str_starts_with($data, self::COMPRESSION_PREFIX) ||
str_starts_with($data, self::COMPRESSION_ZLIB_PREFIX) ||
str_starts_with($data, self::COMPRESSION_GZIP_PREFIX)) {
return false;
}
// Don't compress small numeric values
if (is_numeric($data) && strlen($data) < 20) {
return false;
}
// Don't compress already compressed data formats
$compressed_formats = [
// Images
"\x89\x50\x4E\x47", // PNG
"\xFF\xD8\xFF", // JPEG
"\x1F\x8B\x08", // GZIP
"\x42\x5A\x68", // BZIP2
// Add more signatures as needed
];
foreach ($compressed_formats as $signature) {
if (str_starts_with($data, $signature)) {
return false;
}
}
return $this->compression_enabled &&
strlen($data) >= $this->min_compress_length &&
$this->get_compression_function() !== null;
}
// Add this new method to get appropriate compression function
private function get_compression_function(): ?string {
switch ($this->preferred_compression) {
case 'gzip':
if (function_exists('gzcompress')) {
return 'gzcompress';
}
// Fall through to zlib
case 'zlib':
if (function_exists('zlib_encode')) {
return 'zlib_encode';
}
break;
case 'none':
return null;
}
// Final fallback check
if (function_exists('gzcompress')) {
return 'gzcompress';
}
return null;
}
/**
* Possibly unserialize and decompress data
*/
private function maybe_serialize(mixed $value): string|false {
try {
$serialized = serialize($value);
if (!$this->should_compress($serialized)) {
return $serialized;
}
$compression_func = $this->get_compression_function();
if ($compression_func === null) {
return $serialized;
}
$before_size = strlen($serialized);
$compressed = match($compression_func) {
'gzcompress' => gzcompress($serialized, $this->compression_level),
'zlib_encode' => zlib_encode($serialized, ZLIB_ENCODING_DEFLATE, $this->compression_level),
default => false
};
if ($compressed === false) {
error_log('Redis Cache: Compression failed');
return $serialized;
}
$after_size = strlen($compressed);
// Only use compression if it actually helps
if ($after_size >= $before_size) {
$this->track_compression_stats('skipped', $before_size);
return $serialized;
}
$this->track_compression_stats('compressed', $before_size, $after_size);
$prefix = match($compression_func) {
'gzcompress' => self::COMPRESSION_GZIP_PREFIX,
'zlib_encode' => self::COMPRESSION_ZLIB_PREFIX,
default => self::COMPRESSION_PREFIX
};
return $prefix . $compressed;
} catch (\Exception $e) {
error_log('Redis Cache: Serialization error - ' . $e->getMessage());
return false;
}
}
// Replace maybe_unserialize method
private function maybe_unserialize(mixed $data): mixed {
if (!is_string($data)) {
return $data;
}
try {
// Check for compression prefixes
$decompressed = null;
if (str_starts_with($data, self::COMPRESSION_GZIP_PREFIX)) {
if (!function_exists('gzuncompress')) {
throw new \RuntimeException('gzuncompress function not available');
}
$decompressed = gzuncompress(substr($data, strlen(self::COMPRESSION_GZIP_PREFIX)));
}
elseif (str_starts_with($data, self::COMPRESSION_ZLIB_PREFIX)) {
if (!function_exists('zlib_decode')) {
throw new \RuntimeException('zlib_decode function not available');
}
$decompressed = zlib_decode(substr($data, strlen(self::COMPRESSION_ZLIB_PREFIX)));
}
elseif (str_starts_with($data, self::COMPRESSION_PREFIX)) {
// Legacy compression support
if (!function_exists('gzuncompress')) {
throw new \RuntimeException('gzuncompress function not available');
}
$decompressed = gzuncompress(substr($data, strlen(self::COMPRESSION_PREFIX)));
}
if ($decompressed !== null) {
if ($decompressed === false) {
throw new \RuntimeException('Decompression failed');
}
$data = $decompressed;
}
$unserialized = @unserialize($data);
if ($unserialized === false && $data !== 'b:0;') {
throw new \RuntimeException('Unserialization failed');
}
return $unserialized;
} catch (\Exception $e) {
error_log('Redis Cache: Unserialization error - ' . $e->getMessage());
return false;
}
}
private function track_compression_stats(string $type, int $before_size, ?int $after_size = null): void {
if (!isset($this->compression_stats[$type])) {
$this->compression_stats[$type] = [
'count' => 0,
'total_before' => 0,
'total_after' => 0
];
}
$this->compression_stats[$type]['count']++;
$this->compression_stats[$type]['total_before'] += $before_size;
if ($after_size !== null) {
$this->compression_stats[$type]['total_after'] += $after_size;
}
}
// Add method to get compression statistics
public function get_compression_stats(): array {
$stats = $this->compression_stats;
// Calculate ratios
foreach ($stats as $type => $data) {
if (isset($data['total_after']) && $data['total_before'] > 0) {
$stats[$type]['ratio'] = round(
($data['total_before'] - $data['total_after']) / $data['total_before'] * 100,
2
);
}
}
return $stats;
}
/**
* Configure compression at runtime.
*/
public function configure_compression(bool $enabled = true, int $min_length = 1024, int $level = 6): void {
$this->compression_enabled = $enabled;
$this->min_compress_length = $min_length;
$this->compression_level = max(1, min(9, $level));
}
/**
* Constructor
*/
public function __construct(bool $fail_gracefully = false) {
$this->fail_gracefully = $fail_gracefully;
$this->cacheEvictionQueue = new \SplQueue();
// Determine the appropriate client, build parameters, then connect
$client = $this->determine_client();
$params = $this->build_parameters();
try {
switch ($client) {
case 'phpredis':
$this->connect_phpredis($params);
break;
case 'relay':
$this->connect_relay($params);
break;
default:
// fallback to predis
$this->connect_predis($params);
}
$this->redis_connected = true;
$this->fetch_info();
// Add serializer configuration here, after connection is established
$this->configure_serializer();
} catch (\Exception $e) {
$this->handle_exception($e);
}
// Initialize group lists (global, ignored, unflushable)
$this->bootstrap_group_lists();
$this->cache_group_types();
// Configure compression from constants
$compression_enabled = defined('WP_REDIS_COMPRESSION') ? WP_REDIS_COMPRESSION : true;
$min_compress_length = defined('WP_REDIS_MIN_COMPRESS_LENGTH') ? (int)WP_REDIS_MIN_COMPRESS_LENGTH : 1024;
$compression_level = defined('WP_REDIS_COMPRESSION_LEVEL') ? (int)WP_REDIS_COMPRESSION_LEVEL : 6;
$this->configure_compression($compression_enabled, $min_compress_length, $compression_level);
$this->preload_cache();
// Initialize the mutex
if (class_exists('\SplMutex')) {
$this->runtime_lock = new \SplMutex();
} elseif (function_exists('sem_get') && function_exists('ftok')) {
$this->runtime_lock = @sem_get(ftok(__FILE__, 'R'));
if ($this->runtime_lock === false) {
$this->runtime_lock = null;
}
} else {
$this->runtime_lock = null;
}
}
private function decompress_data(string $data): string|false {
try {
if (str_starts_with($data, self::COMPRESSION_GZIP_PREFIX)) {
if (!function_exists('gzuncompress')) {
throw new \RuntimeException('gzuncompress function not available');
}
return gzuncompress(substr($data, strlen(self::COMPRESSION_GZIP_PREFIX)));
}
if (str_starts_with($data, self::COMPRESSION_ZLIB_PREFIX)) {
if (!function_exists('zlib_decode')) {
throw new \RuntimeException('zlib_decode function not available');
}
return zlib_decode(substr($data, strlen(self::COMPRESSION_ZLIB_PREFIX)));
}
if (str_starts_with($data, self::COMPRESSION_PREFIX)) {
if (!function_exists('gzuncompress')) {
throw new \RuntimeException('gzuncompress function not available');
}
return gzuncompress(substr($data, strlen(self::COMPRESSION_PREFIX)));
}
return false;
} catch (\Exception $e) {
error_log('Redis Cache: Decompression error - ' . $e->getMessage());
return false;
}
}
/**
* Configure Redis serializer based on available extensions and settings
*/
private function configure_serializer(): void {
if (!$this->redis_status()) {
return;
}
// Get configured serializer from constant or default to PHP
$serializer = defined('WP_REDIS_SERIALIZER')
? strtolower(WP_REDIS_SERIALIZER)
: 'php';
try {
switch ($serializer) {
case 'igbinary':
if (extension_loaded('igbinary') && defined('Redis::SERIALIZER_IGBINARY')) {
$this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY);
$this->diagnostics['serializer'] = 'igbinary';
} else {
$this->fallback_to_php_serializer();
}
break;
case 'json':
if (defined('Redis::SERIALIZER_JSON')) {
$this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_JSON);
$this->diagnostics['serializer'] = 'json';
} else {
$this->fallback_to_php_serializer();
}
break;
case 'msgpack':
if (extension_loaded('msgpack') && defined('Redis::SERIALIZER_MSGPACK')) {
$this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_MSGPACK);
$this->diagnostics['serializer'] = 'msgpack';
} else {
$this->fallback_to_php_serializer();
}
break;
case 'none':
if (defined('Redis::SERIALIZER_NONE')) {
$this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_NONE);
$this->diagnostics['serializer'] = 'none';
} else {
$this->fallback_to_php_serializer();
}
break;
case 'php':
default:
$this->fallback_to_php_serializer();
break;
}
} catch (\Exception $e) {
error_log('Redis Cache: Error configuring serializer: ' . $e->getMessage());
$this->fallback_to_php_serializer();
}
}
/**
* Set PHP as the fallback serializer
*/
private function fallback_to_php_serializer(): void {
try {
if (defined('Redis::OPT_SERIALIZER') && defined('Redis::SERIALIZER_PHP')) {
$this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
$this->diagnostics['serializer'] = 'php';
}
} catch (\Exception $e) {
error_log('Redis Cache: Failed to set PHP serializer - ' . $e->getMessage());
}
}
/**
* Store a value in the runtime cache with eviction logic.
*/
private function store_in_runtime_cache(string $derivedKey, mixed $value): void {
try {
if ($this->acquire_lock()) {
try {
// Track memory usage before addition
$initial_memory = memory_get_usage();
// Update existing entry
if (isset($this->cache[$derivedKey])) {
$this->cache[$derivedKey] = is_object($value) ? clone $value : $value;
$this->cache_usage_tracking[$derivedKey] = [
'time' => time(),
'size' => memory_get_usage() - $initial_memory
];
return;
}
// Check memory limit before adding new entry
if ($this->check_memory_limit()) {
$this->force_cleanup();
}
// If still at capacity after cleanup, evict oldest
if ($this->cacheEvictionQueue->count() >= $this->max_runtime_entries) {
$this->evict_oldest();
}
// Add new entry
$this->cache[$derivedKey] = is_object($value) ? clone $value : $value;
$this->cacheEvictionQueue->enqueue($derivedKey);
// Track memory usage
$this->cache_usage_tracking[$derivedKey] = [
'time' => time(),
'size' => memory_get_usage() - $initial_memory
];
// Periodic cleanup check
$this->maybe_run_cleanup();
} finally {
$this->release_lock();
}
}
} catch (\Exception $e) {
error_log('Redis Cache: Runtime cache error: ' . $e->getMessage());
// Emergency cleanup if something goes wrong
$this->emergency_cleanup();
}
}
// Add these new methods for memory management
private function check_memory_limit(): bool {
$limit = ini_get('memory_limit');
if ($limit === '-1') return false; // No limit set
$limit_bytes = $this->convert_to_bytes($limit);
$current_usage = memory_get_usage();
return ($current_usage / $limit_bytes) > 0.9; // 90% threshold
}
private function convert_to_bytes(string $value): int {
$value = trim($value);
$last = strtolower($value[strlen($value)-1]);
$value = (int)$value;
switch($last) {
case 'g': $value *= 1024;
case 'm': $value *= 1024;
case 'k': $value *= 1024;
}
return $value;
}
private function force_cleanup(): void {
// Remove entries exceeding age threshold
$threshold = time() - 3600; // 1 hour old
foreach ($this->cache_usage_tracking as $key => $data) {
if ($data['time'] < $threshold) {
$this->evict_key($key);
}
}
// If still need more space, remove largest entries
if ($this->check_memory_limit()) {
uasort($this->cache_usage_tracking, fn($a, $b) => $b['size'] - $a['size']);
$count = 0;
foreach ($this->cache_usage_tracking as $key => $data) {
$this->evict_key($key);
$count++;
if ($count >= 10) break; // Remove top 10 largest entries
}
}
}
private function evict_key(string $key): void {
unset($this->cache[$key]);
unset($this->cache_usage_tracking[$key]);
// Requeue remaining items to maintain sync
$temp_queue = new \SplQueue();
while (!$this->cacheEvictionQueue->isEmpty()) {
$qkey = $this->cacheEvictionQueue->dequeue();
if ($qkey !== $key && isset($this->cache[$qkey])) {
$temp_queue->enqueue($qkey);
}
}
$this->cacheEvictionQueue = $temp_queue;
}
private function evict_oldest(): void {
while (!$this->cacheEvictionQueue->isEmpty()) {
$oldest_key = $this->cacheEvictionQueue->dequeue();
if (isset($this->cache[$oldest_key])) {
$this->evict_key($oldest_key);
break;
}
}
}
private function maybe_run_cleanup(): void {
$current_time = time();
if (($current_time - $this->last_cleanup_time) >= self::CLEANUP_INTERVAL) {
$this->force_cleanup();
$this->last_cleanup_time = $current_time;
}
}
private function emergency_cleanup(): void {
try {
// Reset everything in emergency
$this->cache = [];
$this->cache_usage_tracking = [];
$this->cacheEvictionQueue = new \SplQueue();
$this->last_cleanup_time = time();
error_log('Redis Cache: Emergency cleanup performed');
} catch (\Exception $e) {
error_log('Redis Cache: Emergency cleanup failed: ' . $e->getMessage());
}
}
// Add these new methods for lock handling
private function acquire_lock(): bool {
if ($this->runtime_lock === null) {
return true; // No locking available, proceed anyway
}
if ($this->runtime_lock instanceof \SplMutex) {
return $this->runtime_lock->lock();
}
return @sem_acquire($this->runtime_lock, true);
}
private function release_lock(): void {
if ($this->runtime_lock === null) {
return; // No locking available
}
if ($this->runtime_lock instanceof \SplMutex) {
$this->runtime_lock->unlock();
return;
}
@sem_release($this->runtime_lock);
}
// Add a destructor to ensure lock cleanup
public function __destruct() {
try {
if ($this->redis) {
$this->redis->close();
}
if ($this->runtime_lock instanceof \SplMutex) {
if ($this->runtime_lock->locked()) {
$this->runtime_lock->unlock();
}
} elseif ($this->runtime_lock !== null) {
@sem_remove($this->runtime_lock);
}
} catch (\Exception $e) {
error_log('Redis Cache: Error cleaning up - ' . $e->getMessage());
}
}
/**
* Add keys to be preloaded on initialization
*/
public function add_preload_keys(array $keys, string $group = 'default'): void {
foreach ($keys as $key) {
$this->preload_keys[] = $this->build_key($key, $group);
}
}
/**
* Preload frequently accessed keys into runtime cache
*/
private function preload_cache(): void {
if (empty($this->preload_keys) || !$this->redis_status()) {
return;
}
try {
$values = $this->redis->mget($this->preload_keys);
if (!is_array($values)) {
// If mget fails but doesn't throw, log and return
error_log('WordPress Redis Cache: Failed to preload cache - invalid mget response');
return;
}
foreach ($this->preload_keys as $i => $key) {
if (isset($values[$i]) && $values[$i] !== false && $values[$i] !== null) {
$value = $this->maybe_unserialize($values[$i]);
if ($value !== false) {
$this->cache[$key] = $value;
}
}
}
} catch (\Exception $e) {
$this->handle_exception($e);
return;
}
}
/**
* Initialize group arrays from possible user constants.
*/
private function bootstrap_group_lists(): void {
if (defined('WP_REDIS_GLOBAL_GROUPS') && is_array(WP_REDIS_GLOBAL_GROUPS)) {
$this->global_groups = array_map([$this, 'sanitize_key_part'], WP_REDIS_GLOBAL_GROUPS);
}
$this->global_groups[] = 'redis-cache';
if (defined('WP_REDIS_IGNORED_GROUPS') && is_array(WP_REDIS_IGNORED_GROUPS)) {
$this->ignored_groups = array_map([$this, 'sanitize_key_part'], WP_REDIS_IGNORED_GROUPS);
}
if (defined('WP_REDIS_UNFLUSHABLE_GROUPS') && is_array(WP_REDIS_UNFLUSHABLE_GROUPS)) {
$this->unflushable_groups = array_map([$this, 'sanitize_key_part'], WP_REDIS_UNFLUSHABLE_GROUPS);
}
}
/**
* Map each group into a "type" for quick checking later.
*/
private function cache_group_types(): void {
foreach ($this->global_groups as $g) {
$this->group_type[$g] = 'global';
}
foreach ($this->ignored_groups as $g) {
$this->group_type[$g] = 'ignored';
}
foreach ($this->unflushable_groups as $g) {
$this->group_type[$g] = 'unflushable';
}
}
/**
* Determine which Redis client to use: phpredis, relay, or predis.
*/
private function determine_client(): string {
$client = 'predis';
if (class_exists('Redis')) {
$client = 'phpredis';
}
if (defined('WP_REDIS_CLIENT')) {
$client = strtolower((string) WP_REDIS_CLIENT);
// 'pecl' is often used to refer to phpredis in some docs
$client = str_replace('pecl', 'phpredis', $client);
}
// If "relay" is configured but Relay extension isn't actually installed, fall back
if ($client === 'relay' && !class_exists('\Relay\Relay')) {
$client = 'phpredis';
}
return $client;
}
/**
* Build connection parameters from constants or defaults.
*/
private function build_parameters(): array {
$default = [
'scheme' => 'tcp',
'host' => defined('WP_REDIS_HOST') ? WP_REDIS_HOST : '127.0.0.1',
'port' => defined('WP_REDIS_PORT') ? WP_REDIS_PORT : 6379,
'database' => defined('WP_REDIS_DATABASE') ? WP_REDIS_DATABASE : 0,
'timeout' => defined('WP_REDIS_TIMEOUT') ? WP_REDIS_TIMEOUT : 1,
'read_timeout' => defined('WP_REDIS_READ_TIMEOUT') ? WP_REDIS_READ_TIMEOUT : 1,
'retry_interval' => defined('WP_REDIS_RETRY_INTERVAL') ? WP_REDIS_RETRY_INTERVAL : null,
'persistent' => defined('WP_REDIS_PERSISTENT') ? WP_REDIS_PERSISTENT : true, // Enable by default
'persistent_id' => defined('WP_REDIS_PERSISTENT_ID') ? WP_REDIS_PERSISTENT_ID : null,
'password' => null,
];
// Map WP_REDIS_* constants into $default if defined
foreach (['scheme','host','port','path','password','database','timeout','read_timeout','retry_interval'] as $setting) {
$constant = 'WP_REDIS_' . strtoupper($setting);
if (defined($constant)) {