-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathRedis.php
1416 lines (1264 loc) · 52 KB
/
Redis.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
/*
==New BSD License==
Copyright (c) 2013, Colin Mollenhour
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of Colin Mollenhour may not be used to endorse or promote products
derived from this software without specific prior written permission.
* The class name must remain as Cm_Cache_Backend_Redis.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Redis adapter for Zend_Cache
*
* @copyright Copyright (c) 2013 Colin Mollenhour (http://colin.mollenhour.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @author Colin Mollenhour (http://colin.mollenhour.com)
*/
class Cm_Cache_Backend_Redis extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
public const SET_IDS = 'zc:ids';
public const SET_TAGS = 'zc:tags';
public const PREFIX_KEY = 'zc:k:';
public const PREFIX_TAG_IDS = 'zc:ti:';
public const FIELD_DATA = 'd';
public const FIELD_MTIME = 'm';
public const FIELD_TAGS = 't';
public const FIELD_INF = 'i';
public const MAX_LIFETIME = 2592000; /* Redis backend limit */
public const COMPRESS_PREFIX = ":\x1f\x8b";
public const DEFAULT_CONNECT_TIMEOUT = 2.5;
public const DEFAULT_CONNECT_RETRIES = 1;
public const LUA_SAVE_SH1 = '1617c9fb2bda7d790bb1aaa320c1099d81825e64';
public const LUA_CLEAN_SH1 = '39383dcf36d2e71364a666b2a806bc8219cd332d';
public const LUA_GC_SH1 = '6990147f5d1999b936dac3b6f7e5d2071908bcf3';
/** @var Credis_Client */
protected $_redis;
/** @var bool */
protected $_notMatchingTags = false;
/** @var int */
protected $_lifetimelimit = self::MAX_LIFETIME; /* Redis backend limit */
/** @var int|bool */
protected $_compressTags = 1;
/** @var int|bool */
protected $_compressData = 1;
/** @var int */
protected $_compressThreshold = 20480;
/** @var string */
protected $_compressionLib;
/** @var string */
protected $_compressPrefix;
/**
* On large data sets SUNION slows down considerably when used with too many arguments
* so this is used to chunk the SUNION into a few commands where the number of set ids
* exceeds this setting.
*
* @var int
*/
protected $_sunionChunkSize = 500;
/**
* Maximum number of ids to be removed at a time
*
* @var int
*/
protected $_removeChunkSize = 10000;
/** @var bool */
protected $_useLua = true;
/** @var integer */
protected $_autoExpireLifetime = 0;
/** @var string */
protected $_autoExpirePattern = '/REQEST/';
/** @var boolean */
protected $_autoExpireRefreshOnLoad = false;
/**
* Lua's unpack() has a limit on the size of the table imposed by
* the number of Lua stack slots that a C function can use.
* This value is defined by LUAI_MAXCSTACK in luaconf.h and for Redis it is set to 8000.
*
* @see https://github.com/antirez/redis/blob/b903145/deps/lua/src/luaconf.h#L439
* @var int
*/
protected $_luaMaxCStack = 5000;
/**
* If 'retry_reads_on_master' is truthy then reads will be retried against master when slave returns "(nil)" value
*
* @var boolean
*/
protected $_retryReadsOnMaster = false;
/**
* @var stdClass
*/
protected $_clientOptions;
/**
* If 'load_from_slaves' is truthy then reads are performed on a randomly selected slave server
*
* @var Credis_Client
*/
protected $_slave;
protected function getClientOptions($options = array())
{
$clientOptions = new stdClass();
$clientOptions->forceStandalone = isset($options['force_standalone']) && $options['force_standalone'];
$clientOptions->connectRetries = isset($options['connect_retries']) ? (int) $options['connect_retries'] : self::DEFAULT_CONNECT_RETRIES;
$clientOptions->readTimeout = isset($options['read_timeout']) ? (float) $options['read_timeout'] : null;
$clientOptions->password = $options['password'] ?? null;
$clientOptions->username = $options['username'] ?? null;
$clientOptions->database = isset($options['database']) ? (int) $options['database'] : 0;
$clientOptions->persistent = $options['persistent'] ?? '';
$clientOptions->timeout = $options['timeout'] ?? self::DEFAULT_CONNECT_TIMEOUT;
return $clientOptions;
}
/**
* Construct Zend_Cache Redis backend
* @param array $options
* @throws Zend_Cache_Exception
* @throws CredisException
* @noinspection PhpMissingParentConstructorInspection
*/
public function __construct($options = array())
{
if (empty($options['server']) && empty($options['cluster'])) {
Zend_Cache::throwException('Redis \'server\' not specified.');
}
$this->_clientOptions = $this->getClientOptions($options);
// If 'sentinel_master' is specified then server is actually sentinel and master address should be fetched from server.
$sentinelMaster = empty($options['sentinel_master']) ? null : $options['sentinel_master'];
if ($sentinelMaster) {
$sentinelClientOptions = isset($options['sentinel']) && is_array($options['sentinel'])
? $this->getClientOptions($options['sentinel'] + $options)
: $this->_clientOptions;
$servers = preg_split('/\s*,\s*/', trim($options['server']), -1, PREG_SPLIT_NO_EMPTY);
$sentinel = null;
$exception = null;
for ($i = 0; $i <= $sentinelClientOptions->connectRetries; $i++) { // Try each sentinel in round-robin fashion
foreach ($servers as $server) {
try {
$sentinelClient = new Credis_Client($server, null, $sentinelClientOptions->timeout, $sentinelClientOptions->persistent);
$sentinelClient->forceStandalone();
$sentinelClient->setMaxConnectRetries(0);
if ($sentinelClientOptions->readTimeout) {
$sentinelClient->setReadTimeout($sentinelClientOptions->readTimeout);
}
if ($sentinelClientOptions->password) {
$sentinelClient->auth($sentinelClientOptions->password) or Zend_Cache::throwException('Unable to authenticate with the redis sentinel.');
}
$sentinel = new Credis_Sentinel($sentinelClient);
$sentinel
->setClientTimeout($this->_clientOptions->timeout)
->setClientPersistent($this->_clientOptions->persistent);
$redisMaster = $sentinel->getMasterClient($sentinelMaster);
$this->_applyClientOptions($redisMaster);
// Verify connected server is actually master as per Sentinel client spec
if (! empty($options['sentinel_master_verify'])) {
$roleData = $redisMaster->role();
if (! $roleData || $roleData[0] != 'master') {
usleep(100000); // Sleep 100ms and try again
$redisMaster = $sentinel->getMasterClient($sentinelMaster);
$this->_applyClientOptions($redisMaster);
$roleData = $redisMaster->role();
if (! $roleData || $roleData[0] != 'master') {
Zend_Cache::throwException('Unable to determine master redis server.');
}
}
}
$this->_redis = $redisMaster;
break 2;
} catch (Exception $e) {
unset($sentinelClient);
$exception = $e;
}
}
}
if (! $this->_redis) {
Zend_Cache::throwException('Unable to connect to a redis sentinel: '.$exception->getMessage(), $exception);
}
// Optionally use read slaves - will only be used for 'load' operation
if (! empty($options['load_from_slaves'])) {
$slaves = $sentinel->getSlaveClients($sentinelMaster);
if ($slaves) {
if ($options['load_from_slaves'] == 2) {
$slaves[] = $this->_redis; // Also send reads to the master
}
$slaveSelect = isset($options['slave_select_callable']) && is_callable($options['slave_select_callable']) ? $options['slave_select_callable'] : null;
if ($slaveSelect) {
$slave = $slaveSelect($slaves, $this->_redis);
} else {
$slaveKey = array_rand($slaves);
$slave = $slaves[$slaveKey]; /* @var $slave Credis_Client */
}
if ($slave instanceof Credis_Client && $slave !== $this->_redis) {
try {
$this->_applyClientOptions($slave, true);
$this->_slave = $slave;
} catch (Exception $e) {
// If there is a problem with first slave then skip 'load_from_slaves' option
}
}
}
}
unset($sentinel);
}
// Instantiate Credis_Cluster
// DEPRECATED
elseif (! empty($options['cluster'])) {
$this->_setupReadWriteCluster($options);
}
// Direct connection to single Redis server and optional slaves
else {
$port = $options['port'] ?? 6379;
$this->_redis = new Credis_Client($options['server'], $port, $this->_clientOptions->timeout, $this->_clientOptions->persistent);
$this->_applyClientOptions($this->_redis);
// Support loading from a replication slave
if (isset($options['load_from_slave'])) {
if (is_array($options['load_from_slave'])) {
if (isset($options['load_from_slave']['server'])) { // Single slave
$server = $options['load_from_slave']['server'];
$port = $options['load_from_slave']['port'];
$clientOptions = $this->getClientOptions($options['load_from_slave'] + $options);
$totalServers = 2;
} else { // Multiple slaves
$slaveKey = array_rand($options['load_from_slave']);
$slave = $options['load_from_slave'][$slaveKey];
$server = $slave['server'];
$port = $slave['port'];
$clientOptions = $this->getClientOptions($slave + $options);
$totalServers = count($options['load_from_slave']) + 1;
}
} else { // String
$server = $options['load_from_slave'];
$port = 6379;
$clientOptions = $this->_clientOptions;
// If multiple addresses are given, split and choose a random one
if (strpos($server, ',') !== false) {
$slaves = preg_split('/\s*,\s*/', $server, -1, PREG_SPLIT_NO_EMPTY);
$slaveKey = array_rand($slaves);
$server = $slaves[$slaveKey];
$port = null;
$totalServers = count($slaves) + 1;
} else {
$totalServers = 2;
}
}
// Skip setting up slave if master is not write only, and it is randomly chosen to be the read server
$masterWriteOnly = isset($options['master_write_only']) ? (int) $options['master_write_only'] : false;
if (is_string($server) && $server && ! (!$masterWriteOnly && rand(1, $totalServers) === 1)) {
try {
$slave = new Credis_Client($server, $port, $clientOptions->timeout, $clientOptions->persistent);
$this->_applyClientOptions($slave, true, $clientOptions);
$this->_slave = $slave;
} catch (Exception $e) {
// Slave will not be used
}
}
}
}
if (isset($options['notMatchingTags'])) {
$this->_notMatchingTags = (bool) $options['notMatchingTags'];
}
if (isset($options['compress_tags'])) {
$this->_compressTags = (int) $options['compress_tags'];
}
if (isset($options['compress_data'])) {
$this->_compressData = (int) $options['compress_data'];
}
if (isset($options['lifetimelimit'])) {
$this->_lifetimelimit = (int) min($options['lifetimelimit'], self::MAX_LIFETIME);
}
if (isset($options['compress_threshold'])) {
$this->_compressThreshold = (int) $options['compress_threshold'];
if ($this->_compressThreshold < 1) {
$this->_compressThreshold = 1;
}
}
if (isset($options['automatic_cleaning_factor'])) {
$this->_options['automatic_cleaning_factor'] = (int) $options['automatic_cleaning_factor'];
} else {
$this->_options['automatic_cleaning_factor'] = 0;
}
if (isset($options['compression_lib'])) {
$this->_compressionLib = (string) $options['compression_lib'];
} elseif (function_exists('snappy_compress')) {
$this->_compressionLib = 'snappy';
} elseif (function_exists('lz4_compress')) {
$version = phpversion("lz4");
if (version_compare($version, "0.3.0") < 0) {
$this->_compressTags = $this->_compressTags > 1;
$this->_compressData = $this->_compressData > 1;
}
$this->_compressionLib = 'l4z';
} elseif (function_exists('zstd_compress')) {
$version = phpversion("zstd");
if (version_compare($version, "0.4.13") < 0) {
$this->_compressTags = $this->_compressTags > 1;
$this->_compressData = $this->_compressData > 1;
}
$this->_compressionLib = 'zstd';
} elseif (function_exists('lzf_compress')) {
$this->_compressionLib = 'lzf';
} else {
$this->_compressionLib = 'gzip';
}
$this->_compressPrefix = substr($this->_compressionLib, 0, 2).self::COMPRESS_PREFIX;
if (isset($options['sunion_chunk_size']) && $options['sunion_chunk_size'] > 0) {
$this->_sunionChunkSize = (int) $options['sunion_chunk_size'];
}
if (isset($options['remove_chunk_size']) && $options['remove_chunk_size'] > 0) {
$this->_removeChunkSize = (int) $options['remove_chunk_size'];
}
if (isset($options['use_lua'])) {
$this->_useLua = (bool) $options['use_lua'];
}
if (isset($options['lua_max_c_stack'])) {
$this->_luaMaxCStack = (int) $options['lua_max_c_stack'];
}
if (isset($options['retry_reads_on_master'])) {
$this->_retryReadsOnMaster = (bool) $options['retry_reads_on_master'];
}
if (isset($options['auto_expire_lifetime'])) {
$this->_autoExpireLifetime = (int) $options['auto_expire_lifetime'];
}
if (isset($options['auto_expire_pattern'])) {
$this->_autoExpirePattern = (string) $options['auto_expire_pattern'];
}
if (isset($options['auto_expire_refresh_on_load'])) {
$this->_autoExpireRefreshOnLoad = (bool) $options['auto_expire_refresh_on_load'];
}
}
/**
* Apply common configuration to client instances.
*
* @param Credis_Client $client
* @param bool $forceSelect
* @param null|stdClass $clientOptions
* @throws CredisException
* @throws Zend_Cache_Exception
*/
protected function _applyClientOptions(Credis_Client $client, $forceSelect = false, $clientOptions = null)
{
if ($clientOptions === null) {
$clientOptions = $this->_clientOptions;
}
if ($clientOptions->forceStandalone) {
$client->forceStandalone();
}
$client->setMaxConnectRetries($clientOptions->connectRetries);
if ($clientOptions->readTimeout) {
$client->setReadTimeout($clientOptions->readTimeout);
}
if ($clientOptions->password) {
if ($clientOptions->username) {
$client->auth($clientOptions->password, $clientOptions->username) or Zend_Cache::throwException('Unable to authenticate with the redis server.');
} else {
$client->auth($clientOptions->password) or Zend_Cache::throwException('Unable to authenticate with the redis server.');
}
}
// Always select database when persistent is used in case connection is re-used by other clients
if ($forceSelect || $clientOptions->database || $client->getPersistence()) {
$client->select($clientOptions->database) or Zend_Cache::throwException('The redis database could not be selected.');
}
}
/**
* @param $options
* @throws CredisException
* @throws Zend_Cache_Exception
* @deprecated - Previously this setup an instance of Credis_Cluster but this class was not complete or flawed
*/
protected function _setupReadWriteCluster($options)
{
if (!empty($options['cluster']['master'])) {
foreach ($options['cluster']['master'] as $masterNode) {
if (empty($masterNode['server']) || empty($masterNode['port'])) {
continue;
}
$this->_redis = new Credis_Client(
$masterNode['host'],
$masterNode['port'],
$masterNode['timeout'] ?? 2.5,
$masterNode['persistent'] ?? ''
);
$this->_applyClientOptions($this->_redis);
break;
}
}
if (!empty($options['cluster']['slave'])) {
$slaveKey = array_rand($options['cluster']['slave']);
$slave = $options['cluster']['slave'][$slaveKey];
$this->_slave = new Credis_Client(
$slave['host'],
$slave['port'],
$slave['timeout'] ?? 2.5,
$slave['persistent'] ?? ''
);
$this->_applyClientOptions($this->_redis, true);
}
}
/**
* Load value with given id from cache
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return bool|string
* @throws CredisException
*/
public function load($id, $doNotTestCacheValidity = false)
{
if ($this->_slave) {
try {
$data = $this->_slave->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
// Prevent compounded effect of cache flood on asynchronously replicating master/slave setup
if ($this->_retryReadsOnMaster && $data === false) {
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
}
} catch (CredisException $e) {
// Always retry reads on master when dataset is loading on slave
if ($e->getMessage() === 'LOADING Redis is loading the dataset in memory') {
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
} else {
throw $e;
}
}
} else {
try {
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
} catch (CredisException $e) {
// Retry once after 1 second when dataset is loading
if ($e->getMessage() === 'LOADING Redis is loading the dataset in memory') {
sleep(1);
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
} else {
throw $e;
}
}
}
if ($data === null || $data === false || is_object($data)) {
return false;
}
$decoded = $this->_decodeData($data);
if ($this->_autoExpireLifetime === 0 || !$this->_autoExpireRefreshOnLoad) {
return $decoded;
}
$matches = $this->_matchesAutoExpiringPattern($id);
if (!$matches) {
return $decoded;
}
$this->_redis->expire(self::PREFIX_KEY.$id, min($this->_autoExpireLifetime, self::MAX_LIFETIME));
return $decoded;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return bool|int False if record is not available or "last modified" timestamp of the available cache record
*/
public function test($id)
{
// Don't use slave for this since `test` is usually used for locking
$mtime = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_MTIME);
return ($mtime ? (int)$mtime : false);
}
/**
* Get the lifetime
*
* if $specificLifetime is not false, the given specific lifetime is used
* else, the global lifetime is used
*
* @param int $specificLifetime
* @return int Cache lifetime
*/
public function getLifetime($specificLifetime)
{
// Lifetimes set via Layout XMLs get parsed as string so bool(false) becomes string("false")
if ($specificLifetime === 'false') {
$specificLifetime = false;
}
return parent::getLifetime($specificLifetime);
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param bool|int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @throws CredisException
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if (!is_array($tags)) {
$tags = $tags ? array($tags) : array();
} else {
$tags = array_flip(array_flip($tags));
}
$lifetime = $this->_getAutoExpiringLifetime($this->getLifetime($specificLifetime), $id);
$lifetime = $lifetime === null ? $lifetime : (int) $lifetime;
if ($this->_useLua) {
$sArgs = array(
self::PREFIX_KEY,
self::FIELD_DATA,
self::FIELD_TAGS,
self::FIELD_MTIME,
self::FIELD_INF,
self::SET_TAGS,
self::PREFIX_TAG_IDS,
self::SET_IDS,
$id,
$this->_encodeData($data, $this->_compressData),
$this->_encodeData(implode(',', $tags), $this->_compressTags),
time(),
$lifetime ? 0 : 1,
min($lifetime, self::MAX_LIFETIME),
$this->_notMatchingTags ? 1 : 0
);
$res = $this->_redis->evalSha(self::LUA_SAVE_SH1, $tags, $sArgs);
if (is_null($res)) {
$script =
"local oldTags = redis.call('HGET', ARGV[1]..ARGV[9], ARGV[3]) ".
"redis.call('HMSET', ARGV[1]..ARGV[9], ARGV[2], ARGV[10], ARGV[3], ARGV[11], ARGV[4], ARGV[12], ARGV[5], ARGV[13]) ".
"if (ARGV[13] == '0') then ".
"redis.call('EXPIRE', ARGV[1]..ARGV[9], ARGV[14]) ".
"end ".
"if next(KEYS) ~= nil then ".
"redis.call('SADD', ARGV[6], unpack(KEYS)) ".
"for _, tagname in ipairs(KEYS) do ".
"redis.call('SADD', ARGV[7]..tagname, ARGV[9]) ".
"end ".
"end ".
"if (ARGV[15] == '1') then ".
"redis.call('SADD', ARGV[8], ARGV[9]) ".
"end ".
"if (oldTags ~= false) then ".
"return oldTags ".
"else ".
"return '' ".
"end";
$res = $this->_redis->eval($script, $tags, $sArgs);
}
// Process removed tags if cache entry already existed
if ($res) {
$oldTags = explode(',', $this->_decodeData($res));
if ($remTags = ($oldTags ? array_diff($oldTags, $tags) : false)) {
// Update the id list for each tag
foreach ($remTags as $tag) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
}
}
return true;
}
// Get list of tags previously assigned
$oldTags = $this->_decodeData($this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_TAGS));
$oldTags = $oldTags ? explode(',', $oldTags) : array();
$this->_redis->pipeline()->multi();
// Set the data
$result = $this->_redis->hMSet(self::PREFIX_KEY.$id, array(
self::FIELD_DATA => $this->_encodeData($data, $this->_compressData),
self::FIELD_TAGS => $this->_encodeData(implode(',', $tags), $this->_compressTags),
self::FIELD_MTIME => time(),
self::FIELD_INF => is_null($lifetime) ? 1 : 0,
));
if (! $result) {
throw new CredisException("Could not set cache key $id");
}
// Set expiration if specified
if ($lifetime !== false && !is_null($lifetime)) {
$this->_redis->expire(self::PREFIX_KEY.$id, min($lifetime, self::MAX_LIFETIME));
}
// Process added tags
if ($tags) {
// Update the list with all the tags
$this->_redis->sAdd(self::SET_TAGS, $tags);
// Update the id list for each tag
foreach ($tags as $tag) {
$this->_redis->sAdd(self::PREFIX_TAG_IDS . $tag, $id);
}
}
// Process removed tags
if ($remTags = ($oldTags ? array_diff($oldTags, $tags) : false)) {
// Update the id list for each tag
foreach ($remTags as $tag) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
}
// Update the list with all the ids
if ($this->_notMatchingTags) {
$this->_redis->sAdd(self::SET_IDS, $id);
}
$this->_redis->exec();
return true;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
// Get list of tags for this id
$tags = explode(',', $this->_decodeData($this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_TAGS)));
$this->_redis->pipeline()->multi();
// Remove data
$this->_redis->unlink(self::PREFIX_KEY.$id);
// Remove id from list of all ids
if ($this->_notMatchingTags) {
$this->_redis->sRem(self::SET_IDS, $id);
}
// Update the id list for each tag
foreach ($tags as $tag) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
$result = $this->_redis->exec();
return isset($result[0]) && (bool)$result[0];
}
/**
* @param array $tags
* @throws Zend_Cache_Exception
*/
protected function _removeByNotMatchingTags($tags)
{
$ids = $this->getIdsNotMatchingTags($tags);
$this->_removeByIds($ids);
}
/**
* @param array $tags
*/
protected function _removeByMatchingTags($tags)
{
$ids = $this->getIdsMatchingTags($tags);
$this->_removeByIds($ids);
}
/**
* @param array $ids
*/
protected function _removeByIds($ids)
{
if ($ids) {
$ids = array_chunk($ids, $this->_removeChunkSize);
foreach ($ids as $idsChunk) {
$this->_redis->pipeline()->multi();
// Remove data
$this->_redis->unlink($this->_preprocessIds($idsChunk));
// Remove ids from list of all ids
if ($this->_notMatchingTags) {
$this->_redis->sRem(self::SET_IDS, $idsChunk);
}
$this->_redis->exec();
}
}
}
/**
* @param array $tags
*/
protected function _removeByMatchingAnyTags($tags)
{
if ($this->_useLua) {
$tags = array_chunk($tags, $this->_sunionChunkSize);
foreach ($tags as $chunk) {
$args = array(self::PREFIX_TAG_IDS, self::PREFIX_KEY, self::SET_TAGS, self::SET_IDS, ($this->_notMatchingTags ? 1 : 0), (int) $this->_luaMaxCStack);
if (! $this->_redis->evalSha(self::LUA_CLEAN_SH1, $chunk, $args)) {
$script =
"for i = 1, #KEYS, ARGV[6] do " .
"local prefixedTags = {} " .
"for x, tag in ipairs(KEYS) do " .
"prefixedTags[x] = ARGV[1]..tag " .
"end " .
"local keysToDel = redis.call('SUNION', unpack(prefixedTags, i, math.min(#prefixedTags, i + ARGV[6] - 1))) " .
"for _, keyname in ipairs(keysToDel) do " .
"redis.call('UNLINK', ARGV[2]..keyname) " .
"if (ARGV[5] == '1') then " .
"redis.call('SREM', ARGV[4], keyname) " .
"end " .
"end " .
"redis.call('UNLINK', unpack(prefixedTags, i, math.min(#prefixedTags, i + ARGV[6] - 1))) " .
"redis.call('SREM', ARGV[3], unpack(KEYS, i, math.min(#KEYS, i + ARGV[6] - 1))) " .
"end " .
"return true";
$this->_redis->eval($script, $chunk, $args);
}
}
return;
}
$ids = $this->getIdsMatchingAnyTags($tags);
$this->_redis->pipeline()->multi();
if ($ids) {
$ids = array_chunk($ids, $this->_removeChunkSize);
foreach ($ids as $idsChunk) {
// Remove data
$this->_redis->unlink($this->_preprocessIds($idsChunk));
// Remove ids from list of all ids
if ($this->_notMatchingTags) {
$this->_redis->sRem(self::SET_IDS, $idsChunk);
}
// Commit each chunk in a separate transaction
if (count($ids) > 1) {
$this->_redis->pipeline()->exec();
$this->_redis->pipeline()->multi();
}
}
}
// Remove tag id lists
$this->_redis->unlink($this->_preprocessTagIds($tags));
// Remove tags from list of tags
$this->_redis->sRem(self::SET_TAGS, $tags);
$this->_redis->exec();
}
/**
* Clean up tag id lists since as keys expire the ids remain in the tag id lists
*/
protected function _collectGarbage()
{
// Clean up expired keys from tag id set and global id set
if ($this->_useLua) {
$sArgs = array(self::PREFIX_KEY, self::SET_TAGS, self::SET_IDS, self::PREFIX_TAG_IDS, ($this->_notMatchingTags ? 1 : 0));
$allTags = (array) $this->_redis->sMembers(self::SET_TAGS);
$tagsCount = count($allTags);
$counter = 0;
$tagsBatch = array();
foreach ($allTags as $tag) {
$tagsBatch[] = $tag;
$counter++;
if (count($tagsBatch) == 10 || $counter == $tagsCount) {
if (! $this->_redis->evalSha(self::LUA_GC_SH1, $tagsBatch, $sArgs)) {
$script =
"local tagKeys = {} ".
"local expired = {} ".
"local expiredCount = 0 ".
"local notExpiredCount = 0 ".
"for _, tagName in ipairs(KEYS) do ".
"tagKeys = redis.call('SMEMBERS', ARGV[4]..tagName) ".
"for __, keyName in ipairs(tagKeys) do ".
"if (redis.call('EXISTS', ARGV[1]..keyName) == 0) then ".
"expiredCount = expiredCount + 1 ".
"expired[expiredCount] = keyName ".
/* Redis Lua scripts have a hard limit of 8000 parameters per command */
"if (expiredCount == 7990) then ".
"redis.call('SREM', ARGV[4]..tagName, unpack(expired)) ".
"if (ARGV[5] == '1') then ".
"redis.call('SREM', ARGV[3], unpack(expired)) ".
"end ".
"expiredCount = 0 ".
"expired = {} ".
"end ".
"else ".
"notExpiredCount = notExpiredCount + 1 ".
"end ".
"end ".
"if (expiredCount > 0) then ".
"redis.call('SREM', ARGV[4]..tagName, unpack(expired)) ".
"if (ARGV[5] == '1') then ".
"redis.call('SREM', ARGV[3], unpack(expired)) ".
"end ".
"end ".
"if (notExpiredCount == 0) then ".
"redis.call ('UNLINK', ARGV[4]..tagName) ".
"redis.call ('SREM', ARGV[2], tagName) ".
"end ".
"expired = {} ".
"expiredCount = 0 ".
"notExpiredCount = 0 ".
"end ".
"return true";
$this->_redis->eval($script, $tagsBatch, $sArgs);
}
$tagsBatch = array();
/* Give Redis some time to handle other requests */
usleep(20000);
}
}
return;
}
$exists = array();
$tags = (array) $this->_redis->sMembers(self::SET_TAGS);
foreach ($tags as $tag) {
// Get list of expired ids for each tag
$tagMembers = $this->_redis->sMembers(self::PREFIX_TAG_IDS . $tag);
$numTagMembers = count($tagMembers);
$expired = array();
$numExpired = $numNotExpired = 0;
if ($numTagMembers) {
while ($id = array_pop($tagMembers)) {
if (! isset($exists[$id])) {
$exists[$id] = $this->_redis->exists(self::PREFIX_KEY.$id);
}
if ($exists[$id]) {
$numNotExpired++;
} else {
$numExpired++;
$expired[] = $id;
// Remove incrementally to reduce memory usage
if (count($expired) % 100 == 0 && $numNotExpired > 0) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $expired);
if ($this->_notMatchingTags) { // Clean up expired ids from ids set
$this->_redis->sRem(self::SET_IDS, $expired);
}
$expired = array();
}
}
}
if (! count($expired)) {
continue;
}
}
// Remove empty tags or completely expired tags
if ($numExpired == $numTagMembers) {
$this->_redis->unlink(self::PREFIX_TAG_IDS . $tag);
$this->_redis->sRem(self::SET_TAGS, $tag);
}
// Clean up expired ids from tag ids set
elseif (count($expired)) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $expired);
if ($this->_notMatchingTags) { // Clean up expired ids from ids set
$this->_redis->sRem(self::SET_IDS, $expired);
}
}
unset($expired);
}
// TODO
// Clean up global list of ids for ids with no tag
// if ($this->_notMatchingTags) {
// }
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => runs _collectGarbage()
* 'matchingTag' => supported
* 'notMatchingTag' => supported
* 'matchingAnyTag' => supported
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if ($tags && ! is_array($tags)) {
$tags = array($tags);
}
try {
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
return $this->_redis->flushDb();
}
if ($mode == Zend_Cache::CLEANING_MODE_OLD) {
$this->_collectGarbage();
return true;
}
if (! count($tags)) {
return true;
}
switch ($mode) {
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$this->_removeByMatchingTags($tags);
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$this->_removeByNotMatchingTags($tags);
break;