(dev/core#217) Implement Redis driver for PrevNext handling
[civicrm-core.git] / CRM / Core / PrevNextCache / Redis.php
CommitLineData
751f3d98
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28/**
29 * Class CRM_Core_PrevNextCache_Memory
30 *
31 * Store the previous/next cache in a Redis set.
32 *
33 * Each logical prev-next cache corresponds to three distinct items in Redis:
34 * - "{prefix}/{qfKey}/list" - Sorted set of `entity_id`, with all entities
35 * - "{prefix}/{qfkey}/sel" - Sorted set of `entity_id`, with only entities marked by user
36 * - "{prefix}/{qfkey}/data" - Hash mapping from `entity_id` to `data`
37 *
38 * @link https://github.com/phpredis/phpredis
39 */
40class CRM_Core_PrevNextCache_Redis implements CRM_Core_PrevNextCache_Interface {
41
42 const TTL = 21600;
43
44 /**
45 * @var Redis
46 */
47 protected $redis;
48
49 /**
50 * @var string
51 */
52 protected $prefix;
53
54 /**
55 * CRM_Core_PrevNextCache_Redis constructor.
56 * @param array $settings
57 */
58 public function __construct($settings) {
59 $this->redis = CRM_Utils_Cache_Redis::connect($settings);
60 $this->prefix = isset($settings['prefix']) ? $settings['prefix'] : '';
61 $this->prefix .= \CRM_Utils_Cache::DELIMITER . 'prevnext' . \CRM_Utils_Cache::DELIMITER;
62 }
63
64 public function fillWithSql($cacheKey, $sql) {
65 $dao = CRM_Core_DAO::executeQuery($sql, [], FALSE, NULL, FALSE, TRUE, TRUE);
66 if (is_a($dao, 'DB_Error')) {
67 throw new CRM_Core_Exception($dao->message);
68 }
69
70 list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
71
72 while ($dao->fetch()) {
73 list (, $entity_id, $data) = array_values($dao->toArray());
74 $maxScore++;
75 $this->redis->zAdd($allKey, $maxScore, $entity_id);
76 $this->redis->hSet($dataKey, $entity_id, $data);
77 }
78
79 $dao->free();
80 return TRUE;
81 }
82
83 public function fillWithArray($cacheKey, $rows) {
84 list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
85
86 foreach ($rows as $row) {
87 $maxScore++;
88 $this->redis->zAdd($allKey, $maxScore, $row['entity_id1']);
89 $this->redis->hSet($dataKey, $row['entity_id1'], $row['data']);
90 }
91
92 return TRUE;
93 }
94
95 public function fetch($cacheKey, $offset, $rowCount) {
96 $allKey = $this->key($cacheKey, 'all');
97 return $this->redis->zRange($allKey, $offset, $offset + $rowCount - 1);
98 }
99
100 public function markSelection($cacheKey, $action, $ids = NULL) {
101 $allKey = $this->key($cacheKey, 'all');
102 $selKey = $this->key($cacheKey, 'sel');
103
104 if ($action === 'select') {
105 foreach ((array) $ids as $id) {
106 $score = $this->redis->zScore($allKey, $id);
107 $this->redis->zAdd($selKey, $score, $id);
108 }
109 }
110 elseif ($action === 'unselect' && $ids === NULL) {
111 $this->redis->delete($selKey);
112 $this->redis->setTimeout($selKey, self::TTL);
113 }
114 elseif ($action === 'unselect' && $ids !== NULL) {
115 foreach ((array) $ids as $id) {
116 $this->redis->zDelete($selKey, $id);
117 }
118 }
119 }
120
121 public function getSelection($cacheKey, $action = 'get') {
122 $allKey = $this->key($cacheKey, 'all');
123 $selKey = $this->key($cacheKey, 'sel');
124
125 if ($action === 'get') {
126 $result = [];
127 foreach ($this->redis->zRange($selKey, 0, -1) as $entity_id) {
128 $result[$entity_id] = 1;
129 }
130 return [$cacheKey => $result];
131 }
132 elseif ($action === 'getall') {
133 $result = [];
134 foreach ($this->redis->zRange($allKey, 0, -1) as $entity_id) {
135 $result[$entity_id] = 1;
136 }
137 return [$cacheKey => $result];
138 }
139 else {
140 throw new \CRM_Core_Exception("Unrecognized action: $action");
141 }
142 }
143
144 public function getPositions($cacheKey, $id1) {
145 $allKey = $this->key($cacheKey, 'all');
146 $dataKey = $this->key($cacheKey, 'data');
147
148 $rank = $this->redis->zRank($allKey, $id1);
149 if (!is_int($rank) || $rank < 0) {
150 return ['foundEntry' => 0];
151 }
152
153 $pos = ['foundEntry' => 1];
154
155 if ($rank > 0) {
156 $pos['prev'] = [];
157 foreach ($this->redis->zRange($allKey, $rank - 1, $rank - 1) as $value) {
158 $pos['prev']['id1'] = $value;
159 }
160 $pos['prev']['data'] = $this->redis->hGet($dataKey, $pos['prev']['id1']);
161 }
162
163 $count = $this->getCount($cacheKey);
164 if ($count > $rank + 1) {
165 $pos['next'] = [];
166 foreach ($this->redis->zRange($allKey, $rank + 1, $rank + 1) as $value) {
167 $pos['next']['id1'] = $value;
168 }
169 $pos['next']['data'] = $this->redis->hGet($dataKey, $pos['next']['id1']);
170 }
171
172 return $pos;
173 }
174
175 public function deleteItem($id = NULL, $cacheKey = NULL) {
176 if ($id === NULL && $cacheKey !== NULL) {
177 // Delete by cacheKey.
178 $allKey = $this->key($cacheKey, 'all');
179 $selKey = $this->key($cacheKey, 'sel');
180 $dataKey = $this->key($cacheKey, 'data');
181 $this->redis->delete($allKey, $selKey, $dataKey);
182 }
183 elseif ($id === NULL && $cacheKey === NULL) {
184 // Delete everything.
185 $keys = $this->redis->keys($this->prefix . '*');
186 $this->redis->del($keys);
187 }
188 elseif ($id !== NULL && $cacheKey !== NULL) {
189 // Delete a specific contact, within a specific cache.
190 $this->redis->zDelete($this->key($cacheKey, 'all'), $id);
191 $this->redis->zDelete($this->key($cacheKey, 'sel'), $id);
192 $this->redis->hDel($this->key($cacheKey, 'data'), $id);
193 }
194 elseif ($id !== NULL && $cacheKey === NULL) {
195 // Delete a specific contact, across all prevnext caches.
196 $allKeys = $this->redis->keys($this->key('*', 'all'));
197 foreach ($allKeys as $allKey) {
198 $parts = explode(\CRM_Utils_Cache::DELIMITER, $allKey);
199 array_pop($parts);
200 $tmpCacheKey = array_pop($parts);
201 $this->deleteItem($id, $tmpCacheKey);
202 }
203 }
204 else {
205 throw new CRM_Core_Exception("Not implemented: Redis::deleteItem");
206 }
207 }
208
209 public function getCount($cacheKey) {
210 $allKey = $this->key($cacheKey, 'all');
211 return $this->redis->zSize($allKey);
212 }
213
214 /**
215 * Construct the full path to a cache item.
216 *
217 * @param string $cacheKey
218 * Identifier for this saved search.
219 * Ex: 'abcd1234abcd1234'.
220 * @param string $item
221 * Ex: 'list', 'rel', 'data'.
222 * @return string
223 * Ex: 'dmaster/prevnext/abcd1234abcd1234/list'
224 */
225 private function key($cacheKey, $item) {
226 return $this->prefix . $cacheKey . \CRM_Utils_Cache::DELIMITER . $item;
227 }
228
229 /**
230 * Initialize any data-structures or timeouts for the cache-key.
231 *
232 * This is non-destructive -- if data already exists, it's preserved.
233 *
234 * @return array
235 * 0 => string $allItemsCacheKey,
236 * 1 => string $dataItemsCacheKey,
237 * 2 => string $selectedItemsCacheKey,
238 * 3 => int $maxExistingScore
239 */
240 private function initCacheKey($cacheKey) {
241 $allKey = $this->key($cacheKey, 'all');
242 $selKey = $this->key($cacheKey, 'sel');
243 $dataKey = $this->key($cacheKey, 'data');
244
245 $this->redis->setTimeout($allKey, self::TTL);
246 $this->redis->setTimeout($dataKey, self::TTL);
247 $this->redis->setTimeout($selKey, self::TTL);
248
249 $maxScore = 0;
250 foreach ($this->redis->zRange($allKey, -1, -1, TRUE) as $lastElem => $lastScore) {
251 $maxScore = $lastScore;
252 }
253 return array($allKey, $dataKey, $selKey, $maxScore);
254 }
255
256}