Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
93.67% |
681 / 727 |
|
70.69% |
41 / 58 |
CRAP | |
0.00% |
0 / 1 |
WANObjectCache | |
93.67% |
681 / 727 |
|
70.69% |
41 / 58 |
233.37 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
2 | |||
setLogger | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
newEmpty | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
get | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
4 | |||
getMulti | |
95.24% |
20 / 21 |
|
0.00% |
0 / 1 |
5 | |||
fetchKeys | |
98.53% |
67 / 68 |
|
0.00% |
0 / 1 |
17 | |||
processCheckKeys | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
4 | |||
set | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
2 | |||
setMainValue | |
98.68% |
75 / 76 |
|
0.00% |
0 / 1 |
21 | |||
delete | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
3 | |||
getCheckKeyTime | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getMultiCheckKeyTime | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
4 | |||
touchCheckKey | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
resetCheckKey | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
getWithSetCallback | |
100.00% |
23 / 23 |
|
100.00% |
1 / 1 |
8 | |||
fetchOrRegenerate | |
100.00% |
129 / 129 |
|
100.00% |
1 / 1 |
26 | |||
claimStampedeLock | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
yieldStampedeLock | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
makeSisterKeys | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
makeSisterKey | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
3.04 | |||
isExtremelyNewValue | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
getInterimValue | |
66.67% |
8 / 12 |
|
0.00% |
0 / 1 |
5.93 | |||
setInterimValue | |
91.67% |
11 / 12 |
|
0.00% |
0 / 1 |
2.00 | |||
resolveBusyValue | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
getMultiWithSetCallback | |
100.00% |
21 / 21 |
|
100.00% |
1 / 1 |
2 | |||
getMultiWithUnionSetCallback | |
90.00% |
45 / 50 |
|
0.00% |
0 / 1 |
9.08 | |||
makeGlobalKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
makeKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
hash256 | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
makeMultiKeys | |
91.67% |
11 / 12 |
|
0.00% |
0 / 1 |
5.01 | |||
multiRemap | |
40.00% |
2 / 5 |
|
0.00% |
0 / 1 |
4.94 | |||
watchErrors | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getLastError | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
30 | |||
clearLastError | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
clearProcessCache | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
useInterimHoldOffCaching | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getQoS | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
adaptiveTTL | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
getWarmupKeyMisses | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
relayVolatilePurge | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
2 | |||
relayNonVolatilePurge | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
prependRoute | |
66.67% |
2 / 3 |
|
0.00% |
0 / 1 |
2.15 | |||
scheduleAsyncRefresh | |
53.33% |
8 / 15 |
|
0.00% |
0 / 1 |
3.91 | |||
isAcceptablyFreshValue | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
4 | |||
isLotteryRefreshDue | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
worthRefreshPopular | |
54.55% |
6 / 11 |
|
0.00% |
0 / 1 |
7.35 | |||
worthRefreshExpiring | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
5 | |||
isValid | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
wrap | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
2 | |||
unwrap | |
100.00% |
28 / 28 |
|
100.00% |
1 / 1 |
6 | |||
determineKeyGroupForStats | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
parsePurgeValue | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
5.02 | |||
makeTombstonePurgeValue | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
makeCheckPurgeValue | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
getProcessCache | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
getNonProcessCachedMultiKeys | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
5 | |||
fetchWrappedValuesForWarmupCache | |
63.64% |
7 / 11 |
|
0.00% |
0 / 1 |
6.20 | |||
timeSinceLoggedMiss | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
getCurrentTime | n/a |
0 / 0 |
n/a |
0 / 0 |
2 | |||||
setMockTime | n/a |
0 / 0 |
n/a |
0 / 0 |
2 |
1 | <?php |
2 | /** |
3 | * This program is free software; you can redistribute it and/or modify |
4 | * it under the terms of the GNU General Public License as published by |
5 | * the Free Software Foundation; either version 2 of the License, or |
6 | * (at your option) any later version. |
7 | * |
8 | * This program is distributed in the hope that it will be useful, |
9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
11 | * GNU General Public License for more details. |
12 | * |
13 | * You should have received a copy of the GNU General Public License along |
14 | * with this program; if not, write to the Free Software Foundation, Inc., |
15 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
16 | * http://www.gnu.org/copyleft/gpl.html |
17 | * |
18 | * @file |
19 | * @ingroup Cache |
20 | */ |
21 | |
22 | use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface; |
23 | use Psr\Log\LoggerAwareInterface; |
24 | use Psr\Log\LoggerInterface; |
25 | use Psr\Log\NullLogger; |
26 | use Wikimedia\LightweightObjectStore\ExpirationAwareness; |
27 | use Wikimedia\LightweightObjectStore\StorageAwareness; |
28 | |
29 | /** |
30 | * Multi-datacenter aware caching interface |
31 | * |
32 | * ### Using WANObjectCache |
33 | * |
34 | * This class intends to boost performance of code paths by using cache-aside logic |
35 | * for data potentially derived from source databases subject to replication lag. Callers |
36 | * will generally make use of the getWithSetCallback() method. |
37 | * |
38 | * All operations go to the local datacenter cache, except for delete(), touchCheckKey(), |
39 | * and resetCheckKey(), which are also broadcasted to caches in all datacenters. |
40 | * |
41 | * To ensure consumers of the cache see new values in a timely manner, you need to |
42 | * follow either the validation strategy, or the purge strategy. |
43 | * |
44 | * The validation strategy refers to the natural avoidance of stale data |
45 | * by one of the following means: |
46 | * |
47 | * - A) The cached value is immutable. |
48 | * If the consumer has access to an identifier that uniquely describes a value, |
49 | * cached value need not change. Instead, the key can change. This also allows |
50 | * all servers to access their perceived current version. This is important |
51 | * in context of multiple deployed versions of your application and/or cross-dc |
52 | * database replication, to ensure deterministic values without oscillation. |
53 | * - B) Validity is checked against the source after get(). |
54 | * This is the inverse of A. The unique identifier is embedded inside the value |
55 | * and validated after on retrieval. If outdated, the value is recomputed. |
56 | * - C) The value is cached with a modest TTL (without validation). |
57 | * If value recomputation is reasonably performant, and the value is allowed to |
58 | * be stale, one should consider using TTL only – using the value's age as |
59 | * method of validation. |
60 | * |
61 | * The purge strategy refers to the approach whereby your application knows that source |
62 | * data has changed and can react by purging the relevant cache keys. Since purges are |
63 | * expensive, this strategy should be avoided if possible. The simplest purge method is |
64 | * delete(). |
65 | * |
66 | * In any case, callers must not assume that updates and purges are immediately visible |
67 | * to all application servers. It should be treated like a replica database in this regard. |
68 | * If such semantics are required, then solutions must be sought outside WANObjectCache. |
69 | * |
70 | * Note that write operations, such as set() and delete(), are allowed to return true as |
71 | * soon as the command could be sent or buffered via an open socket to the relevant cache |
72 | * backend server. If that server is a proxy, then it is responsible for detecting |
73 | * and tracking downed servers. |
74 | * |
75 | * @anchor wanobjectcache-deployment |
76 | * ### Deploying WANObjectCache |
77 | * |
78 | * There are two supported ways to set up broadcasted operations: |
79 | * |
80 | * - A) Set up mcrouter as the cache backend, with a memcached BagOStuff class for the 'cache' |
81 | * parameter, and a wildcard routing prefix for the 'broadcastRoutingPrefix' parameter. |
82 | * Configure mcrouter as follows: |
83 | * - Define a "<datacenter>" pool of memcached servers for each datacenter. |
84 | * - Define a "<datacenter>/wan" route to each datacenter, using "AllSyncRoute" for the |
85 | * routes that go to the local datacenter pool and "AllAsyncRoute" for the routes that |
86 | * go to remote datacenter pools. The child routes should use "HashRoute|<datacenter>". |
87 | * This allows for the use of a wildcard route for 'broadcastRoutingPrefix'. See |
88 | * https://github.com/facebook/mcrouter/wiki/Routing-Prefix and |
89 | * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup. |
90 | * - In order to reroute operations from "down" servers to spare ("gutter") servers, use |
91 | * "FailoverWithExptimeRoute" (failover_exptime=60) instead of "HashRoute|<datacenter>" |
92 | * in the "AllSyncRoute"/"AllAsyncRoute" child routes. |
93 | * The "gutter" pool is a set of memcached servers that only handle failover traffic. |
94 | * Such servers should be carefully spread over different rows and racks. See |
95 | * https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles#failoverroute |
96 | * - B) Set up dynomite as the cache backend, using a memcached BagOStuff class for the 'cache' |
97 | * parameter. Note that with this setup, all key setting operations will be broadcasted, |
98 | * rather than just purges. Writes will be eventually consistent via the Dynamo replication |
99 | * model. See https://github.com/Netflix/dynomite. |
100 | * |
101 | * Broadcasted operations like delete() and touchCheckKey() are intended to run |
102 | * immediately in the local datacenter and asynchronously in remote datacenters. |
103 | * |
104 | * This means that callers in all datacenters may see older values for however many |
105 | * milliseconds that the purge took to reach that datacenter. As with any cache, this |
106 | * should not be relied on for cases where reads are used to determine writes to source |
107 | * (e.g. non-cache) data stores, except when reading immutable data. |
108 | * |
109 | * Internally, access to a given key actually involves the use of one or more "sister" keys. |
110 | * A sister key is constructed by prefixing the base key with "WANCache:" (used to distinguish |
111 | * WANObjectCache formatted keys) and suffixing a colon followed by a single-character sister |
112 | * key type. The sister key types include the following: |
113 | * |
114 | * - `v`: used to store "regular" values (metadata-wrapped) and temporary purge "tombstones". |
115 | * - `t`: used to store "last purge" timestamps for "check" keys. |
116 | * - `m`: used to store temporary mutex locks to avoid cache stampedes. |
117 | * - `i`: used to store temporary interim values (metadata-wrapped) for tombstoned keys. |
118 | * - `c`: used to store temporary "cool-off" indicators, which specify a period during which |
119 | * values cannot be stored, neither regularly nor using interim keys. |
120 | * |
121 | * @ingroup Cache |
122 | * @newable |
123 | * @since 1.26 |
124 | */ |
125 | class WANObjectCache implements |
126 | ExpirationAwareness, |
127 | StorageAwareness, |
128 | IStoreKeyEncoder, |
129 | LoggerAwareInterface |
130 | { |
131 | /** @var BagOStuff The local datacenter cache */ |
132 | protected $cache; |
133 | /** @var MapCacheLRU[] Map of group PHP instance caches */ |
134 | protected $processCaches = []; |
135 | /** @var LoggerInterface */ |
136 | protected $logger; |
137 | /** @var StatsdDataFactoryInterface */ |
138 | protected $stats; |
139 | /** @var callable|null Function that takes a WAN cache callback and runs it later */ |
140 | protected $asyncHandler; |
141 | |
142 | /** |
143 | * Routing prefix for operations that should be broadcasted to all data centers. |
144 | * |
145 | * If null, the there is only one datacenter or a backend proxy broadcasts everything. |
146 | * |
147 | * @var string|null |
148 | */ |
149 | protected $broadcastRoute; |
150 | /** @var bool Whether to use "interim" caching while keys are tombstoned */ |
151 | protected $useInterimHoldOffCaching = true; |
152 | /** @var float Unix timestamp of the oldest possible valid values */ |
153 | protected $epoch; |
154 | /** @var string Stable secret used for hashing long strings into key components */ |
155 | protected $secret; |
156 | /** @var int Scheme to use for key coalescing (Hash Tags or Hash Stops) */ |
157 | protected $coalesceScheme; |
158 | |
159 | /** @var array<int,array> List of (key, UNIX timestamp) tuples for get() cache misses */ |
160 | private $missLog; |
161 | |
162 | /** @var int Callback stack depth for getWithSetCallback() */ |
163 | private $callbackDepth = 0; |
164 | /** @var mixed[] Temporary warm-up cache */ |
165 | private $warmupCache = []; |
166 | /** @var int Key fetched */ |
167 | private $warmupKeyMisses = 0; |
168 | |
169 | /** @var float|null */ |
170 | private $wallClockOverride; |
171 | |
172 | /** Max expected seconds to pass between delete() and DB commit finishing */ |
173 | private const MAX_COMMIT_DELAY = 3; |
174 | /** Max expected seconds of combined lag from replication and "view snapshots" */ |
175 | private const MAX_READ_LAG = 7; |
176 | /** Seconds to tombstone keys on delete() and to treat keys as volatile after purges */ |
177 | public const HOLDOFF_TTL = self::MAX_COMMIT_DELAY + self::MAX_READ_LAG + 1; |
178 | |
179 | /** Consider regeneration if the key will expire within this many seconds */ |
180 | private const LOW_TTL = 60; |
181 | /** Max TTL, in seconds, to store keys when a data source has high replication lag */ |
182 | public const TTL_LAGGED = 30; |
183 | |
184 | /** Expected time-till-refresh, in seconds, if the key is accessed once per second */ |
185 | private const HOT_TTR = 900; |
186 | /** Minimum key age, in seconds, for expected time-till-refresh to be considered */ |
187 | private const AGE_NEW = 60; |
188 | |
189 | /** Idiom for getWithSetCallback() meaning "no cache stampede mutex" */ |
190 | private const TSE_NONE = -1; |
191 | |
192 | /** Idiom for set()/getWithSetCallback() meaning "no post-expiration persistence" */ |
193 | public const STALE_TTL_NONE = 0; |
194 | /** Idiom for set()/getWithSetCallback() meaning "no post-expiration grace period" */ |
195 | public const GRACE_TTL_NONE = 0; |
196 | /** Idiom for delete()/touchCheckKey() meaning "no hold-off period" */ |
197 | public const HOLDOFF_TTL_NONE = 0; |
198 | |
199 | /** @var float Idiom for getWithSetCallback() meaning "no minimum required as-of timestamp" */ |
200 | public const MIN_TIMESTAMP_NONE = 0.0; |
201 | |
202 | /** Default process cache name and max key count */ |
203 | private const PC_PRIMARY = 'primary:1000'; |
204 | |
205 | /** Idiom for get()/getMulti() to return extra information by reference */ |
206 | public const PASS_BY_REF = []; |
207 | |
208 | /** Use twemproxy-style Hash Tag key scheme (e.g. "{...}") */ |
209 | private const SCHEME_HASH_TAG = 1; |
210 | /** Use mcrouter-style Hash Stop key scheme (e.g. "...|#|") */ |
211 | private const SCHEME_HASH_STOP = 2; |
212 | |
213 | /** Seconds to keep dependency purge keys around */ |
214 | private const CHECK_KEY_TTL = self::TTL_YEAR; |
215 | /** Seconds to keep interim value keys for tombstoned keys around */ |
216 | private const INTERIM_KEY_TTL = 2; |
217 | |
218 | /** Seconds to keep lock keys around */ |
219 | private const LOCK_TTL = 10; |
220 | /** Seconds to ramp up the chance of regeneration due to expected time-till-refresh */ |
221 | private const RAMPUP_TTL = 30; |
222 | |
223 | /** @var float Tiny negative float to use when CTL comes up >= 0 due to clock skew */ |
224 | private const TINY_NEGATIVE = -0.000001; |
225 | /** @var float Tiny positive float to use when using "minTime" to assert an inequality */ |
226 | private const TINY_POSITIVE = 0.000001; |
227 | |
228 | /** Min millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */ |
229 | private const RECENT_SET_LOW_MS = 50; |
230 | /** Max millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */ |
231 | private const RECENT_SET_HIGH_MS = 100; |
232 | |
233 | /** Consider value generation somewhat high if it takes this many seconds or more */ |
234 | private const GENERATION_HIGH_SEC = 0.2; |
235 | |
236 | /** Key to the tombstone entry timestamp */ |
237 | private const PURGE_TIME = 0; |
238 | /** Key to the tombstone entry hold-off TTL */ |
239 | private const PURGE_HOLDOFF = 1; |
240 | |
241 | /** Cache format version number */ |
242 | private const VERSION = 1; |
243 | |
244 | /** Version number attribute for a key; keep value for b/c (< 1.36) */ |
245 | public const KEY_VERSION = 'version'; |
246 | /** Generation completion timestamp attribute for a key; keep value for b/c (< 1.36) */ |
247 | public const KEY_AS_OF = 'asOf'; |
248 | /** Logical TTL attribute for a key */ |
249 | public const KEY_TTL = 'ttl'; |
250 | /** Remaining TTL attribute for a key; keep value for b/c (< 1.36) */ |
251 | public const KEY_CUR_TTL = 'curTTL'; |
252 | /** Tomstone timestamp attribute for a key; keep value for b/c (< 1.36) */ |
253 | public const KEY_TOMB_AS_OF = 'tombAsOf'; |
254 | /** Highest "check" key timestamp for a key; keep value for b/c (< 1.36) */ |
255 | public const KEY_CHECK_AS_OF = 'lastCKPurge'; |
256 | |
257 | /** Value for a key */ |
258 | private const RES_VALUE = 0; |
259 | /** Version number attribute for a key */ |
260 | private const RES_VERSION = 1; |
261 | /** Generation completion timestamp attribute for a key */ |
262 | private const RES_AS_OF = 2; |
263 | /** Logical TTL attribute for a key */ |
264 | private const RES_TTL = 3; |
265 | /** Tomstone timestamp attribute for a key */ |
266 | private const RES_TOMB_AS_OF = 4; |
267 | /** Highest "check" key timestamp for a key */ |
268 | private const RES_CHECK_AS_OF = 5; |
269 | /** Highest "touched" timestamp for a key */ |
270 | private const RES_TOUCH_AS_OF = 6; |
271 | /** Remaining TTL attribute for a key */ |
272 | private const RES_CUR_TTL = 7; |
273 | |
274 | /** Key to WAN cache version number; stored in blobs */ |
275 | private const FLD_FORMAT_VERSION = 0; |
276 | /** Key to the cached value; stored in blobs */ |
277 | private const FLD_VALUE = 1; |
278 | /** Key to the original TTL; stored in blobs */ |
279 | private const FLD_TTL = 2; |
280 | /** Key to the cache timestamp; stored in blobs */ |
281 | private const FLD_TIME = 3; |
282 | /** Key to the flags bit field (reserved number) */ |
283 | private const /** @noinspection PhpUnusedPrivateFieldInspection */ FLD_FLAGS = 4; |
284 | /** Key to collection cache version number; stored in blobs */ |
285 | private const FLD_VALUE_VERSION = 5; |
286 | private const /** @noinspection PhpUnusedPrivateFieldInspection */ FLD_GENERATION_TIME = 6; |
287 | |
288 | /** Single character component for value keys */ |
289 | private const TYPE_VALUE = 'v'; |
290 | /** Single character component for timestamp check keys */ |
291 | private const TYPE_TIMESTAMP = 't'; |
292 | /** Single character component for mutex lock keys */ |
293 | private const TYPE_MUTEX = 'm'; |
294 | /** Single character component for interium value keys */ |
295 | private const TYPE_INTERIM = 'i'; |
296 | |
297 | /** Value prefix of purge values */ |
298 | private const PURGE_VAL_PREFIX = 'PURGED'; |
299 | |
300 | /** |
301 | * @stable to call |
302 | * @param array $params |
303 | * - cache : BagOStuff object for a persistent cache |
304 | * - logger : LoggerInterface object |
305 | * - stats : StatsdDataFactoryInterface object |
306 | * - asyncHandler : A function that takes a callback and runs it later. If supplied, |
307 | * whenever a preemptive refresh would be triggered in getWithSetCallback(), the |
308 | * current cache value is still used instead. However, the async-handler function |
309 | * receives a WAN cache callback that, when run, will execute the value generation |
310 | * callback supplied by the getWithSetCallback() caller. The result will be saved |
311 | * as normal. The handler is expected to call the WAN cache callback at an opportune |
312 | * time (e.g. HTTP post-send), though generally within a few 100ms. [optional] |
313 | * - broadcastRoutingPrefix: a routing prefix used to broadcast certain operations to all |
314 | * datacenters; See also <https://github.com/facebook/mcrouter/wiki/Config-Files>. |
315 | * This prefix takes the form `/<datacenter>/<name of wan route>/`, where `datacenter` |
316 | * is usually a wildcard to select all matching routes (e.g. the WAN cluster in all DCs). |
317 | * See also <https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup>. |
318 | * This is required when using mcrouter as a multi-region backing store proxy. [optional] |
319 | * - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional] |
320 | * - secret: stable secret used for hashing long strings into key components. [optional] |
321 | * - coalesceScheme: which key scheme to use in order to encourage the backend to place any |
322 | * "helper" keys for a "value" key within the same cache server. This reduces network |
323 | * overhead and reduces the chance the a single downed cache server causes disruption. |
324 | * Use "hash_stop" with mcrouter and "hash_tag" with dynomite. [default: "hash_stop"] |
325 | */ |
326 | public function __construct( array $params ) { |
327 | $this->cache = $params['cache']; |
328 | $this->broadcastRoute = $params['broadcastRoutingPrefix'] ?? null; |
329 | $this->epoch = $params['epoch'] ?? 0; |
330 | $this->secret = $params['secret'] ?? (string)$this->epoch; |
331 | if ( ( $params['coalesceScheme'] ?? '' ) === 'hash_tag' ) { |
332 | // https://redis.io/topics/cluster-spec |
333 | // https://github.com/twitter/twemproxy/blob/v0.4.1/notes/recommendation.md#hash-tags |
334 | // https://github.com/Netflix/dynomite/blob/v0.7.0/notes/recommendation.md#hash-tags |
335 | $this->coalesceScheme = self::SCHEME_HASH_TAG; |
336 | } else { |
337 | // https://github.com/facebook/mcrouter/wiki/Key-syntax |
338 | $this->coalesceScheme = self::SCHEME_HASH_STOP; |
339 | } |
340 | |
341 | $this->setLogger( $params['logger'] ?? new NullLogger() ); |
342 | $this->stats = $params['stats'] ?? new NullStatsdDataFactory(); |
343 | $this->asyncHandler = $params['asyncHandler'] ?? null; |
344 | |
345 | $this->missLog = array_fill( 0, 10, [ '', 0.0 ] ); |
346 | } |
347 | |
348 | /** |
349 | * @param LoggerInterface $logger |
350 | */ |
351 | public function setLogger( LoggerInterface $logger ) { |
352 | $this->logger = $logger; |
353 | } |
354 | |
355 | /** |
356 | * Get an instance that wraps EmptyBagOStuff |
357 | * |
358 | * @return WANObjectCache |
359 | */ |
360 | public static function newEmpty() { |
361 | return new static( [ 'cache' => new EmptyBagOStuff() ] ); |
362 | } |
363 | |
364 | /** |
365 | * Fetch the value of a key from cache |
366 | * |
367 | * If supplied, $curTTL is set to the remaining TTL (current time left): |
368 | * - a) INF; if $key exists, has no TTL, and is not purged by $checkKeys |
369 | * - b) float (>=0); if $key exists, has a TTL, and is not purged by $checkKeys |
370 | * - c) float (<0); if $key is tombstoned, stale, or existing but purged by $checkKeys |
371 | * - d) null; if $key does not exist and is not tombstoned |
372 | * |
373 | * If a key is tombstoned, $curTTL will reflect the time since delete(). |
374 | * |
375 | * The timestamp of $key will be checked against the last-purge timestamp |
376 | * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge |
377 | * initialized to the current timestamp. If any of $checkKeys have a timestamp |
378 | * greater than that of $key, then $curTTL will reflect how long ago $key |
379 | * became invalid. Callers can use $curTTL to know when the value is stale. |
380 | * The $checkKeys parameter allow mass key purges by updating a single key: |
381 | * - a) Each "check" key represents "last purged" of some source data |
382 | * - b) Callers pass in relevant "check" keys as $checkKeys in get() |
383 | * - c) When the source data that "check" keys represent changes, |
384 | * the touchCheckKey() method is called on them |
385 | * |
386 | * Source data entities might exists in a DB that uses snapshot isolation |
387 | * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that |
388 | * isolation can largely be maintained by doing the following: |
389 | * - a) Calling delete() on entity change *and* creation, before DB commit |
390 | * - b) Keeping transaction duration shorter than the delete() hold-off TTL |
391 | * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls |
392 | * |
393 | * However, pre-snapshot values might still be seen if an update was made |
394 | * in a remote datacenter but the purge from delete() didn't relay yet. |
395 | * |
396 | * Consider using getWithSetCallback(), which has cache slam avoidance and key |
397 | * versioning features, instead of bare get()/set() calls. |
398 | * |
399 | * Do not use this method on versioned keys accessed via getWithSetCallback(). |
400 | * |
401 | * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF. |
402 | * In that case, it becomes a key metadata map. Otherwise, for backwards compatibility, |
403 | * $info becomes the value generation timestamp (null if the key is nonexistant/tombstoned). |
404 | * Key metadata map fields include: |
405 | * - WANObjectCache::KEY_VERSION: value version number; null if key is nonexistant |
406 | * - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if key is nonexistant |
407 | * - WANObjectCache::KEY_TTL: assigned TTL (seconds); null if key is nonexistant/tombstoned |
408 | * - WANObjectCache::KEY_CUR_TTL: remaining TTL (seconds); null if key is nonexistant |
409 | * - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if key is not tombstoned |
410 | * - WANObjectCache::KEY_CHECK_AS_OF: highest "check" key timestamp (UNIX); null if none |
411 | * |
412 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
413 | * @param float|null &$curTTL Seconds of TTL left [returned] |
414 | * @param string[] $checkKeys Map of (integer or cache key => "check" key(s)); |
415 | * "check" keys must also be made with makeKey()/makeGlobalKey() |
416 | * @param array &$info Metadata map [returned] |
417 | * @return mixed Value of cache key; false on failure |
418 | */ |
419 | final public function get( $key, &$curTTL = null, array $checkKeys = [], &$info = [] ) { |
420 | // Note that an undeclared variable passed as $info starts as null (not the default). |
421 | // Also, if no $info parameter is provided, then it doesn't matter how it changes here. |
422 | $legacyInfo = ( $info !== self::PASS_BY_REF ); |
423 | |
424 | $res = $this->fetchKeys( [ $key ], $checkKeys )[$key]; |
425 | |
426 | $curTTL = $res[self::RES_CUR_TTL]; |
427 | $info = $legacyInfo |
428 | ? $res[self::RES_AS_OF] |
429 | : [ |
430 | self::KEY_VERSION => $res[self::RES_VERSION], |
431 | self::KEY_AS_OF => $res[self::RES_AS_OF], |
432 | self::KEY_TTL => $res[self::RES_TTL], |
433 | self::KEY_CUR_TTL => $res[self::RES_CUR_TTL], |
434 | self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF], |
435 | self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF] |
436 | ]; |
437 | |
438 | if ( $curTTL === null || $curTTL <= 0 ) { |
439 | // Log the timestamp in case a corresponding set() call does not provide "walltime" |
440 | unset( $this->missLog[array_key_first( $this->missLog )] ); |
441 | $this->missLog[] = [ $key, $this->getCurrentTime() ]; |
442 | } |
443 | |
444 | return $res[self::RES_VALUE]; |
445 | } |
446 | |
447 | /** |
448 | * Fetch the value of several keys from cache |
449 | * |
450 | * $curTTLs becomes a map of only present/tombstoned $keys to their current time-to-live. |
451 | * |
452 | * $checkKeys holds the "check" keys used to validate values of applicable keys. The |
453 | * integer indexes hold "check" keys that apply to all of $keys while the string indexes |
454 | * hold "check" keys that only apply to the cache key with that name. The logic of "check" |
455 | * keys otherwise works the same as in WANObjectCache::get(). |
456 | * |
457 | * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF. |
458 | * In that case, it becomes a mapping of all the $keys to their metadata maps, each in the |
459 | * style of WANObjectCache::get(). Otherwise, for backwards compatibility, $info becomes a |
460 | * map of only present/tombstoned $keys to their value generation timestamps. |
461 | * |
462 | * @see WANObjectCache::get() |
463 | * |
464 | * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values |
465 | * @param array<string,float> &$curTTLs Map of (key => seconds of TTL left) [returned] |
466 | * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s)); |
467 | * "check" keys must also be made with makeKey()/makeGlobalKey() |
468 | * @param array<string,array> &$info Map of (key => metadata map) [returned] |
469 | * @return array<string,mixed> Map of (key => value) for existing values in order of $keys |
470 | */ |
471 | final public function getMulti( |
472 | array $keys, |
473 | &$curTTLs = [], |
474 | array $checkKeys = [], |
475 | &$info = [] |
476 | ) { |
477 | // Note that an undeclared variable passed as $info starts as null (not the default). |
478 | // Also, if no $info parameter is provided, then it doesn't matter how it changes here. |
479 | $legacyInfo = ( $info !== self::PASS_BY_REF ); |
480 | |
481 | $curTTLs = []; |
482 | $info = []; |
483 | $valuesByKey = []; |
484 | |
485 | $resByKey = $this->fetchKeys( $keys, $checkKeys ); |
486 | foreach ( $resByKey as $key => $res ) { |
487 | if ( $res[self::RES_VALUE] !== false ) { |
488 | $valuesByKey[$key] = $res[self::RES_VALUE]; |
489 | } |
490 | |
491 | if ( $res[self::RES_CUR_TTL] !== null ) { |
492 | $curTTLs[$key] = $res[self::RES_CUR_TTL]; |
493 | } |
494 | $info[$key] = $legacyInfo |
495 | ? $res[self::RES_AS_OF] |
496 | : [ |
497 | self::KEY_VERSION => $res[self::RES_VERSION], |
498 | self::KEY_AS_OF => $res[self::RES_AS_OF], |
499 | self::KEY_TTL => $res[self::RES_TTL], |
500 | self::KEY_CUR_TTL => $res[self::RES_CUR_TTL], |
501 | self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF], |
502 | self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF] |
503 | ]; |
504 | } |
505 | |
506 | return $valuesByKey; |
507 | } |
508 | |
509 | /** |
510 | * Fetch the value and key metadata of several keys from cache |
511 | * |
512 | * $checkKeys holds the "check" keys used to validate values of applicable keys. |
513 | * The integer indexes hold "check" keys that apply to all of $keys while the string |
514 | * indexes hold "check" keys that only apply to the cache key with that name. |
515 | * |
516 | * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values |
517 | * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s)); |
518 | * "check" keys must also be made with makeKey()/makeGlobalKey() |
519 | * @param callable|null $touchedCb Callback yielding a UNIX timestamp from a value, or null |
520 | * @return array<string,array> Map of (key => WANObjectCache::RESULT_* map) in order of $keys |
521 | * @note Callable type hints are not used to avoid class-autoloading |
522 | */ |
523 | protected function fetchKeys( array $keys, array $checkKeys, $touchedCb = null ) { |
524 | $resByKey = []; |
525 | |
526 | // List of all sister keys that need to be fetched from cache |
527 | $allSisterKeys = []; |
528 | // Order-corresponding value sister key list for the base key list ($keys) |
529 | $valueSisterKeys = []; |
530 | // List of "check" sister keys to compare all value sister keys against |
531 | $checkSisterKeysForAll = []; |
532 | // Map of (base key => additional "check" sister key(s) to compare against) |
533 | $checkSisterKeysByKey = []; |
534 | |
535 | foreach ( $keys as $key ) { |
536 | $sisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE ); |
537 | $allSisterKeys[] = $sisterKey; |
538 | $valueSisterKeys[] = $sisterKey; |
539 | } |
540 | |
541 | foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) { |
542 | // Note: avoid array_merge() inside loop in case there are many keys |
543 | if ( is_int( $i ) ) { |
544 | // Single "check" key that applies to all base keys |
545 | $sisterKey = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP ); |
546 | $allSisterKeys[] = $sisterKey; |
547 | $checkSisterKeysForAll[] = $sisterKey; |
548 | } else { |
549 | // List of "check" keys that apply to a specific base key |
550 | foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) { |
551 | $sisterKey = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP ); |
552 | $allSisterKeys[] = $sisterKey; |
553 | $checkSisterKeysByKey[$i][] = $sisterKey; |
554 | } |
555 | } |
556 | } |
557 | |
558 | if ( $this->warmupCache ) { |
559 | // Get the wrapped values of the sister keys from the warmup cache |
560 | $wrappedBySisterKey = $this->warmupCache; |
561 | $sisterKeysMissing = array_diff( $allSisterKeys, array_keys( $wrappedBySisterKey ) ); |
562 | if ( $sisterKeysMissing ) { |
563 | $this->warmupKeyMisses += count( $sisterKeysMissing ); |
564 | $wrappedBySisterKey += $this->cache->getMulti( $sisterKeysMissing ); |
565 | } |
566 | } else { |
567 | // Fetch the wrapped values of the sister keys from the backend |
568 | $wrappedBySisterKey = $this->cache->getMulti( $allSisterKeys ); |
569 | } |
570 | |
571 | // Pessimistically treat the "current time" as the time when any network I/O finished |
572 | $now = $this->getCurrentTime(); |
573 | |
574 | // List of "check" sister key purge timestamps to compare all value sister keys against |
575 | $ckPurgesForAll = $this->processCheckKeys( |
576 | $checkSisterKeysForAll, |
577 | $wrappedBySisterKey, |
578 | $now |
579 | ); |
580 | // Map of (base key => extra "check" sister key purge timestamp(s) to compare against) |
581 | $ckPurgesByKey = []; |
582 | foreach ( $checkSisterKeysByKey as $keyWithCheckKeys => $checkKeysForKey ) { |
583 | $ckPurgesByKey[$keyWithCheckKeys] = $this->processCheckKeys( |
584 | $checkKeysForKey, |
585 | $wrappedBySisterKey, |
586 | $now |
587 | ); |
588 | } |
589 | |
590 | // Unwrap and validate any value found for each base key (under the value sister key) |
591 | reset( $keys ); |
592 | foreach ( $valueSisterKeys as $valueSisterKey ) { |
593 | // Get the corresponding base key for this value sister key |
594 | $key = current( $keys ); |
595 | next( $keys ); |
596 | |
597 | if ( array_key_exists( $valueSisterKey, $wrappedBySisterKey ) ) { |
598 | // Key exists as either a live value or tombstone value |
599 | $wrapped = $wrappedBySisterKey[$valueSisterKey]; |
600 | } else { |
601 | // Key does not exist |
602 | $wrapped = false; |
603 | } |
604 | |
605 | $res = $this->unwrap( $wrapped, $now ); |
606 | $value = $res[self::RES_VALUE]; |
607 | |
608 | foreach ( array_merge( $ckPurgesForAll, $ckPurgesByKey[$key] ?? [] ) as $ckPurge ) { |
609 | $res[self::RES_CHECK_AS_OF] = max( |
610 | $ckPurge[self::PURGE_TIME], |
611 | $res[self::RES_CHECK_AS_OF] |
612 | ); |
613 | // Timestamp marking the end of the hold-off period for this purge |
614 | $holdoffDeadline = $ckPurge[self::PURGE_TIME] + $ckPurge[self::PURGE_HOLDOFF]; |
615 | // Check if the value was generated during the hold-off period |
616 | if ( $value !== false && $holdoffDeadline >= $res[self::RES_AS_OF] ) { |
617 | // How long ago this value was purged by *this* "check" key |
618 | $ago = min( $ckPurge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE ); |
619 | // How long ago this value was purged by *any* known "check" key |
620 | $res[self::RES_CUR_TTL] = min( $res[self::RES_CUR_TTL], $ago ); |
621 | } |
622 | } |
623 | |
624 | if ( $touchedCb !== null && $value !== false ) { |
625 | $touched = $touchedCb( $value ); |
626 | if ( $touched !== null && $touched >= $res[self::RES_AS_OF] ) { |
627 | $res[self::RES_CUR_TTL] = min( |
628 | $res[self::RES_CUR_TTL], |
629 | $res[self::RES_AS_OF] - $touched, |
630 | self::TINY_NEGATIVE |
631 | ); |
632 | } |
633 | } else { |
634 | $touched = null; |
635 | } |
636 | |
637 | $res[self::RES_TOUCH_AS_OF] = max( $res[self::RES_TOUCH_AS_OF], $touched ); |
638 | |
639 | $resByKey[$key] = $res; |
640 | } |
641 | |
642 | return $resByKey; |
643 | } |
644 | |
645 | /** |
646 | * @param string[] $checkSisterKeys List of "check" sister keys |
647 | * @param mixed[] $wrappedBySisterKey Preloaded map of (sister key => wrapped value) |
648 | * @param float $now UNIX timestamp |
649 | * @return array[] List of purge value arrays |
650 | */ |
651 | private function processCheckKeys( |
652 | array $checkSisterKeys, |
653 | array $wrappedBySisterKey, |
654 | float $now |
655 | ) { |
656 | $purges = []; |
657 | |
658 | foreach ( $checkSisterKeys as $timeKey ) { |
659 | $purge = isset( $wrappedBySisterKey[$timeKey] ) |
660 | ? $this->parsePurgeValue( $wrappedBySisterKey[$timeKey] ) |
661 | : null; |
662 | |
663 | if ( $purge === null ) { |
664 | // No holdoff when lazy creating a check key, use cache right away (T344191) |
665 | $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge ); |
666 | $this->cache->add( |
667 | $timeKey, |
668 | $wrapped, |
669 | self::CHECK_KEY_TTL, |
670 | $this->cache::WRITE_BACKGROUND |
671 | ); |
672 | } |
673 | |
674 | $purges[] = $purge; |
675 | } |
676 | |
677 | return $purges; |
678 | } |
679 | |
680 | /** |
681 | * Set the value of a key in cache |
682 | * |
683 | * Simply calling this method when source data changes is not valid because |
684 | * the changes do not replicate to the other WAN sites. In that case, delete() |
685 | * should be used instead. This method is intended for use on cache misses. |
686 | * |
687 | * If data was read using "view snapshots" (e.g. innodb REPEATABLE-READ), |
688 | * use 'since' to avoid the following race condition: |
689 | * - a) T1 starts |
690 | * - b) T2 updates a row, calls delete(), and commits |
691 | * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone |
692 | * - d) T1 reads the row and calls set() due to a cache miss |
693 | * - e) Stale value is stuck in cache |
694 | * |
695 | * Setting 'lag' and 'since' help avoids keys getting stuck in stale states. |
696 | * |
697 | * Be aware that this does not update the process cache for getWithSetCallback() |
698 | * callers. Keys accessed via that method are not generally meant to also be set |
699 | * using this primitive method. |
700 | * |
701 | * Consider using getWithSetCallback(), which has cache slam avoidance and key |
702 | * versioning features, instead of bare get()/set() calls. |
703 | * |
704 | * Do not use this method on versioned keys accessed via getWithSetCallback(). |
705 | * |
706 | * Example usage: |
707 | * @code |
708 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
709 | * $setOpts = Database::getCacheSetOptions( $dbr ); |
710 | * // Fetch the row from the DB |
711 | * $row = $dbr->selectRow( ... ); |
712 | * $key = $cache->makeKey( 'building', $buildingId ); |
713 | * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts ); |
714 | * @endcode |
715 | * |
716 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
717 | * @param mixed $value Value to set for the cache key |
718 | * @param int $ttl Seconds to live. Special values are: |
719 | * - WANObjectCache::TTL_INDEFINITE: Cache forever (default) |
720 | * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted) |
721 | * @param array $opts Options map: |
722 | * - lag: Highest seconds of replication lag potentially affecting reads used to generate |
723 | * the value. This should not be affected by the duration of transaction "view snapshots" |
724 | * (e.g. innodb REPEATABLE-READ) nor the time elapsed since the first read (though both |
725 | * increase staleness). For reads using view snapshots, only the replication lag during |
726 | * snapshot initialization matters. Use false if replication is stopped/broken on a |
727 | * replica server involved in the reads. |
728 | * Default: 0 seconds |
729 | * - since: UNIX timestamp indicative of the highest possible staleness caused by the |
730 | * duration of transaction "view snapshots" (e.g. innodb REPEATABLE-READ) and the time |
731 | * elapsed since the first read. This should not be affected by replication lag. |
732 | * Default: 0 seconds |
733 | * - pending: Whether this data is possibly from an uncommitted write transaction. |
734 | * Generally, other threads should not see values from the future and |
735 | * they certainly should not see ones that ended up getting rolled back. |
736 | * Default: false |
737 | * - lockTSE: If excessive replication/snapshot lag is detected, then store the value |
738 | * with this TTL and flag it as stale. This is only useful if the reads for this key |
739 | * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set |
740 | * then it will still add on to this TTL in the excessive lag scenario. |
741 | * Default: WANObjectCache::TSE_NONE |
742 | * - staleTTL: Seconds to keep the key around if it is stale. The get()/getMulti() |
743 | * methods return such stale values with a $curTTL of 0, and getWithSetCallback() |
744 | * will call the generation callback in such cases, passing in the old value |
745 | * and its as-of time to the callback. This is useful if adaptiveTTL() is used |
746 | * on the old value's as-of time when it is verified as still being correct. |
747 | * Default: WANObjectCache::STALE_TTL_NONE |
748 | * - segmentable: Allow partitioning of the value if it is a large string. |
749 | * Default: false. |
750 | * - creating: Optimize for the case where the key does not already exist. |
751 | * Default: false |
752 | * - version: Integer version number signifying the format of the value. |
753 | * Default: null |
754 | * - walltime: How long the value took to generate in seconds. Default: null |
755 | * @phpcs:ignore Generic.Files.LineLength |
756 | * @phan-param array{lag?:float|int,since?:float|int,pending?:bool,lockTSE?:int,staleTTL?:int,creating?:bool,version?:int,walltime?:int|float,segmentable?:bool} $opts |
757 | * @note Options added in 1.28: staleTTL |
758 | * @note Options added in 1.33: creating |
759 | * @note Options added in 1.34: version, walltime |
760 | * @note Options added in 1.40: segmentable |
761 | * @return bool Success |
762 | */ |
763 | final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) { |
764 | $keygroup = $this->determineKeyGroupForStats( $key ); |
765 | |
766 | $ok = $this->setMainValue( |
767 | $key, |
768 | $value, |
769 | $ttl, |
770 | $opts['version'] ?? null, |
771 | $opts['walltime'] ?? null, |
772 | $opts['lag'] ?? 0, |
773 | $opts['since'] ?? null, |
774 | $opts['pending'] ?? false, |
775 | $opts['lockTSE'] ?? self::TSE_NONE, |
776 | $opts['staleTTL'] ?? self::STALE_TTL_NONE, |
777 | $opts['segmentable'] ?? false, |
778 | $opts['creating'] ?? false |
779 | ); |
780 | |
781 | $this->stats->increment( "wanobjectcache.$keygroup.set." . ( $ok ? 'ok' : 'error' ) ); |
782 | |
783 | return $ok; |
784 | } |
785 | |
786 | /** |
787 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
788 | * @param mixed $value |
789 | * @param int|float $ttl |
790 | * @param int|null $version |
791 | * @param float|null $walltime |
792 | * @param float|int|bool $dataReplicaLag |
793 | * @param float|int|null $dataReadSince |
794 | * @param bool $dataPendingCommit |
795 | * @param int $lockTSE |
796 | * @param int $staleTTL |
797 | * @param bool $segmentable |
798 | * @param bool $creating |
799 | * @return bool Success |
800 | */ |
801 | private function setMainValue( |
802 | $key, |
803 | $value, |
804 | $ttl, |
805 | ?int $version, |
806 | ?float $walltime, |
807 | $dataReplicaLag, |
808 | $dataReadSince, |
809 | bool $dataPendingCommit, |
810 | int $lockTSE, |
811 | int $staleTTL, |
812 | bool $segmentable, |
813 | bool $creating |
814 | ) { |
815 | if ( $ttl < 0 ) { |
816 | // not cacheable |
817 | return true; |
818 | } |
819 | |
820 | $now = $this->getCurrentTime(); |
821 | $ttl = (int)$ttl; |
822 | $walltime ??= $this->timeSinceLoggedMiss( $key, $now ); |
823 | $dataSnapshotLag = ( $dataReadSince !== null ) ? max( 0, $now - $dataReadSince ) : 0; |
824 | $dataCombinedLag = $dataReplicaLag + $dataSnapshotLag; |
825 | |
826 | // Forbid caching data that only exists within an uncommitted transaction. Also, lower |
827 | // the TTL when the data has a "since" time so far in the past that a delete() tombstone, |
828 | // made after that time, could have already expired (the key is no longer write-holed). |
829 | // The mitigation TTL depends on whether this data lag is assumed to systemically effect |
830 | // regeneration attempts in the near future. The TTL also reflects regeneration wall time. |
831 | if ( $dataPendingCommit ) { |
832 | // Case A: data comes from an uncommitted write transaction |
833 | $mitigated = 'pending writes'; |
834 | // Data might never be committed; rely on a less problematic regeneration attempt |
835 | $mitigationTTL = self::TTL_UNCACHEABLE; |
836 | } elseif ( $dataSnapshotLag > self::MAX_READ_LAG ) { |
837 | // Case B: high snapshot lag |
838 | $pregenSnapshotLag = ( $walltime !== null ) ? ( $dataSnapshotLag - $walltime ) : 0; |
839 | if ( ( $pregenSnapshotLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) { |
840 | // Case B1: generation started when transaction duration was already long |
841 | $mitigated = 'snapshot lag (late generation)'; |
842 | // Probably non-systemic; rely on a less problematic regeneration attempt |
843 | $mitigationTTL = self::TTL_UNCACHEABLE; |
844 | } else { |
845 | // Case B2: slow generation made transaction duration long |
846 | $mitigated = 'snapshot lag (high generation time)'; |
847 | // Probably systemic; use a low TTL to avoid stampedes/uncacheability |
848 | $mitigationTTL = self::TTL_LAGGED; |
849 | } |
850 | } elseif ( $dataReplicaLag === false || $dataReplicaLag > self::MAX_READ_LAG ) { |
851 | // Case C: low/medium snapshot lag with high replication lag |
852 | $mitigated = 'replication lag'; |
853 | // Probably systemic; use a low TTL to avoid stampedes/uncacheability |
854 | $mitigationTTL = self::TTL_LAGGED; |
855 | } elseif ( $dataCombinedLag > self::MAX_READ_LAG ) { |
856 | $pregenCombinedLag = ( $walltime !== null ) ? ( $dataCombinedLag - $walltime ) : 0; |
857 | // Case D: medium snapshot lag with medium replication lag |
858 | if ( ( $pregenCombinedLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) { |
859 | // Case D1: generation started when read lag was too high |
860 | $mitigated = 'read lag (late generation)'; |
861 | // Probably non-systemic; rely on a less problematic regeneration attempt |
862 | $mitigationTTL = self::TTL_UNCACHEABLE; |
863 | } else { |
864 | // Case D2: slow generation made read lag too high |
865 | $mitigated = 'read lag (high generation time)'; |
866 | // Probably systemic; use a low TTL to avoid stampedes/uncacheability |
867 | $mitigationTTL = self::TTL_LAGGED; |
868 | } |
869 | } else { |
870 | // Case E: new value generated with recent data |
871 | $mitigated = null; |
872 | // Nothing to mitigate |
873 | $mitigationTTL = null; |
874 | } |
875 | |
876 | if ( $mitigationTTL === self::TTL_UNCACHEABLE ) { |
877 | $this->logger->warning( |
878 | "Rejected set() for {cachekey} due to $mitigated.", |
879 | [ |
880 | 'cachekey' => $key, |
881 | 'lag' => $dataReplicaLag, |
882 | 'age' => $dataSnapshotLag, |
883 | 'walltime' => $walltime |
884 | ] |
885 | ); |
886 | |
887 | // no-op the write for being unsafe |
888 | return true; |
889 | } |
890 | |
891 | // TTL to use in staleness checks (does not effect persistence layer TTL) |
892 | $logicalTTL = null; |
893 | |
894 | if ( $mitigationTTL !== null ) { |
895 | // New value was generated from data that is old enough to be risky |
896 | if ( $lockTSE >= 0 ) { |
897 | // Persist the value as long as normal, but make it count as stale sooner |
898 | $logicalTTL = min( $ttl ?: INF, $mitigationTTL ); |
899 | } else { |
900 | // Persist the value for a shorter duration |
901 | $ttl = min( $ttl ?: INF, $mitigationTTL ); |
902 | } |
903 | |
904 | $this->logger->warning( |
905 | "Lowered set() TTL for {cachekey} due to $mitigated.", |
906 | [ |
907 | 'cachekey' => $key, |
908 | 'lag' => $dataReplicaLag, |
909 | 'age' => $dataSnapshotLag, |
910 | 'walltime' => $walltime |
911 | ] |
912 | ); |
913 | } |
914 | |
915 | // Wrap that value with time/TTL/version metadata |
916 | $wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now ); |
917 | $storeTTL = $ttl + $staleTTL; |
918 | |
919 | $flags = $this->cache::WRITE_BACKGROUND; |
920 | if ( $segmentable ) { |
921 | $flags |= $this->cache::WRITE_ALLOW_SEGMENTS; |
922 | } |
923 | |
924 | if ( $creating ) { |
925 | $ok = $this->cache->add( |
926 | $this->makeSisterKey( $key, self::TYPE_VALUE ), |
927 | $wrapped, |
928 | $storeTTL, |
929 | $flags |
930 | ); |
931 | } else { |
932 | $ok = $this->cache->merge( |
933 | $this->makeSisterKey( $key, self::TYPE_VALUE ), |
934 | static function ( $cache, $key, $cWrapped ) use ( $wrapped ) { |
935 | // A string value means that it is a tombstone; do nothing in that case |
936 | return ( is_string( $cWrapped ) ) ? false : $wrapped; |
937 | }, |
938 | $storeTTL, |
939 | $this->cache::MAX_CONFLICTS_ONE, |
940 | $flags |
941 | ); |
942 | } |
943 | |
944 | return $ok; |
945 | } |
946 | |
947 | /** |
948 | * Purge a key from all datacenters |
949 | * |
950 | * This should only be called when the underlying data (being cached) |
951 | * changes in a significant way. This deletes the key and starts a hold-off |
952 | * period where the key cannot be written to for a few seconds (HOLDOFF_TTL). |
953 | * This is done to avoid the following race condition: |
954 | * - a) Some DB data changes and delete() is called on a corresponding key |
955 | * - b) A request refills the key with a stale value from a lagged DB |
956 | * - c) The stale value is stuck there until the key is expired/evicted |
957 | * |
958 | * This is implemented by storing a special "tombstone" value at the cache |
959 | * key that this class recognizes; get() calls will return false for the key |
960 | * and any set() calls will refuse to replace tombstone values at the key. |
961 | * For this to always avoid stale value writes, the following must hold: |
962 | * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or |
963 | * - b) If lag is higher, the DB will have gone into read-only mode already |
964 | * |
965 | * Note that set() can also be lag-aware and lower the TTL if it's high. |
966 | * |
967 | * Be aware that this does not clear the process cache. Even if it did, callbacks |
968 | * used by getWithSetCallback() might still return stale data in the case of either |
969 | * uncommitted or not-yet-replicated changes (callback generally use replica DBs). |
970 | * |
971 | * When using potentially long-running ACID transactions, a good pattern is |
972 | * to use a pre-commit hook to issue the delete. This means that immediately |
973 | * after commit, callers will see the tombstone in cache upon purge relay. |
974 | * It also avoids the following race condition: |
975 | * - a) T1 begins, changes a row, and calls delete() |
976 | * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone |
977 | * - c) T2 starts, reads the row and calls set() due to a cache miss |
978 | * - d) T1 finally commits |
979 | * - e) Stale value is stuck in cache |
980 | * |
981 | * Example usage: |
982 | * @code |
983 | * $dbw->startAtomic( __METHOD__ ); // start of request |
984 | * ... <execute some stuff> ... |
985 | * // Update the row in the DB |
986 | * $dbw->update( ... ); |
987 | * $key = $cache->makeKey( 'homes', $homeId ); |
988 | * // Purge the corresponding cache entry just before committing |
989 | * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) { |
990 | * $cache->delete( $key ); |
991 | * } ); |
992 | * ... <execute some stuff> ... |
993 | * $dbw->endAtomic( __METHOD__ ); // end of request |
994 | * @endcode |
995 | * |
996 | * The $ttl parameter can be used when purging values that have not actually changed |
997 | * recently. For example, user-requested purges or cache cleanup scripts might not need |
998 | * to invoke a hold-off period on cache backfills, so they can use HOLDOFF_TTL_NONE. |
999 | * |
1000 | * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback(). |
1001 | * |
1002 | * If called twice on the same key, then the last hold-off TTL takes precedence. For |
1003 | * idempotence, the $ttl should not vary for different delete() calls on the same key. |
1004 | * |
1005 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1006 | * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL |
1007 | * @return bool True if the item was purged or not found, false on failure |
1008 | */ |
1009 | final public function delete( $key, $ttl = self::HOLDOFF_TTL ) { |
1010 | // Purge values must be stored under the value key so that WANObjectCache::set() |
1011 | // can atomically merge values without accidentally undoing a recent purge and thus |
1012 | // violating the holdoff TTL restriction. |
1013 | $valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE ); |
1014 | |
1015 | if ( $ttl <= 0 ) { |
1016 | // A client or cache cleanup script is requesting a cache purge, so there is no |
1017 | // volatility period due to replica DB lag. Any recent change to an entity cached |
1018 | // in this key should have triggered an appropriate purge event. |
1019 | $ok = $this->relayNonVolatilePurge( $valueSisterKey ); |
1020 | } else { |
1021 | // A cacheable entity recently changed, so there might be a volatility period due |
1022 | // to replica DB lag. Clients usually expect their actions to be reflected in any |
1023 | // of their subsequent web request. This is attainable if (a) purge relay lag is |
1024 | // lower than the time it takes for subsequent request by the client to arrive, |
1025 | // and, (b) DB replica queries have "read-your-writes" consistency due to DB lag |
1026 | // mitigation systems. |
1027 | $now = $this->getCurrentTime(); |
1028 | // Set the key to the purge value in all datacenters |
1029 | $purge = $this->makeTombstonePurgeValue( $now ); |
1030 | $ok = $this->relayVolatilePurge( $valueSisterKey, $purge, $ttl ); |
1031 | } |
1032 | |
1033 | $keygroup = $this->determineKeyGroupForStats( $key ); |
1034 | $this->stats->increment( "wanobjectcache.$keygroup.delete." . ( $ok ? 'ok' : 'error' ) ); |
1035 | |
1036 | return $ok; |
1037 | } |
1038 | |
1039 | /** |
1040 | * Fetch the value of a timestamp "check" key |
1041 | * |
1042 | * The key will be *initialized* to the current time if not set, |
1043 | * so only call this method if this behavior is actually desired |
1044 | * |
1045 | * The timestamp can be used to check whether a cached value is valid. |
1046 | * Callers should not assume that this returns the same timestamp in |
1047 | * all datacenters due to relay delays. |
1048 | * |
1049 | * The level of staleness can roughly be estimated from this key, but |
1050 | * if the key was evicted from cache, such calculations may show the |
1051 | * time since expiry as ~0 seconds. |
1052 | * |
1053 | * Note that "check" keys won't collide with other regular keys. |
1054 | * |
1055 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1056 | * @return float UNIX timestamp |
1057 | */ |
1058 | final public function getCheckKeyTime( $key ) { |
1059 | return $this->getMultiCheckKeyTime( [ $key ] )[$key]; |
1060 | } |
1061 | |
1062 | /** |
1063 | * Fetch the values of each timestamp "check" key |
1064 | * |
1065 | * This works like getCheckKeyTime() except it takes a list of keys |
1066 | * and returns a map of timestamps instead of just that of one key |
1067 | * |
1068 | * This might be useful if both: |
1069 | * - a) a class of entities each depend on hundreds of other entities |
1070 | * - b) these other entities are depended upon by millions of entities |
1071 | * |
1072 | * The later entities can each use a "check" key to purge their dependee entities. |
1073 | * However, it is expensive for the former entities to verify against all of the relevant |
1074 | * "check" keys during each getWithSetCallback() call. A less expensive approach is to do |
1075 | * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle |
1076 | * ground between using blind TTLs and using constant verification. The adaptiveTTL() method |
1077 | * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the |
1078 | * last-modified times of the dependent entities (either from the DB or the "check" keys). |
1079 | * |
1080 | * Example usage: |
1081 | * @code |
1082 | * $value = $cache->getWithSetCallback( |
1083 | * $cache->makeGlobalKey( 'wikibase-item', $id ), |
1084 | * self::INITIAL_TTV, // initial time-till-verify |
1085 | * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) { |
1086 | * $now = microtime( true ); |
1087 | * // Use $oldValue if it passes max ultimate age and "check" key comparisons |
1088 | * if ( $oldValue && |
1089 | * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) && |
1090 | * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE |
1091 | * ) { |
1092 | * // Increase time-till-verify by 50% of last time to reduce overhead |
1093 | * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 ); |
1094 | * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data |
1095 | * return $oldValue; |
1096 | * } |
1097 | * |
1098 | * $mtimes = []; // dependency last-modified times; passed by reference |
1099 | * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ]; |
1100 | * // Guess time-till-change among the dependencies, e.g. 1/(total change rate) |
1101 | * $ttc = 1 / array_sum( array_map( |
1102 | * function ( $mtime ) use ( $now ) { |
1103 | * return 1 / ( $mtime ? ( $now - $mtime ) : 900 ); |
1104 | * }, |
1105 | * $mtimes |
1106 | * ) ); |
1107 | * // The time-to-verify should not be overly pessimistic nor optimistic |
1108 | * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV ); |
1109 | * |
1110 | * return $value; |
1111 | * }, |
1112 | * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save |
1113 | * ); |
1114 | * @endcode |
1115 | * |
1116 | * @see WANObjectCache::getCheckKeyTime() |
1117 | * @see WANObjectCache::getWithSetCallback() |
1118 | * |
1119 | * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey() |
1120 | * @return float[] Map of (key => UNIX timestamp) |
1121 | * @since 1.31 |
1122 | */ |
1123 | final public function getMultiCheckKeyTime( array $keys ) { |
1124 | $checkSisterKeysByKey = []; |
1125 | foreach ( $keys as $key ) { |
1126 | $checkSisterKeysByKey[$key] = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP ); |
1127 | } |
1128 | |
1129 | $wrappedBySisterKey = $this->cache->getMulti( $checkSisterKeysByKey ); |
1130 | $wrappedBySisterKey += array_fill_keys( $checkSisterKeysByKey, false ); |
1131 | |
1132 | $now = $this->getCurrentTime(); |
1133 | $times = []; |
1134 | foreach ( $checkSisterKeysByKey as $key => $checkSisterKey ) { |
1135 | $purge = $this->parsePurgeValue( $wrappedBySisterKey[$checkSisterKey] ); |
1136 | if ( $purge === null ) { |
1137 | $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge ); |
1138 | $this->cache->add( |
1139 | $checkSisterKey, |
1140 | $wrapped, |
1141 | self::CHECK_KEY_TTL, |
1142 | $this->cache::WRITE_BACKGROUND |
1143 | ); |
1144 | } |
1145 | |
1146 | $times[$key] = $purge[self::PURGE_TIME]; |
1147 | } |
1148 | |
1149 | return $times; |
1150 | } |
1151 | |
1152 | /** |
1153 | * Increase the last-purge timestamp of a "check" key in all datacenters |
1154 | * |
1155 | * This method should only be called when some heavily referenced data changes in |
1156 | * a significant way, such that it is impractical to call delete() on all the cache |
1157 | * keys that should be purged. The get*() method calls used to fetch these keys must |
1158 | * include the given "check" key in the relevant "check" keys argument/option. |
1159 | * |
1160 | * A "check" key essentially represents a last-modified time of an entity. When the |
1161 | * key is touched, the timestamp will be updated to the current time. Keys fetched |
1162 | * using get*() calls, that include the "check" key, will be seen as purged. |
1163 | * |
1164 | * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the |
1165 | * future by get*() methods in order to avoid race conditions where keys are updated |
1166 | * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check" |
1167 | * key, making it possible to know the timestamp of the last change to the corresponding |
1168 | * entities in most cases. This might use more cache space than resetCheckKey(). |
1169 | * |
1170 | * When a few important keys get a large number of hits, a high cache time is usually |
1171 | * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate |
1172 | * in such cases since the "time since expiry" cannot be inferred, causing any get() |
1173 | * after the reset to treat the key as being "hot", resulting in more stale value usage. |
1174 | * |
1175 | * Note that "check" keys won't collide with other regular keys. |
1176 | * |
1177 | * @see WANObjectCache::get() |
1178 | * @see WANObjectCache::getWithSetCallback() |
1179 | * @see WANObjectCache::resetCheckKey() |
1180 | * |
1181 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1182 | * @param int $holdoff HOLDOFF_TTL or HOLDOFF_TTL_NONE constant |
1183 | * @return bool True if the item was purged or not found, false on failure |
1184 | */ |
1185 | final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) { |
1186 | $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP ); |
1187 | |
1188 | $now = $this->getCurrentTime(); |
1189 | $purge = $this->makeCheckPurgeValue( $now, $holdoff ); |
1190 | $ok = $this->relayVolatilePurge( $checkSisterKey, $purge, self::CHECK_KEY_TTL ); |
1191 | |
1192 | $keygroup = $this->determineKeyGroupForStats( $key ); |
1193 | $this->stats->increment( "wanobjectcache.$keygroup.ck_touch." . ( $ok ? 'ok' : 'error' ) ); |
1194 | |
1195 | return $ok; |
1196 | } |
1197 | |
1198 | /** |
1199 | * Clear the last-purge timestamp of a "check" key in all datacenters |
1200 | * |
1201 | * Similar to touchCheckKey(), in that keys fetched using get*() calls, that include |
1202 | * the given "check" key, will be seen as purged. However, there are some differences: |
1203 | * - a) The "check" key will be deleted from all caches and lazily |
1204 | * re-initialized when accessed (rather than set everywhere) |
1205 | * - b) Thus, dependent keys will be known to be stale, but not |
1206 | * for how long (they are treated as "just" purged), which |
1207 | * effects any lockTSE logic in getWithSetCallback() |
1208 | * - c) Since "check" keys are initialized only on the server the key hashes |
1209 | * to, any temporary ejection of that server will cause the value to be |
1210 | * seen as purged as a new server will initialize the "check" key. |
1211 | * |
1212 | * The advantage over touchCheckKey() is that the "check" keys, which have high TTLs, |
1213 | * will only be created when a get*() method actually uses those keys. This is better |
1214 | * when a large number of "check" keys must be changed in a short period of time. |
1215 | * |
1216 | * Note that "check" keys won't collide with other regular keys. |
1217 | * |
1218 | * @see WANObjectCache::get() |
1219 | * @see WANObjectCache::getWithSetCallback() |
1220 | * @see WANObjectCache::touchCheckKey() |
1221 | * |
1222 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1223 | * @return bool True if the item was purged or not found, false on failure |
1224 | */ |
1225 | final public function resetCheckKey( $key ) { |
1226 | $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP ); |
1227 | $ok = $this->relayNonVolatilePurge( $checkSisterKey ); |
1228 | |
1229 | $keygroup = $this->determineKeyGroupForStats( $key ); |
1230 | $this->stats->increment( "wanobjectcache.$keygroup.ck_reset." . ( $ok ? 'ok' : 'error' ) ); |
1231 | |
1232 | return $ok; |
1233 | } |
1234 | |
1235 | /** |
1236 | * Method to fetch/regenerate a cache key |
1237 | * |
1238 | * On cache miss, the key will be set to the callback result via set() |
1239 | * (unless the callback returns false) and that result will be returned. |
1240 | * The arguments supplied to the callback are: |
1241 | * - $oldValue: prior cache value or false if none was present |
1242 | * - &$ttl: alterable reference to the TTL to be assigned to the new value |
1243 | * - &$setOpts: alterable reference to the set() options to be used with the new value |
1244 | * - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present (since 1.28) |
1245 | * - $params: custom field/value map as defined by $cbParams (since 1.35) |
1246 | * |
1247 | * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions |
1248 | * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current |
1249 | * value, but it can be used to maintain "most recent X" values that come from time or |
1250 | * sequence based source data, provided that the "as of" id/time is tracked. Note that |
1251 | * preemptive regeneration and $checkKeys can result in a non-false current value. |
1252 | * |
1253 | * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller |
1254 | * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache |
1255 | * regeneration will automatically be triggered using the callback. |
1256 | * |
1257 | * The $ttl argument and "hotTTR" option (in $opts) use time-dependent randomization |
1258 | * to avoid stampedes. Keys that are slow to regenerate and either heavily used |
1259 | * or subject to explicit (unpredictable) purges, may need additional mechanisms. |
1260 | * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts). |
1261 | * If explicit purges are needed, also: |
1262 | * - a) Pass $key into $checkKeys |
1263 | * - b) Use touchCheckKey( $key ) instead of delete( $key ) |
1264 | * |
1265 | * This applies cache server I/O stampede protection against duplicate cache sets. |
1266 | * This is important when the callback is slow and/or yields large values for a key. |
1267 | * |
1268 | * Example usage (typical key): |
1269 | * @code |
1270 | * $catInfo = $cache->getWithSetCallback( |
1271 | * // Key to store the cached value under |
1272 | * $cache->makeKey( 'cat-attributes', $catId ), |
1273 | * // Time-to-live (in seconds) |
1274 | * $cache::TTL_MINUTE, |
1275 | * // Function that derives the new key value |
1276 | * function ( $oldValue, &$ttl, array &$setOpts ) { |
1277 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1278 | * // Account for any snapshot/replica DB lag |
1279 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1280 | * |
1281 | * return $dbr->selectRow( ... ); |
1282 | * } |
1283 | * ); |
1284 | * @endcode |
1285 | * |
1286 | * Example usage (key that is expensive and hot): |
1287 | * @code |
1288 | * $catConfig = $cache->getWithSetCallback( |
1289 | * // Key to store the cached value under |
1290 | * $cache->makeKey( 'site-cat-config' ), |
1291 | * // Time-to-live (in seconds) |
1292 | * $cache::TTL_DAY, |
1293 | * // Function that derives the new key value |
1294 | * function ( $oldValue, &$ttl, array &$setOpts ) { |
1295 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1296 | * // Account for any snapshot/replica DB lag |
1297 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1298 | * |
1299 | * return CatConfig::newFromRow( $dbr->selectRow( ... ) ); |
1300 | * }, |
1301 | * [ |
1302 | * // Calling touchCheckKey() on this key purges the cache |
1303 | * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ], |
1304 | * // Try to only let one datacenter thread manage cache updates at a time |
1305 | * 'lockTSE' => 30, |
1306 | * // Avoid querying cache servers multiple times in a web request |
1307 | * 'pcTTL' => $cache::TTL_PROC_LONG |
1308 | * ] |
1309 | * ); |
1310 | * @endcode |
1311 | * |
1312 | * Example usage (key with dynamic dependencies): |
1313 | * @code |
1314 | * $catState = $cache->getWithSetCallback( |
1315 | * // Key to store the cached value under |
1316 | * $cache->makeKey( 'cat-state', $cat->getId() ), |
1317 | * // Time-to-live (seconds) |
1318 | * $cache::TTL_HOUR, |
1319 | * // Function that derives the new key value |
1320 | * function ( $oldValue, &$ttl, array &$setOpts ) { |
1321 | * // Determine new value from the DB |
1322 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1323 | * // Account for any snapshot/replica DB lag |
1324 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1325 | * |
1326 | * return CatState::newFromResults( $dbr->select( ... ) ); |
1327 | * }, |
1328 | * [ |
1329 | * // The "check" keys that represent things the value depends on; |
1330 | * // Calling touchCheckKey() on any of them purges the cache |
1331 | * 'checkKeys' => [ |
1332 | * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ), |
1333 | * $cache->makeKey( 'people-present', $cat->getHouseId() ), |
1334 | * $cache->makeKey( 'cat-laws', $cat->getCityId() ), |
1335 | * ] |
1336 | * ] |
1337 | * ); |
1338 | * @endcode |
1339 | * |
1340 | * Example usage (key that is expensive with too many DB dependencies for "check" keys): |
1341 | * @code |
1342 | * $catToys = $cache->getWithSetCallback( |
1343 | * // Key to store the cached value under |
1344 | * $cache->makeKey( 'cat-toys', $catId ), |
1345 | * // Time-to-live (seconds) |
1346 | * $cache::TTL_HOUR, |
1347 | * // Function that derives the new key value |
1348 | * function ( $oldValue, &$ttl, array &$setOpts ) { |
1349 | * // Determine new value from the DB |
1350 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1351 | * // Account for any snapshot/replica DB lag |
1352 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1353 | * |
1354 | * return CatToys::newFromResults( $dbr->select( ... ) ); |
1355 | * }, |
1356 | * [ |
1357 | * // Get the highest timestamp of any of the cat's toys |
1358 | * 'touchedCallback' => function ( $value ) use ( $catId ) { |
1359 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1360 | * $ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... ); |
1361 | * |
1362 | * return wfTimestampOrNull( TS_UNIX, $ts ); |
1363 | * }, |
1364 | * // Avoid DB queries for repeated access |
1365 | * 'pcTTL' => $cache::TTL_PROC_SHORT |
1366 | * ] |
1367 | * ); |
1368 | * @endcode |
1369 | * |
1370 | * Example usage (hot key holding most recent 100 events): |
1371 | * @code |
1372 | * $lastCatActions = $cache->getWithSetCallback( |
1373 | * // Key to store the cached value under |
1374 | * $cache->makeKey( 'cat-last-actions', 100 ), |
1375 | * // Time-to-live (in seconds) |
1376 | * 10, |
1377 | * // Function that derives the new key value |
1378 | * function ( $oldValue, &$ttl, array &$setOpts ) { |
1379 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1380 | * // Account for any snapshot/replica DB lag |
1381 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1382 | * |
1383 | * // Start off with the last cached list |
1384 | * $list = $oldValue ?: []; |
1385 | * // Fetch the last 100 relevant rows in descending order; |
1386 | * // only fetch rows newer than $list[0] to reduce scanning |
1387 | * $rows = iterator_to_array( $dbr->select( ... ) ); |
1388 | * // Merge them and get the new "last 100" rows |
1389 | * return array_slice( array_merge( $new, $list ), 0, 100 ); |
1390 | * }, |
1391 | * [ |
1392 | * // Try to only let one datacenter thread manage cache updates at a time |
1393 | * 'lockTSE' => 30, |
1394 | * // Use a magic value when no cache value is ready rather than stampeding |
1395 | * 'busyValue' => 'computing' |
1396 | * ] |
1397 | * ); |
1398 | * @endcode |
1399 | * |
1400 | * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with |
1401 | * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated |
1402 | * cache evictions and wasted memory): |
1403 | * @code |
1404 | * $catSituationTolerabilityCache = $this->cache->getWithSetCallback( |
1405 | * // Group by constraint ID/hash, cat family ID/hash, or something else useful |
1406 | * $this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ), |
1407 | * WANObjectCache::TTL_DAY, // rarely used groups should fade away |
1408 | * // The $scenarioKey format is $constraintId:<ID/hash of $situation> |
1409 | * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) { |
1410 | * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE ); |
1411 | * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present |
1412 | * if ( $result === null || $this->isScenarioResultExpired( $result ) ) { |
1413 | * $result = $this->checkScenarioTolerability( $constraintId, $situation ); |
1414 | * $lruCache->set( $scenarioKey, $result, 3 / 8 ); |
1415 | * } |
1416 | * // Save the new LRU cache map and reset the map's TTL |
1417 | * return $lruCache->toArray(); |
1418 | * }, |
1419 | * [ |
1420 | * // Once map is > 1 sec old, consider refreshing |
1421 | * 'ageNew' => 1, |
1422 | * // Update within 5 seconds after "ageNew" given a 1hz cache check rate |
1423 | * 'hotTTR' => 5, |
1424 | * // Avoid querying cache servers multiple times in a request; this also means |
1425 | * // that a request can only alter the value of any given constraint key once |
1426 | * 'pcTTL' => WANObjectCache::TTL_PROC_LONG |
1427 | * ] |
1428 | * ); |
1429 | * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] ) |
1430 | * ? $catSituationTolerabilityCache[$scenarioKey] |
1431 | * : $this->checkScenarioTolerability( $constraintId, $situation ); |
1432 | * @endcode |
1433 | * |
1434 | * @see WANObjectCache::get() |
1435 | * @see WANObjectCache::set() |
1436 | * |
1437 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1438 | * @param int $ttl Nominal seconds-to-live for newly computed values. Special values are: |
1439 | * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions) |
1440 | * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted) |
1441 | * @param callable $callback Value generation function |
1442 | * @param array $opts Options map: |
1443 | * - checkKeys: List of "check" keys. The key at $key will be seen as stale when either |
1444 | * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This |
1445 | * is useful if thousands or millions of keys depend on the same entity. The entity can |
1446 | * simply have its "check" key updated whenever the entity is modified. |
1447 | * Default: []. |
1448 | * - graceTTL: If the key is stale due to a purge (by "checkKeys" or "touchedCallback") |
1449 | * less than this many seconds ago, consider reusing the stale value. The odds of a |
1450 | * refresh become more likely over time, becoming certain once the grace period is |
1451 | * reached. This can reduce traffic spikes when millions of keys are compared to the |
1452 | * same "check" key and touchCheckKey() or resetCheckKey() is called on that "check" key. |
1453 | * This option is not useful for avoiding traffic spikes in the case of the key simply |
1454 | * expiring on account of its TTL (use "lowTTL" instead). |
1455 | * Default: WANObjectCache::GRACE_TTL_NONE. |
1456 | * - lockTSE: If the value is stale and the "time since expiry" (TSE) is less than the given |
1457 | * number of seconds ago, then reuse the stale value if another such thread is already |
1458 | * regenerating the value. The TSE of the key is influenced by purges (e.g. via delete(), |
1459 | * "checkKeys", "touchedCallback"), and various other options (e.g. "staleTTL"). A low |
1460 | * enough TSE is assumed to indicate a high enough key access rate to justify stampede |
1461 | * avoidance. Note that no cache value exists after deletion, expiration, or eviction |
1462 | * at the storage-layer; to prevent stampedes during these cases, use "busyValue". |
1463 | * Default: WANObjectCache::TSE_NONE. |
1464 | * - busyValue: Specify a placeholder value to use when no value exists and another thread |
1465 | * is currently regenerating it. This assures that cache stampedes cannot happen if the |
1466 | * value falls out of cache. This also mitigates stampedes when value regeneration |
1467 | * becomes very slow (greater than $ttl/"lowTTL"). If this is a closure, then it will |
1468 | * be invoked to get the placeholder when needed. |
1469 | * Default: null. |
1470 | * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids |
1471 | * network I/O when a key is read several times. This will not cache when the callback |
1472 | * returns false, however. Note that any purges will not be seen while process cached; |
1473 | * since the callback should use replica DBs and they may be lagged or have snapshot |
1474 | * isolation anyway, this should not typically matter. |
1475 | * Default: WANObjectCache::TTL_UNCACHEABLE. |
1476 | * - pcGroup: Process cache group to use instead of the primary one. If set, this must be |
1477 | * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing |
1478 | * large values, small yet numerous values, or some values with a high cost of eviction. |
1479 | * It is generally preferable to use a class constant when setting this value. |
1480 | * This has no effect unless pcTTL is used. |
1481 | * Default: WANObjectCache::PC_PRIMARY. |
1482 | * - version: Integer version number. This lets callers make breaking changes to the format |
1483 | * of cached values without causing problems for sites that use non-instantaneous code |
1484 | * deployments. Old and new code will recognize incompatible versions and purges from |
1485 | * both old and new code will been seen by each other. When this method encounters an |
1486 | * incompatibly versioned value at the provided key, a "variant key" will be used for |
1487 | * reading from and saving to cache. The variant key is specific to the key and version |
1488 | * number provided to this method. If the variant key value is older than that of the |
1489 | * provided key, or the provided key is non-existant, then the variant key will be seen |
1490 | * as non-existant. Therefore, delete() calls purge the provided key's variant keys. |
1491 | * The "checkKeys" and "touchedCallback" options still apply to variant keys as usual. |
1492 | * Avoid storing class objects, as this reduces compatibility (due to serialization). |
1493 | * Default: null. |
1494 | * - minAsOf: Reject values if they were generated before this UNIX timestamp. |
1495 | * This is useful if the source of a key is suspected of having possibly changed |
1496 | * recently, and the caller wants any such changes to be reflected. |
1497 | * Default: WANObjectCache::MIN_TIMESTAMP_NONE. |
1498 | * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per |
1499 | * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this |
1500 | * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old. |
1501 | * This uses randomization to avoid triggering cache stampedes. The TTR is useful at |
1502 | * reducing the impact of missed cache purges, since the effect of a heavily referenced |
1503 | * key being stale is worse than that of a rarely referenced key. Unlike simply lowering |
1504 | * $ttl, seldomly used keys are largely unaffected by this option, which makes it |
1505 | * possible to have a high hit rate for the "long-tail" of less-used keys. |
1506 | * Default: WANObjectCache::HOT_TTR. |
1507 | * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less |
1508 | * than this. It becomes more likely over time, becoming certain once the key is expired. |
1509 | * This helps avoid cache stampedes that might be triggered due to the key expiring. |
1510 | * Default: WANObjectCache::LOW_TTL. |
1511 | * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds. |
1512 | * Default: WANObjectCache::AGE_NEW. |
1513 | * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache |
1514 | * miss the callback may get $oldValue/$oldAsOf values for keys that have already been |
1515 | * expired for this specified time. This is useful if adaptiveTTL() is used on the old |
1516 | * value's as-of time when it is verified as still being correct. |
1517 | * Default: WANObjectCache::STALE_TTL_NONE |
1518 | * - touchedCallback: A callback that takes the current value and returns a UNIX timestamp |
1519 | * indicating the last time a dynamic dependency changed. Null can be returned if there |
1520 | * are no relevant dependency changes to check. This can be used to check against things |
1521 | * like last-modified times of files or DB timestamp fields. This should generally not be |
1522 | * used for small and easily queried values in a DB if the callback itself ends up doing |
1523 | * a similarly expensive DB query to check a timestamp. Usages of this option makes the |
1524 | * most sense for values that are moderately to highly expensive to regenerate and easy |
1525 | * to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries. |
1526 | * Default: null. |
1527 | * @param array $cbParams Custom field/value map to pass to the callback (since 1.35) |
1528 | * @phpcs:ignore Generic.Files.LineLength |
1529 | * @phan-param array{checkKeys?:string[],graceTTL?:int,lockTSE?:int,busyValue?:mixed,pcTTL?:int,pcGroup?:string,version?:int,minAsOf?:float|int,hotTTR?:int,lowTTL?:int,ageNew?:int,staleTTL?:int,touchedCallback?:callable} $opts |
1530 | * @return mixed Value found or written to the key |
1531 | * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf |
1532 | * @note Options added in 1.31: staleTTL, graceTTL |
1533 | * @note Options added in 1.33: touchedCallback |
1534 | * @note Callable type hints are not used to avoid class-autoloading |
1535 | */ |
1536 | final public function getWithSetCallback( |
1537 | $key, $ttl, $callback, array $opts = [], array $cbParams = [] |
1538 | ) { |
1539 | $version = $opts['version'] ?? null; |
1540 | $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE; |
1541 | $pCache = ( $pcTTL >= 0 ) |
1542 | ? $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY ) |
1543 | : null; |
1544 | |
1545 | // Use the process cache if requested as long as no outer cache callback is running. |
1546 | // Nested callback process cache use is not lag-safe with regard to HOLDOFF_TTL since |
1547 | // process cached values are more lagged than persistent ones as they are not purged. |
1548 | if ( $pCache && $this->callbackDepth == 0 ) { |
1549 | $cached = $pCache->get( $key, $pcTTL, false ); |
1550 | if ( $cached !== false ) { |
1551 | $this->logger->debug( "getWithSetCallback($key): process cache hit" ); |
1552 | return $cached; |
1553 | } |
1554 | } |
1555 | |
1556 | [ $value, $valueVersion, $curAsOf ] = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams ); |
1557 | if ( $valueVersion !== $version ) { |
1558 | // Current value has a different version; use the variant key for this version. |
1559 | // Regenerate the variant value if it is not newer than the main value at $key |
1560 | // so that purges to the main key propagate to the variant value. |
1561 | $this->logger->debug( "getWithSetCallback($key): using variant key" ); |
1562 | [ $value ] = $this->fetchOrRegenerate( |
1563 | $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), (string)$version ), |
1564 | $ttl, |
1565 | $callback, |
1566 | [ 'version' => null, 'minAsOf' => $curAsOf ] + $opts, |
1567 | $cbParams |
1568 | ); |
1569 | } |
1570 | |
1571 | // Update the process cache if enabled |
1572 | if ( $pCache && $value !== false ) { |
1573 | $pCache->set( $key, $value ); |
1574 | } |
1575 | |
1576 | return $value; |
1577 | } |
1578 | |
1579 | /** |
1580 | * Do the actual I/O for getWithSetCallback() when needed |
1581 | * |
1582 | * @see WANObjectCache::getWithSetCallback() |
1583 | * |
1584 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1585 | * @param int $ttl |
1586 | * @param callable $callback |
1587 | * @param array $opts |
1588 | * @param array $cbParams |
1589 | * @return array Ordered list of the following: |
1590 | * - Cached or regenerated value |
1591 | * - Cached or regenerated value version number or null if not versioned |
1592 | * - Timestamp of the current cached value at the key or null if there is no value |
1593 | * @note Callable type hints are not used to avoid class-autoloading |
1594 | */ |
1595 | private function fetchOrRegenerate( $key, $ttl, $callback, array $opts, array $cbParams ) { |
1596 | $checkKeys = $opts['checkKeys'] ?? []; |
1597 | $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE; |
1598 | $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE; |
1599 | $hotTTR = $opts['hotTTR'] ?? self::HOT_TTR; |
1600 | $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl ); |
1601 | $ageNew = $opts['ageNew'] ?? self::AGE_NEW; |
1602 | $touchedCb = $opts['touchedCallback'] ?? null; |
1603 | $startTime = $this->getCurrentTime(); |
1604 | |
1605 | $keygroup = $this->determineKeyGroupForStats( $key ); |
1606 | |
1607 | // Get the current key value and its metadata |
1608 | $curState = $this->fetchKeys( [ $key ], $checkKeys, $touchedCb )[$key]; |
1609 | $curValue = $curState[self::RES_VALUE]; |
1610 | // Use the cached value if it exists and is not due for synchronous regeneration |
1611 | if ( $this->isAcceptablyFreshValue( $curState, $graceTTL, $minAsOf ) ) { |
1612 | if ( !$this->isLotteryRefreshDue( $curState, $lowTTL, $ageNew, $hotTTR, $startTime ) ) { |
1613 | $this->stats->timing( |
1614 | "wanobjectcache.$keygroup.hit.good", |
1615 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1616 | ); |
1617 | |
1618 | return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ]; |
1619 | } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts, $cbParams ) ) { |
1620 | $this->logger->debug( "fetchOrRegenerate($key): hit with async refresh" ); |
1621 | $this->stats->timing( |
1622 | "wanobjectcache.$keygroup.hit.refresh", |
1623 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1624 | ); |
1625 | |
1626 | return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ]; |
1627 | } else { |
1628 | $this->logger->debug( "fetchOrRegenerate($key): hit with sync refresh" ); |
1629 | } |
1630 | } |
1631 | |
1632 | $isKeyTombstoned = ( $curState[self::RES_TOMB_AS_OF] !== null ); |
1633 | // Use the interim key as a temporary alternative if the key is tombstoned |
1634 | if ( $isKeyTombstoned ) { |
1635 | $volState = $this->getInterimValue( $key, $minAsOf, $startTime, $touchedCb ); |
1636 | $volValue = $volState[self::RES_VALUE]; |
1637 | } else { |
1638 | $volState = $curState; |
1639 | $volValue = $curValue; |
1640 | } |
1641 | |
1642 | // During the volatile "hold-off" period that follows a purge of the key, the value |
1643 | // will be regenerated many times if frequently accessed. This is done to mitigate |
1644 | // the effects of backend replication lag as soon as possible. However, throttle the |
1645 | // overhead of locking and regeneration by reusing values recently written to cache |
1646 | // tens of milliseconds ago. Verify the "as of" time against the last purge event. |
1647 | $lastPurgeTime = max( |
1648 | // RES_TOUCH_AS_OF depends on the value (possibly from the interim key) |
1649 | $volState[self::RES_TOUCH_AS_OF], |
1650 | $curState[self::RES_TOMB_AS_OF], |
1651 | $curState[self::RES_CHECK_AS_OF] |
1652 | ); |
1653 | $safeMinAsOf = max( $minAsOf, $lastPurgeTime + self::TINY_POSITIVE ); |
1654 | if ( $this->isExtremelyNewValue( $volState, $safeMinAsOf, $startTime ) ) { |
1655 | $this->logger->debug( "fetchOrRegenerate($key): volatile hit" ); |
1656 | $this->stats->timing( |
1657 | "wanobjectcache.$keygroup.hit.volatile", |
1658 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1659 | ); |
1660 | |
1661 | return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ]; |
1662 | } |
1663 | |
1664 | $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE; |
1665 | $busyValue = $opts['busyValue'] ?? null; |
1666 | $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE; |
1667 | $segmentable = $opts['segmentable'] ?? false; |
1668 | $version = $opts['version'] ?? null; |
1669 | |
1670 | // Determine whether one thread per datacenter should handle regeneration at a time |
1671 | $useRegenerationLock = |
1672 | // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to |
1673 | // deduce the key hotness because |$curTTL| will always keep increasing until the |
1674 | // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE |
1675 | // is not set, constant regeneration of a key for the tombstone lifetime might be |
1676 | // very expensive. Assume tombstoned keys are possibly hot in order to reduce |
1677 | // the risk of high regeneration load after the delete() method is called. |
1678 | $isKeyTombstoned || |
1679 | // Assume a key is hot if requested soon ($lockTSE seconds) after purge. |
1680 | // This avoids stampedes when timestamps from $checkKeys/$touchedCb bump. |
1681 | ( |
1682 | $curState[self::RES_CUR_TTL] !== null && |
1683 | $curState[self::RES_CUR_TTL] <= 0 && |
1684 | abs( $curState[self::RES_CUR_TTL] ) <= $lockTSE |
1685 | ) || |
1686 | // Assume a key is hot if there is no value and a busy fallback is given. |
1687 | // This avoids stampedes on eviction or preemptive regeneration taking too long. |
1688 | ( $busyValue !== null && $volValue === false ); |
1689 | |
1690 | // If a regeneration lock is required, threads that do not get the lock will try to use |
1691 | // the stale value, the interim value, or the $busyValue placeholder, in that order. If |
1692 | // none of those are set then all threads will bypass the lock and regenerate the value. |
1693 | $hasLock = $useRegenerationLock && $this->claimStampedeLock( $key ); |
1694 | if ( $useRegenerationLock && !$hasLock ) { |
1695 | // Determine if there is stale or volatile cached value that is still usable |
1696 | // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive |
1697 | if ( $this->isValid( $volValue, $volState[self::RES_AS_OF], $minAsOf ) ) { |
1698 | $this->logger->debug( "fetchOrRegenerate($key): returning stale value" ); |
1699 | $this->stats->timing( |
1700 | "wanobjectcache.$keygroup.hit.stale", |
1701 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1702 | ); |
1703 | |
1704 | return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ]; |
1705 | } elseif ( $busyValue !== null ) { |
1706 | $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss'; |
1707 | $this->logger->debug( "fetchOrRegenerate($key): busy $miss" ); |
1708 | $this->stats->timing( |
1709 | "wanobjectcache.$keygroup.$miss.busy", |
1710 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1711 | ); |
1712 | $placeholderValue = $this->resolveBusyValue( $busyValue ); |
1713 | |
1714 | return [ $placeholderValue, $version, $curState[self::RES_AS_OF] ]; |
1715 | } |
1716 | } |
1717 | |
1718 | // Generate the new value given any prior value with a matching version |
1719 | $setOpts = []; |
1720 | $preCallbackTime = $this->getCurrentTime(); |
1721 | ++$this->callbackDepth; |
1722 | // https://github.com/phan/phan/issues/4419 |
1723 | $value = null; |
1724 | try { |
1725 | $value = $callback( |
1726 | ( $curState[self::RES_VERSION] === $version ) ? $curValue : false, |
1727 | $ttl, |
1728 | $setOpts, |
1729 | ( $curState[self::RES_VERSION] === $version ) ? $curState[self::RES_AS_OF] : null, |
1730 | $cbParams |
1731 | ); |
1732 | } finally { |
1733 | --$this->callbackDepth; |
1734 | } |
1735 | $postCallbackTime = $this->getCurrentTime(); |
1736 | |
1737 | // How long it took to fetch, validate, and generate the value |
1738 | $elapsed = max( $postCallbackTime - $startTime, 0.0 ); |
1739 | |
1740 | // How long it took to generate the value |
1741 | $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 ); |
1742 | $this->stats->timing( "wanobjectcache.$keygroup.regen_walltime", 1e3 * $walltime ); |
1743 | |
1744 | // Attempt to save the newly generated value if applicable |
1745 | if ( |
1746 | // Callback yielded a cacheable value |
1747 | ( $value !== false && $ttl >= 0 ) && |
1748 | // Current thread was not raced out of a regeneration lock or key is tombstoned |
1749 | ( !$useRegenerationLock || $hasLock || $isKeyTombstoned ) |
1750 | ) { |
1751 | $this->stats->timing( "wanobjectcache.$keygroup.regen_set_delay", 1e3 * $elapsed ); |
1752 | // If the key is write-holed then use the (volatile) interim key as an alternative |
1753 | if ( $isKeyTombstoned ) { |
1754 | $this->setInterimValue( |
1755 | $key, |
1756 | $value, |
1757 | $lockTSE, |
1758 | $version, |
1759 | $segmentable |
1760 | ); |
1761 | } else { |
1762 | $this->setMainValue( |
1763 | $key, |
1764 | $value, |
1765 | $ttl, |
1766 | $version, |
1767 | $walltime, |
1768 | // @phan-suppress-next-line PhanCoalescingAlwaysNull |
1769 | $setOpts['lag'] ?? 0, |
1770 | // @phan-suppress-next-line PhanCoalescingAlwaysNull |
1771 | $setOpts['since'] ?? $preCallbackTime, |
1772 | // @phan-suppress-next-line PhanCoalescingAlwaysNull |
1773 | $setOpts['pending'] ?? false, |
1774 | $lockTSE, |
1775 | $staleTTL, |
1776 | $segmentable, |
1777 | ( $curValue === false ) |
1778 | ); |
1779 | } |
1780 | } |
1781 | |
1782 | $this->yieldStampedeLock( $key, $hasLock ); |
1783 | |
1784 | $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss'; |
1785 | $this->logger->debug( "fetchOrRegenerate($key): $miss, new value computed" ); |
1786 | $this->stats->timing( |
1787 | "wanobjectcache.$keygroup.$miss.compute", |
1788 | 1e3 * ( $this->getCurrentTime() - $startTime ) |
1789 | ); |
1790 | |
1791 | return [ $value, $version, $curState[self::RES_AS_OF] ]; |
1792 | } |
1793 | |
1794 | /** |
1795 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1796 | * @return bool Success |
1797 | */ |
1798 | private function claimStampedeLock( $key ) { |
1799 | $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX ); |
1800 | // Note that locking is not bypassed due to I/O errors; this avoids stampedes |
1801 | return $this->cache->add( $checkSisterKey, 1, self::LOCK_TTL ); |
1802 | } |
1803 | |
1804 | /** |
1805 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1806 | * @param bool $hasLock |
1807 | */ |
1808 | private function yieldStampedeLock( $key, $hasLock ) { |
1809 | if ( $hasLock ) { |
1810 | $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX ); |
1811 | $this->cache->delete( $checkSisterKey, $this->cache::WRITE_BACKGROUND ); |
1812 | } |
1813 | } |
1814 | |
1815 | /** |
1816 | * Get sister keys that should be collocated with their corresponding base cache keys |
1817 | * |
1818 | * The key will bear the WANCache prefix and use the configured coalescing scheme |
1819 | * |
1820 | * @param string[] $baseKeys Cache keys made with makeKey()/makeGlobalKey() |
1821 | * @param string $type Consistent hashing agnostic suffix character matching [a-zA-Z] |
1822 | * @param string|null $route Routing prefix (optional) |
1823 | * @return string[] Order-corresponding list of sister keys |
1824 | */ |
1825 | private function makeSisterKeys( array $baseKeys, string $type, string $route = null ) { |
1826 | $sisterKeys = []; |
1827 | foreach ( $baseKeys as $baseKey ) { |
1828 | $sisterKeys[] = $this->makeSisterKey( $baseKey, $type, $route ); |
1829 | } |
1830 | |
1831 | return $sisterKeys; |
1832 | } |
1833 | |
1834 | /** |
1835 | * Get a sister key that should be collocated with a base cache key |
1836 | * |
1837 | * The keys will bear the WANCache prefix and use the configured coalescing scheme |
1838 | * |
1839 | * @param string $baseKey Cache key made with makeKey()/makeGlobalKey() |
1840 | * @param string $typeChar Consistent hashing agnostic suffix character matching [a-zA-Z] |
1841 | * @param string|null $route Routing prefix (optional) |
1842 | * @return string Sister key |
1843 | */ |
1844 | private function makeSisterKey( string $baseKey, string $typeChar, string $route = null ) { |
1845 | if ( $this->coalesceScheme === self::SCHEME_HASH_STOP ) { |
1846 | // Key style: "WANCache:<base key>|#|<character>" |
1847 | $sisterKey = 'WANCache:' . $baseKey . '|#|' . $typeChar; |
1848 | } else { |
1849 | // Key style: "WANCache:{<base key>}:<character>" |
1850 | $sisterKey = 'WANCache:{' . $baseKey . '}:' . $typeChar; |
1851 | } |
1852 | |
1853 | if ( $route !== null ) { |
1854 | $sisterKey = $this->prependRoute( $sisterKey, $route ); |
1855 | } |
1856 | |
1857 | return $sisterKey; |
1858 | } |
1859 | |
1860 | /** |
1861 | * Check if a key value is non-false, new enough, and has an "as of" time almost equal to now |
1862 | * |
1863 | * If the value was just written to cache, and it did not take an unusually long time to |
1864 | * generate, then it is probably not worth regenerating yet. For example, replica databases |
1865 | * might still return lagged pre-purge values anyway. |
1866 | * |
1867 | * @param array $res Current value WANObjectCache::RES_* data map |
1868 | * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp |
1869 | * @param float $now Current UNIX timestamp |
1870 | * @return bool Whether the age of a volatile value is negligible |
1871 | */ |
1872 | private function isExtremelyNewValue( $res, $minAsOf, $now ) { |
1873 | if ( $res[self::RES_VALUE] === false || $res[self::RES_AS_OF] < $minAsOf ) { |
1874 | return false; |
1875 | } |
1876 | |
1877 | $age = $now - $res[self::RES_AS_OF]; |
1878 | |
1879 | return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 ); |
1880 | } |
1881 | |
1882 | /** |
1883 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1884 | * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp |
1885 | * @param float $now Fetch time to determine "age" metadata |
1886 | * @param callable|null $touchedCb Function to find the max "dependency touched" UNIX timestamp |
1887 | * @return array<int,mixed> Result map/n-tuple from unwrap() |
1888 | * @phan-return array{0:mixed,1:mixed,2:?float,3:?int,4:?float,5:?float,6:?float,7:?float} |
1889 | * @note Callable type hints are not used to avoid class-autoloading |
1890 | */ |
1891 | private function getInterimValue( $key, $minAsOf, $now, $touchedCb ) { |
1892 | if ( $this->useInterimHoldOffCaching ) { |
1893 | $interimSisterKey = $this->makeSisterKey( $key, self::TYPE_INTERIM ); |
1894 | $wrapped = $this->cache->get( $interimSisterKey ); |
1895 | $res = $this->unwrap( $wrapped, $now ); |
1896 | if ( $res[self::RES_VALUE] !== false && $res[self::RES_AS_OF] >= $minAsOf ) { |
1897 | if ( $touchedCb !== null ) { |
1898 | // Update "last purge time" since the $touchedCb timestamp depends on $value |
1899 | // Get the new "touched timestamp", accounting for callback-checked dependencies |
1900 | $res[self::RES_TOUCH_AS_OF] = max( |
1901 | $touchedCb( $res[self::RES_VALUE] ), |
1902 | $res[self::RES_TOUCH_AS_OF] |
1903 | ); |
1904 | } |
1905 | |
1906 | return $res; |
1907 | } |
1908 | } |
1909 | |
1910 | return $this->unwrap( false, $now ); |
1911 | } |
1912 | |
1913 | /** |
1914 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
1915 | * @param mixed $value |
1916 | * @param int|float $ttl |
1917 | * @param int|null $version Value version number |
1918 | * @param bool $segmentable |
1919 | * @return bool Success |
1920 | */ |
1921 | private function setInterimValue( |
1922 | $key, |
1923 | $value, |
1924 | $ttl, |
1925 | ?int $version, |
1926 | bool $segmentable |
1927 | ) { |
1928 | $now = $this->getCurrentTime(); |
1929 | $ttl = max( self::INTERIM_KEY_TTL, (int)$ttl ); |
1930 | |
1931 | // Wrap that value with time/TTL/version metadata |
1932 | $wrapped = $this->wrap( $value, $ttl, $version, $now ); |
1933 | |
1934 | $flags = $this->cache::WRITE_BACKGROUND; |
1935 | if ( $segmentable ) { |
1936 | $flags |= $this->cache::WRITE_ALLOW_SEGMENTS; |
1937 | } |
1938 | |
1939 | return $this->cache->set( |
1940 | $this->makeSisterKey( $key, self::TYPE_INTERIM ), |
1941 | $wrapped, |
1942 | $ttl, |
1943 | $flags |
1944 | ); |
1945 | } |
1946 | |
1947 | /** |
1948 | * @param mixed $busyValue |
1949 | * @return mixed |
1950 | */ |
1951 | private function resolveBusyValue( $busyValue ) { |
1952 | return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue; |
1953 | } |
1954 | |
1955 | /** |
1956 | * Method to fetch multiple cache keys at once with regeneration |
1957 | * |
1958 | * This works the same as getWithSetCallback() except: |
1959 | * - a) The $keys argument must be the result of WANObjectCache::makeMultiKeys() |
1960 | * - b) The $callback argument expects a function that returns an entity value, using |
1961 | * boolean "false" if it does not exist. The callback takes the following arguments: |
1962 | * - $id: ID of the entity to query |
1963 | * - $oldValue: prior cache value or false if none was present |
1964 | * - &$ttl: reference to the TTL to be assigned to the new value (alterable) |
1965 | * - &$setOpts: reference to the new value set() options (alterable) |
1966 | * - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present |
1967 | * - c) The return value is a map of (cache key => value) in the order of $keyedIds |
1968 | * |
1969 | * @see WANObjectCache::getWithSetCallback() |
1970 | * @see WANObjectCache::getMultiWithUnionSetCallback() |
1971 | * |
1972 | * Example usage: |
1973 | * @code |
1974 | * $rows = $cache->getMultiWithSetCallback( |
1975 | * // Map of cache keys to entity IDs |
1976 | * $cache->makeMultiKeys( |
1977 | * $this->fileVersionIds(), |
1978 | * function ( $id, $cache ) { |
1979 | * return $cache->makeKey( 'file-version', $id ); |
1980 | * } |
1981 | * ), |
1982 | * // Time-to-live (in seconds) |
1983 | * $cache::TTL_DAY, |
1984 | * // Function that derives the new key value |
1985 | * function ( $id, $oldValue, &$ttl, array &$setOpts ) { |
1986 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
1987 | * // Account for any snapshot/replica DB lag |
1988 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
1989 | * |
1990 | * // Load the row for this file |
1991 | * $queryInfo = File::getQueryInfo(); |
1992 | * $row = $dbr->selectRow( |
1993 | * $queryInfo['tables'], |
1994 | * $queryInfo['fields'], |
1995 | * [ 'id' => $id ], |
1996 | * __METHOD__, |
1997 | * [], |
1998 | * $queryInfo['joins'] |
1999 | * ); |
2000 | * |
2001 | * return $row ? (array)$row : false; |
2002 | * }, |
2003 | * [ |
2004 | * // Process cache for 30 seconds |
2005 | * 'pcTTL' => 30, |
2006 | * // Use a dedicated 500 item cache (initialized on-the-fly) |
2007 | * 'pcGroup' => 'file-versions:500' |
2008 | * ] |
2009 | * ); |
2010 | * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows ); |
2011 | * @endcode |
2012 | * |
2013 | * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys() |
2014 | * @param int $ttl Seconds to live for key updates |
2015 | * @param callable $callback Callback that yields entity generation callbacks |
2016 | * @param array $opts Options map similar to that of getWithSetCallback() |
2017 | * @return mixed[] Map of (cache key => value) in the same order as $keyedIds |
2018 | * @since 1.28 |
2019 | */ |
2020 | final public function getMultiWithSetCallback( |
2021 | ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = [] |
2022 | ) { |
2023 | // Batch load required keys into the in-process warmup cache |
2024 | $this->warmupCache = $this->fetchWrappedValuesForWarmupCache( |
2025 | $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ), |
2026 | $opts['checkKeys'] ?? [] |
2027 | ); |
2028 | $this->warmupKeyMisses = 0; |
2029 | |
2030 | // The required callback signature includes $id as the first argument for convenience |
2031 | // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the |
2032 | // callback with a proxy callback that has the standard getWithSetCallback() signature. |
2033 | // This is defined only once per batch to avoid closure creation overhead. |
2034 | $proxyCb = static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params ) |
2035 | use ( $callback ) |
2036 | { |
2037 | return $callback( $params['id'], $oldValue, $ttl, $setOpts, $oldAsOf ); |
2038 | }; |
2039 | |
2040 | // Get the order-preserved result map using the warm-up cache |
2041 | $values = []; |
2042 | foreach ( $keyedIds as $key => $id ) { |
2043 | $values[$key] = $this->getWithSetCallback( |
2044 | $key, |
2045 | $ttl, |
2046 | $proxyCb, |
2047 | $opts, |
2048 | [ 'id' => $id ] |
2049 | ); |
2050 | } |
2051 | |
2052 | $this->warmupCache = []; |
2053 | |
2054 | return $values; |
2055 | } |
2056 | |
2057 | /** |
2058 | * Method to fetch/regenerate multiple cache keys at once |
2059 | * |
2060 | * This works the same as getWithSetCallback() except: |
2061 | * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys() |
2062 | * - b) The $callback argument expects a function that returns a map of (ID => new value), |
2063 | * using boolean "false" for entities that could not be found, for all entity IDs in |
2064 | * $ids. The callback takes the following arguments: |
2065 | * - $ids: list of entity IDs that require value generation |
2066 | * - &$ttls: reference to the (entity ID => new TTL) map (alterable) |
2067 | * - &$setOpts: reference to the new value set() options (alterable) |
2068 | * - c) The return value is a map of (cache key => value) in the order of $keyedIds |
2069 | * - d) The "lockTSE" and "busyValue" options are ignored |
2070 | * |
2071 | * @see WANObjectCache::getWithSetCallback() |
2072 | * @see WANObjectCache::getMultiWithSetCallback() |
2073 | * |
2074 | * Example usage: |
2075 | * @code |
2076 | * $rows = $cache->getMultiWithUnionSetCallback( |
2077 | * // Map of cache keys to entity IDs |
2078 | * $cache->makeMultiKeys( |
2079 | * $this->fileVersionIds(), |
2080 | * function ( $id ) use ( $cache ) { |
2081 | * return $cache->makeKey( 'file-version', $id ); |
2082 | * } |
2083 | * ), |
2084 | * // Time-to-live (in seconds) |
2085 | * $cache::TTL_DAY, |
2086 | * // Function that derives the new key value |
2087 | * function ( array $ids, array &$ttls, array &$setOpts ) { |
2088 | * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); |
2089 | * // Account for any snapshot/replica DB lag |
2090 | * $setOpts += Database::getCacheSetOptions( $dbr ); |
2091 | * |
2092 | * // Load the rows for these files |
2093 | * $rows = array_fill_keys( $ids, false ); |
2094 | * $queryInfo = File::getQueryInfo(); |
2095 | * $res = $dbr->select( |
2096 | * $queryInfo['tables'], |
2097 | * $queryInfo['fields'], |
2098 | * [ 'id' => $ids ], |
2099 | * __METHOD__, |
2100 | * [], |
2101 | * $queryInfo['joins'] |
2102 | * ); |
2103 | * foreach ( $res as $row ) { |
2104 | * $rows[$row->id] = $row; |
2105 | * $mtime = wfTimestamp( TS_UNIX, $row->timestamp ); |
2106 | * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] ); |
2107 | * } |
2108 | * |
2109 | * return $rows; |
2110 | * }, |
2111 | * ] |
2112 | * ); |
2113 | * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows ); |
2114 | * @endcode |
2115 | * |
2116 | * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys() |
2117 | * @param int $ttl Seconds to live for key updates |
2118 | * @param callable $callback Callback that yields entity generation callbacks |
2119 | * @param array $opts Options map similar to that of getWithSetCallback() |
2120 | * @return mixed[] Map of (cache key => value) in the same order as $keyedIds |
2121 | * @since 1.30 |
2122 | */ |
2123 | final public function getMultiWithUnionSetCallback( |
2124 | ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = [] |
2125 | ) { |
2126 | $checkKeys = $opts['checkKeys'] ?? []; |
2127 | $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE; |
2128 | |
2129 | // unset incompatible keys |
2130 | unset( $opts['lockTSE'] ); |
2131 | unset( $opts['busyValue'] ); |
2132 | |
2133 | // Batch load required keys into the in-process warmup cache |
2134 | $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ); |
2135 | $this->warmupCache = $this->fetchWrappedValuesForWarmupCache( $keysByIdGet, $checkKeys ); |
2136 | $this->warmupKeyMisses = 0; |
2137 | |
2138 | // IDs of entities known to be in need of generation |
2139 | $idsRegen = []; |
2140 | |
2141 | // Find out which keys are missing/deleted/stale |
2142 | $resByKey = $this->fetchKeys( $keysByIdGet, $checkKeys ); |
2143 | foreach ( $keysByIdGet as $id => $key ) { |
2144 | $res = $resByKey[$key]; |
2145 | if ( |
2146 | $res[self::RES_VALUE] === false || |
2147 | $res[self::RES_CUR_TTL] < 0 || |
2148 | $res[self::RES_AS_OF] < $minAsOf |
2149 | ) { |
2150 | $idsRegen[] = $id; |
2151 | } |
2152 | } |
2153 | |
2154 | // Run the callback to populate the generation value map for all required IDs |
2155 | $newSetOpts = []; |
2156 | $newTTLsById = array_fill_keys( $idsRegen, $ttl ); |
2157 | $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : []; |
2158 | |
2159 | $method = __METHOD__; |
2160 | // The required callback signature includes $id as the first argument for convenience |
2161 | // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the |
2162 | // callback with a proxy callback that has the standard getWithSetCallback() signature. |
2163 | // This is defined only once per batch to avoid closure creation overhead. |
2164 | $proxyCb = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params ) |
2165 | use ( $callback, $newValsById, $newTTLsById, $newSetOpts, $method ) |
2166 | { |
2167 | $id = $params['id']; |
2168 | |
2169 | if ( array_key_exists( $id, $newValsById ) ) { |
2170 | // Value was already regenerated as expected, so use the value in $newValsById |
2171 | $newValue = $newValsById[$id]; |
2172 | $ttl = $newTTLsById[$id]; |
2173 | $setOpts = $newSetOpts; |
2174 | } else { |
2175 | // Pre-emptive/popularity refresh and version mismatch cases are not detected |
2176 | // above and thus $newValsById has no entry. Run $callback on this single entity. |
2177 | $ttls = [ $id => $ttl ]; |
2178 | $result = $callback( [ $id ], $ttls, $setOpts ); |
2179 | if ( !isset( $result[$id] ) ) { |
2180 | // T303092 |
2181 | $this->logger->warning( |
2182 | $method . ' failed due to {id} not set in result {result}', [ |
2183 | 'id' => $id, |
2184 | 'result' => json_encode( $result ) |
2185 | ] ); |
2186 | } |
2187 | $newValue = $result[$id]; |
2188 | $ttl = $ttls[$id]; |
2189 | } |
2190 | |
2191 | return $newValue; |
2192 | }; |
2193 | |
2194 | // Get the order-preserved result map using the warm-up cache |
2195 | $values = []; |
2196 | foreach ( $keyedIds as $key => $id ) { |
2197 | $values[$key] = $this->getWithSetCallback( |
2198 | $key, |
2199 | $ttl, |
2200 | $proxyCb, |
2201 | $opts, |
2202 | [ 'id' => $id ] |
2203 | ); |
2204 | } |
2205 | |
2206 | $this->warmupCache = []; |
2207 | |
2208 | return $values; |
2209 | } |
2210 | |
2211 | /** |
2212 | * @see BagOStuff::makeGlobalKey() |
2213 | * @since 1.27 |
2214 | * @param string $keygroup Key group component, should be under 48 characters. |
2215 | * @param string|int ...$components Additional, ordered, key components for entity IDs |
2216 | * @return string Colon-separated, keyspace-prepended, ordered list of encoded components |
2217 | */ |
2218 | public function makeGlobalKey( $keygroup, ...$components ) { |
2219 | // @phan-suppress-next-line PhanParamTooFewUnpack Should infer non-emptiness |
2220 | return $this->cache->makeGlobalKey( ...func_get_args() ); |
2221 | } |
2222 | |
2223 | /** |
2224 | * @see BagOStuff::makeKey() |
2225 | * @since 1.27 |
2226 | * @param string $keygroup Key group component, should be under 48 characters. |
2227 | * @param string|int ...$components Additional, ordered, key components for entity IDs |
2228 | * @return string Colon-separated, keyspace-prepended, ordered list of encoded components |
2229 | */ |
2230 | public function makeKey( $keygroup, ...$components ) { |
2231 | // @phan-suppress-next-line PhanParamTooFewUnpack Should infer non-emptiness |
2232 | return $this->cache->makeKey( ...func_get_args() ); |
2233 | } |
2234 | |
2235 | /** |
2236 | * Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey() |
2237 | * |
2238 | * @param string $component A raw component used in building a cache key |
2239 | * @return string 64 character HMAC using a stable secret for public collision resistance |
2240 | * @since 1.34 |
2241 | */ |
2242 | public function hash256( $component ) { |
2243 | return hash_hmac( 'sha256', $component, $this->secret ); |
2244 | } |
2245 | |
2246 | /** |
2247 | * Get an iterator of (cache key => entity ID) for a list of entity IDs |
2248 | * |
2249 | * The $callback argument expects a function that returns the key for an entity ID via |
2250 | * makeKey()/makeGlobalKey(). There should be no network nor filesystem I/O used in the |
2251 | * callback. The entity ID/key mapping must be 1:1 or an exception will be thrown. Use |
2252 | * the hash256() method for any hashing. The callback takes the following arguments: |
2253 | * - $id: An entity ID |
2254 | * - $cache: This WANObjectCache instance |
2255 | * |
2256 | * Example usage for the default keyspace: |
2257 | * @code |
2258 | * $keyedIds = $cache->makeMultiKeys( |
2259 | * $modules, |
2260 | * function ( $module, $cache ) { |
2261 | * return $cache->makeKey( 'example-module', $module ); |
2262 | * } |
2263 | * ); |
2264 | * @endcode |
2265 | * |
2266 | * Example usage for mixed default and global keyspace: |
2267 | * @code |
2268 | * $keyedIds = $cache->makeMultiKeys( |
2269 | * $filters, |
2270 | * function ( $filter, $cache ) { |
2271 | * return self::isCentral( $filter ) |
2272 | * ? $cache->makeGlobalKey( 'example-filter', $filter ) |
2273 | * : $cache->makeKey( 'example-filter', $filter ) |
2274 | * } |
2275 | * ); |
2276 | * @endcode |
2277 | * |
2278 | * Example usage with hashing: |
2279 | * @code |
2280 | * $keyedIds = $cache->makeMultiKeys( |
2281 | * $urls, |
2282 | * function ( $url, $cache ) { |
2283 | * return $cache->makeKey( 'example-url', $cache->hash256( $url ) ); |
2284 | * } |
2285 | * ); |
2286 | * @endcode |
2287 | * |
2288 | * @see WANObjectCache::makeKey() |
2289 | * @see WANObjectCache::makeGlobalKey() |
2290 | * @see WANObjectCache::hash256() |
2291 | * |
2292 | * @param string[]|int[] $ids List of entity IDs |
2293 | * @param callable $keyCallback Function returning makeKey()/makeGlobalKey() on the input ID |
2294 | * @return ArrayIterator Iterator of (cache key => ID); order of $ids is preserved |
2295 | * @since 1.28 |
2296 | */ |
2297 | final public function makeMultiKeys( array $ids, $keyCallback ) { |
2298 | $idByKey = []; |
2299 | foreach ( $ids as $id ) { |
2300 | // Discourage triggering of automatic makeKey() hashing in some backends |
2301 | if ( strlen( $id ) > 64 ) { |
2302 | $this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" ); |
2303 | } |
2304 | $key = $keyCallback( $id, $this ); |
2305 | // Edge case: ignore key collisions due to duplicate $ids like "42" and 42 |
2306 | if ( !isset( $idByKey[$key] ) ) { |
2307 | $idByKey[$key] = $id; |
2308 | } elseif ( (string)$id !== (string)$idByKey[$key] ) { |
2309 | throw new UnexpectedValueException( |
2310 | "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'" |
2311 | ); |
2312 | } |
2313 | } |
2314 | |
2315 | return new ArrayIterator( $idByKey ); |
2316 | } |
2317 | |
2318 | /** |
2319 | * Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list |
2320 | * of corresponding entity values by first appearance of each ID in the entity ID list |
2321 | * |
2322 | * For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback(). |
2323 | * |
2324 | * *Only* use this method if the entity ID/key mapping is trivially 1:1 without exception. |
2325 | * Key generation method must utilize the *full* entity ID in the key (not a hash of it). |
2326 | * |
2327 | * Example usage: |
2328 | * @code |
2329 | * $poems = $cache->getMultiWithSetCallback( |
2330 | * $cache->makeMultiKeys( |
2331 | * $uuids, |
2332 | * function ( $uuid ) use ( $cache ) { |
2333 | * return $cache->makeKey( 'poem', $uuid ); |
2334 | * } |
2335 | * ), |
2336 | * $cache::TTL_DAY, |
2337 | * function ( $uuid ) use ( $url ) { |
2338 | * return $this->http->run( [ 'method' => 'GET', 'url' => "$url/$uuid" ] ); |
2339 | * } |
2340 | * ); |
2341 | * $poemsByUUID = $cache->multiRemap( $uuids, $poems ); |
2342 | * @endcode |
2343 | * |
2344 | * @see WANObjectCache::makeMultiKeys() |
2345 | * @see WANObjectCache::getMultiWithSetCallback() |
2346 | * @see WANObjectCache::getMultiWithUnionSetCallback() |
2347 | * |
2348 | * @param string[]|int[] $ids Entity ID list makeMultiKeys() |
2349 | * @param mixed[] $res Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback() |
2350 | * @return mixed[] Map of (ID => value); order of $ids is preserved |
2351 | * @since 1.34 |
2352 | */ |
2353 | final public function multiRemap( array $ids, array $res ) { |
2354 | if ( count( $ids ) !== count( $res ) ) { |
2355 | // If makeMultiKeys() is called on a list of non-unique IDs, then the resulting |
2356 | // ArrayIterator will have less entries due to "first appearance" de-duplication |
2357 | $ids = array_keys( array_fill_keys( $ids, true ) ); |
2358 | if ( count( $ids ) !== count( $res ) ) { |
2359 | throw new UnexpectedValueException( "Multi-key result does not match ID list" ); |
2360 | } |
2361 | } |
2362 | |
2363 | return array_combine( $ids, $res ); |
2364 | } |
2365 | |
2366 | /** |
2367 | * Get a "watch point" token that can be used to get the "last error" to occur after now |
2368 | * |
2369 | * @return int A token that the current error event |
2370 | * @since 1.38 |
2371 | */ |
2372 | public function watchErrors() { |
2373 | return $this->cache->watchErrors(); |
2374 | } |
2375 | |
2376 | /** |
2377 | * Get the "last error" registry |
2378 | * |
2379 | * The method should be invoked by a caller as part of the following pattern: |
2380 | * - The caller invokes watchErrors() to get a "since token" |
2381 | * - The caller invokes a sequence of cache operation methods |
2382 | * - The caller invokes getLastError() with the "since token" |
2383 | * |
2384 | * External callers can also invoke this method as part of the following pattern: |
2385 | * - The caller invokes clearLastError() |
2386 | * - The caller invokes a sequence of cache operation methods |
2387 | * - The caller invokes getLastError() |
2388 | * |
2389 | * @param int $watchPoint Only consider errors from after this "watch point" [optional] |
2390 | * @return int BagOStuff:ERR_* constant for the "last error" registry |
2391 | * @note Parameters added in 1.38: $watchPoint |
2392 | */ |
2393 | final public function getLastError( $watchPoint = 0 ) { |
2394 | $code = $this->cache->getLastError( $watchPoint ); |
2395 | switch ( $code ) { |
2396 | case self::ERR_NONE: |
2397 | return self::ERR_NONE; |
2398 | case self::ERR_NO_RESPONSE: |
2399 | return self::ERR_NO_RESPONSE; |
2400 | case self::ERR_UNREACHABLE: |
2401 | return self::ERR_UNREACHABLE; |
2402 | default: |
2403 | return self::ERR_UNEXPECTED; |
2404 | } |
2405 | } |
2406 | |
2407 | /** |
2408 | * Clear the "last error" registry |
2409 | * @deprecated Since 1.38 |
2410 | */ |
2411 | final public function clearLastError() { |
2412 | $this->cache->clearLastError(); |
2413 | } |
2414 | |
2415 | /** |
2416 | * Clear the in-process caches; useful for testing |
2417 | * |
2418 | * @since 1.27 |
2419 | */ |
2420 | public function clearProcessCache() { |
2421 | $this->processCaches = []; |
2422 | } |
2423 | |
2424 | /** |
2425 | * Enable or disable the use of brief caching for tombstoned keys |
2426 | * |
2427 | * When a key is purged via delete(), there normally is a period where caching |
2428 | * is hold-off limited to an extremely short time. This method will disable that |
2429 | * caching, forcing the callback to run for any of: |
2430 | * - WANObjectCache::getWithSetCallback() |
2431 | * - WANObjectCache::getMultiWithSetCallback() |
2432 | * - WANObjectCache::getMultiWithUnionSetCallback() |
2433 | * |
2434 | * This is useful when both: |
2435 | * - a) the database used by the callback is known to be up-to-date enough |
2436 | * for some particular purpose (e.g. replica DB has applied transaction X) |
2437 | * - b) the caller needs to exploit that fact, and therefore needs to avoid the |
2438 | * use of inherently volatile and possibly stale interim keys |
2439 | * |
2440 | * @see WANObjectCache::delete() |
2441 | * @param bool $enabled Whether to enable interim caching |
2442 | * @since 1.31 |
2443 | */ |
2444 | final public function useInterimHoldOffCaching( $enabled ) { |
2445 | $this->useInterimHoldOffCaching = $enabled; |
2446 | } |
2447 | |
2448 | /** |
2449 | * @param int $flag ATTR_* class constant |
2450 | * @return int QOS_* class constant |
2451 | * @since 1.28 |
2452 | */ |
2453 | public function getQoS( $flag ) { |
2454 | return $this->cache->getQoS( $flag ); |
2455 | } |
2456 | |
2457 | /** |
2458 | * Get a TTL that is higher for objects that have not changed recently |
2459 | * |
2460 | * This is useful for keys that get explicit purges and DB or purge relay |
2461 | * lag is a potential concern (especially how it interacts with CDN cache) |
2462 | * |
2463 | * Example usage: |
2464 | * @code |
2465 | * // Last-modified time of page |
2466 | * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() ); |
2467 | * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at |
2468 | * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then |
2469 | * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL. |
2470 | * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY ); |
2471 | * @endcode |
2472 | * |
2473 | * Another use case is when there are no applicable "last modified" fields in the DB, |
2474 | * and there are too many dependencies for explicit purges to be viable, and the rate of |
2475 | * change to relevant content is unstable, and it is highly valued to have the cached value |
2476 | * be as up-to-date as possible. |
2477 | * |
2478 | * Example usage: |
2479 | * @code |
2480 | * $query = "<some complex query>"; |
2481 | * $idListFromComplexQuery = $cache->getWithSetCallback( |
2482 | * $cache->makeKey( 'complex-graph-query', $hashOfQuery ), |
2483 | * GraphQueryClass::STARTING_TTL, |
2484 | * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) { |
2485 | * $gdb = $this->getReplicaGraphDbConnection(); |
2486 | * // Account for any snapshot/replica DB lag |
2487 | * $setOpts += GraphDatabase::getCacheSetOptions( $gdb ); |
2488 | * |
2489 | * $newList = iterator_to_array( $gdb->query( $query ) ); |
2490 | * sort( $newList, SORT_NUMERIC ); // normalize |
2491 | * |
2492 | * $minTTL = GraphQueryClass::MIN_TTL; |
2493 | * $maxTTL = GraphQueryClass::MAX_TTL; |
2494 | * if ( $oldValue !== false ) { |
2495 | * // Note that $oldAsOf is the last time this callback ran |
2496 | * $ttl = ( $newList === $oldValue ) |
2497 | * // No change: cache for 150% of the age of $oldValue |
2498 | * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 ) |
2499 | * // Changed: cache for 50% of the age of $oldValue |
2500 | * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 ); |
2501 | * } |
2502 | * |
2503 | * return $newList; |
2504 | * }, |
2505 | * [ |
2506 | * // Keep stale values around for doing comparisons for TTL calculations. |
2507 | * // High values improve long-tail keys hit-rates, though might waste space. |
2508 | * 'staleTTL' => GraphQueryClass::GRACE_TTL |
2509 | * ] |
2510 | * ); |
2511 | * @endcode |
2512 | * |
2513 | * @param int|float|string|null $mtime UNIX timestamp; null if none |
2514 | * @param int $maxTTL Maximum TTL (seconds) |
2515 | * @param int $minTTL Minimum TTL (seconds); Default: 30 |
2516 | * @param float $factor Value in the range (0,1); Default: .2 |
2517 | * @return int Adaptive TTL |
2518 | * @since 1.28 |
2519 | */ |
2520 | public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) { |
2521 | // handle fractional seconds and string integers |
2522 | $mtime = (int)$mtime; |
2523 | if ( $mtime <= 0 ) { |
2524 | // no last-modified time provided |
2525 | return $minTTL; |
2526 | } |
2527 | |
2528 | $age = (int)$this->getCurrentTime() - $mtime; |
2529 | |
2530 | return (int)min( $maxTTL, max( $minTTL, $factor * $age ) ); |
2531 | } |
2532 | |
2533 | /** |
2534 | * @internal For use by unit tests only |
2535 | * @return int |
2536 | * @since 1.30 |
2537 | */ |
2538 | final public function getWarmupKeyMisses() { |
2539 | // Number of misses in $this->warmupCache during the last call to certain methods |
2540 | return $this->warmupKeyMisses; |
2541 | } |
2542 | |
2543 | /** |
2544 | * Set a sister key to a purge value in all datacenters |
2545 | * |
2546 | * This method should not wait for the operation to complete on remote datacenters |
2547 | * |
2548 | * Since older purge values can sometimes arrive after newer ones, use a relative expiry |
2549 | * so that even if the older value replaces the newer value, the TTL will greater than the |
2550 | * remaining TTL on the older value (assuming that all purges for a key use the same TTL). |
2551 | * |
2552 | * @param string $sisterKey A value key or "check" key |
2553 | * @param string $purgeValue Result of makeTombstonePurgeValue()/makeCheckKeyPurgeValue() |
2554 | * @param int $ttl Seconds to keep the purge value around |
2555 | * @return bool Success |
2556 | */ |
2557 | protected function relayVolatilePurge( string $sisterKey, string $purgeValue, int $ttl ) { |
2558 | if ( $this->broadcastRoute !== null ) { |
2559 | $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute ); |
2560 | } else { |
2561 | $routeKey = $sisterKey; |
2562 | } |
2563 | |
2564 | return $this->cache->set( |
2565 | $routeKey, |
2566 | $purgeValue, |
2567 | $ttl, |
2568 | $this->cache::WRITE_BACKGROUND |
2569 | ); |
2570 | } |
2571 | |
2572 | /** |
2573 | * Remove a sister key from all datacenters |
2574 | * |
2575 | * This method should not wait for the operation to complete on remote datacenters |
2576 | * |
2577 | * @param string $sisterKey A value key or "check" key |
2578 | * @return bool Success |
2579 | */ |
2580 | protected function relayNonVolatilePurge( string $sisterKey ) { |
2581 | if ( $this->broadcastRoute !== null ) { |
2582 | $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute ); |
2583 | } else { |
2584 | $routeKey = $sisterKey; |
2585 | } |
2586 | |
2587 | return $this->cache->delete( $routeKey, $this->cache::WRITE_BACKGROUND ); |
2588 | } |
2589 | |
2590 | /** |
2591 | * @param string $sisterKey |
2592 | * @param string $route Key routing prefix |
2593 | * @return string |
2594 | */ |
2595 | protected function prependRoute( string $sisterKey, string $route ) { |
2596 | if ( $sisterKey[0] === '/' ) { |
2597 | throw new RuntimeException( "Sister key '$sisterKey' already contains a route." ); |
2598 | } |
2599 | |
2600 | return $route . $sisterKey; |
2601 | } |
2602 | |
2603 | /** |
2604 | * Schedule a deferred cache regeneration if possible |
2605 | * |
2606 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
2607 | * @param int $ttl Seconds to live |
2608 | * @param callable $callback |
2609 | * @param array $opts |
2610 | * @param array $cbParams |
2611 | * @return bool Success |
2612 | * @note Callable type hints are not used to avoid class-autoloading |
2613 | */ |
2614 | private function scheduleAsyncRefresh( $key, $ttl, $callback, array $opts, array $cbParams ) { |
2615 | if ( !$this->asyncHandler ) { |
2616 | return false; |
2617 | } |
2618 | // Update the cache value later, such during post-send of an HTTP request. This forces |
2619 | // cache regeneration by setting "minAsOf" to infinity, meaning that no existing value |
2620 | // is considered valid. Furthermore, note that preemptive regeneration is not applicable |
2621 | // to invalid values, so there is no risk of infinite preemptive regeneration loops. |
2622 | $func = $this->asyncHandler; |
2623 | $func( function () use ( $key, $ttl, $callback, $opts, $cbParams ) { |
2624 | $opts['minAsOf'] = INF; |
2625 | try { |
2626 | $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams ); |
2627 | } catch ( Exception $e ) { |
2628 | // Log some context for easier debugging |
2629 | $this->logger->error( 'Async refresh failed for {key}', [ |
2630 | 'key' => $key, |
2631 | 'ttl' => $ttl, |
2632 | 'exception' => $e |
2633 | ] ); |
2634 | throw $e; |
2635 | } |
2636 | } ); |
2637 | |
2638 | return true; |
2639 | } |
2640 | |
2641 | /** |
2642 | * Check if a key value is non-false, new enough, and either fresh or "gracefully" stale |
2643 | * |
2644 | * @param array $res Current value WANObjectCache::RES_* data map |
2645 | * @param int $graceTTL Consider using stale values if $curTTL is greater than this |
2646 | * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp |
2647 | * @return bool |
2648 | */ |
2649 | private function isAcceptablyFreshValue( $res, $graceTTL, $minAsOf ) { |
2650 | if ( !$this->isValid( $res[self::RES_VALUE], $res[self::RES_AS_OF], $minAsOf ) ) { |
2651 | // Value does not exists or is too old |
2652 | return false; |
2653 | } |
2654 | |
2655 | $curTTL = $res[self::RES_CUR_TTL]; |
2656 | if ( $curTTL > 0 ) { |
2657 | // Value is definitely still fresh |
2658 | return true; |
2659 | } |
2660 | |
2661 | // Remaining seconds during which this stale value can be used |
2662 | $curGraceTTL = $graceTTL + $curTTL; |
2663 | |
2664 | return ( $curGraceTTL > 0 ) |
2665 | // Chance of using the value decreases as $curTTL goes from 0 to -$graceTTL |
2666 | ? !$this->worthRefreshExpiring( $curGraceTTL, $graceTTL, $graceTTL ) |
2667 | // Value is too stale to fall in the grace period |
2668 | : false; |
2669 | } |
2670 | |
2671 | /** |
2672 | * Check if a key is due for randomized regeneration due to near-expiration/popularity |
2673 | * |
2674 | * @param array $res Current value WANObjectCache::RES_* data map |
2675 | * @param float $lowTTL Consider a refresh when $curTTL is less than this; the "low" threshold |
2676 | * @param int $ageNew Age of key when this might recommend refreshing (seconds) |
2677 | * @param int $hotTTR Age of key when it should be refreshed if popular (seconds) |
2678 | * @param float $now The current UNIX timestamp |
2679 | * @return bool |
2680 | */ |
2681 | protected function isLotteryRefreshDue( $res, $lowTTL, $ageNew, $hotTTR, $now ) { |
2682 | $curTTL = $res[self::RES_CUR_TTL]; |
2683 | $logicalTTL = $res[self::RES_TTL]; |
2684 | $asOf = $res[self::RES_AS_OF]; |
2685 | |
2686 | return ( |
2687 | $this->worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) || |
2688 | $this->worthRefreshPopular( $asOf, $ageNew, $hotTTR, $now ) |
2689 | ); |
2690 | } |
2691 | |
2692 | /** |
2693 | * Check if a key is due for randomized regeneration due to its popularity |
2694 | * |
2695 | * This is used so that popular keys can preemptively refresh themselves for higher |
2696 | * consistency (especially in the case of purge loss/delay). Unpopular keys can remain |
2697 | * in cache with their high nominal TTL. This means popular keys keep good consistency, |
2698 | * whether the data changes frequently or not, and long-tail keys get to stay in cache |
2699 | * and get hits too. Similar to worthRefreshExpiring(), randomization is used. |
2700 | * |
2701 | * @param float $asOf UNIX timestamp of the value |
2702 | * @param int $ageNew Age of key when this might recommend refreshing (seconds) |
2703 | * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds) |
2704 | * @param float $now The current UNIX timestamp |
2705 | * @return bool |
2706 | */ |
2707 | protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) { |
2708 | if ( $ageNew < 0 || $timeTillRefresh <= 0 ) { |
2709 | return false; |
2710 | } |
2711 | |
2712 | $age = $now - $asOf; |
2713 | $timeOld = $age - $ageNew; |
2714 | if ( $timeOld <= 0 ) { |
2715 | return false; |
2716 | } |
2717 | |
2718 | $popularHitsPerSec = 1; |
2719 | // Lifecycle is: new, ramp-up refresh chance, full refresh chance. |
2720 | // Note that the "expected # of refreshes" for the ramp-up time range is half |
2721 | // of what it would be if P(refresh) was at its full value during that time range. |
2722 | $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 ); |
2723 | // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes) |
2724 | // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1 (by definition) |
2725 | // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec) |
2726 | $chance = 1 / ( $popularHitsPerSec * $refreshWindowSec ); |
2727 | // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes |
2728 | $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1; |
2729 | |
2730 | return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance ); |
2731 | } |
2732 | |
2733 | /** |
2734 | * Check if a key is nearing expiration and thus due for randomized regeneration |
2735 | * |
2736 | * If $curTTL is greater than the "low" threshold (e.g. not nearing expiration) then this |
2737 | * returns false. If $curTTL <= 0 (e.g. value already expired), then this returns false. |
2738 | * Otherwise, the chance of this returning true increases steadily from 0% to 100% as |
2739 | * $curTTL moves from the "low" threshold down to 0 seconds. |
2740 | * |
2741 | * The logical TTL will be used as the "low" threshold if it is less than $lowTTL. |
2742 | * |
2743 | * This method uses deadline-aware randomization in order to handle wide variations |
2744 | * of cache access traffic without the need for configuration or expensive state. |
2745 | * |
2746 | * @param float $curTTL Approximate TTL left on the key |
2747 | * @param float $logicalTTL Full logical TTL assigned to the key; 0 for "infinite" |
2748 | * @param float $lowTTL Consider a refresh when $curTTL is less than this; the "low" threshold |
2749 | * @return bool |
2750 | */ |
2751 | protected function worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) { |
2752 | if ( $lowTTL <= 0 ) { |
2753 | return false; |
2754 | } |
2755 | // T264787: avoid having keys start off with a high chance of being refreshed; |
2756 | // the point where refreshing becomes possible cannot precede the key lifetime. |
2757 | $effectiveLowTTL = min( $lowTTL, $logicalTTL ?: INF ); |
2758 | |
2759 | // How long the value was in the "low TTL" phase |
2760 | $timeOld = $effectiveLowTTL - $curTTL; |
2761 | if ( $timeOld <= 0 || $timeOld >= $effectiveLowTTL ) { |
2762 | return false; |
2763 | } |
2764 | |
2765 | // Ratio of the low TTL phase that has elapsed (r) |
2766 | $ttrRatio = $timeOld / $effectiveLowTTL; |
2767 | // Use p(r) as the monotonically increasing "chance of refresh" function, |
2768 | // having p(0)=0 and p(1)=1. The value expires at the nominal expiry. |
2769 | $chance = $ttrRatio ** 4; |
2770 | |
2771 | return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance ); |
2772 | } |
2773 | |
2774 | /** |
2775 | * Check that a wrapper value exists and has an acceptable age |
2776 | * |
2777 | * @param array|false $value Value wrapper or false |
2778 | * @param float $asOf Value generation "as of" timestamp |
2779 | * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp |
2780 | * @return bool |
2781 | */ |
2782 | protected function isValid( $value, $asOf, $minAsOf ) { |
2783 | return ( $value !== false && $asOf >= $minAsOf ); |
2784 | } |
2785 | |
2786 | /** |
2787 | * @param mixed $value |
2788 | * @param int $ttl Seconds to live or zero for "indefinite" |
2789 | * @param int|null $version Value version number or null if not versioned |
2790 | * @param float $now Unix Current timestamp just before calling set() |
2791 | * @return array |
2792 | */ |
2793 | private function wrap( $value, $ttl, $version, $now ) { |
2794 | // Returns keys in ascending integer order for PHP7 array packing: |
2795 | // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html |
2796 | $wrapped = [ |
2797 | self::FLD_FORMAT_VERSION => self::VERSION, |
2798 | self::FLD_VALUE => $value, |
2799 | self::FLD_TTL => $ttl, |
2800 | self::FLD_TIME => $now |
2801 | ]; |
2802 | if ( $version !== null ) { |
2803 | $wrapped[self::FLD_VALUE_VERSION] = $version; |
2804 | } |
2805 | |
2806 | return $wrapped; |
2807 | } |
2808 | |
2809 | /** |
2810 | * @param array|string|false $wrapped The entry at a cache key (false if key is nonexistant) |
2811 | * @param float $now Unix Current timestamp (preferably pre-query) |
2812 | * @return array<int,mixed> Result map/n-tuple that includes the following: |
2813 | * - WANObjectCache::RES_VALUE: value or false if absent/tombstoned/malformed |
2814 | * - WANObjectCache::KEY_VERSION: value version number; null if there is no value |
2815 | * - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if there is no value |
2816 | * - WANObjectCache::KEY_TTL: assigned logical TTL (seconds); null if there is no value |
2817 | * - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if not tombstoned |
2818 | * - WANObjectCache::RES_CHECK_AS_OF: null placeholder for highest "check" key timestamp |
2819 | * - WANObjectCache::RES_TOUCH_AS_OF: null placeholder for highest "touched" timestamp |
2820 | * - WANObjectCache::KEY_CUR_TTL: remaining logical TTL (seconds) (negative if tombstoned) |
2821 | * @phan-return array{0:mixed,1:mixed,2:?float,3:?int,4:?float,5:?float,6:?float,7:?float} |
2822 | */ |
2823 | private function unwrap( $wrapped, $now ) { |
2824 | // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html |
2825 | $res = [ |
2826 | // Attributes that only depend on the fetched key value |
2827 | self::RES_VALUE => false, |
2828 | self::RES_VERSION => null, |
2829 | self::RES_AS_OF => null, |
2830 | self::RES_TTL => null, |
2831 | self::RES_TOMB_AS_OF => null, |
2832 | // Attributes that depend on caller-specific "check" keys or "touched callbacks" |
2833 | self::RES_CHECK_AS_OF => null, |
2834 | self::RES_TOUCH_AS_OF => null, |
2835 | self::RES_CUR_TTL => null |
2836 | ]; |
2837 | |
2838 | if ( is_array( $wrapped ) ) { |
2839 | // Entry expected to be a cached value; validate it |
2840 | if ( |
2841 | ( $wrapped[self::FLD_FORMAT_VERSION] ?? null ) === self::VERSION && |
2842 | $wrapped[self::FLD_TIME] >= $this->epoch |
2843 | ) { |
2844 | if ( $wrapped[self::FLD_TTL] > 0 ) { |
2845 | // Get the approximate time left on the key |
2846 | $age = $now - $wrapped[self::FLD_TIME]; |
2847 | $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 ); |
2848 | } else { |
2849 | // Key had no TTL, so the time left is unbounded |
2850 | $curTTL = INF; |
2851 | } |
2852 | $res[self::RES_VALUE] = $wrapped[self::FLD_VALUE]; |
2853 | $res[self::RES_VERSION] = $wrapped[self::FLD_VALUE_VERSION] ?? null; |
2854 | $res[self::RES_AS_OF] = $wrapped[self::FLD_TIME]; |
2855 | $res[self::RES_CUR_TTL] = $curTTL; |
2856 | $res[self::RES_TTL] = $wrapped[self::FLD_TTL]; |
2857 | } |
2858 | } else { |
2859 | // Entry expected to be a tombstone; parse it |
2860 | $purge = $this->parsePurgeValue( $wrapped ); |
2861 | if ( $purge !== null ) { |
2862 | // Tombstoned keys should always have a negative "current TTL" |
2863 | $curTTL = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE ); |
2864 | $res[self::RES_CUR_TTL] = $curTTL; |
2865 | $res[self::RES_TOMB_AS_OF] = $purge[self::PURGE_TIME]; |
2866 | } |
2867 | } |
2868 | |
2869 | return $res; |
2870 | } |
2871 | |
2872 | /** |
2873 | * @param string $key Cache key in the format `<keyspace>:<keygroup>[:<other components>]...` |
2874 | * as formatted by WANObjectCache::makeKey() or ::makeKeyGlobal. |
2875 | * @return string The key group of this cache key |
2876 | */ |
2877 | private function determineKeyGroupForStats( $key ) { |
2878 | $parts = explode( ':', $key, 3 ); |
2879 | // Fallback in case the key was not made by makeKey. |
2880 | // Replace dots because they are special in StatsD (T232907) |
2881 | return strtr( $parts[1] ?? $parts[0], '.', '_' ); |
2882 | } |
2883 | |
2884 | /** |
2885 | * Extract purge metadata from cached value if it is a valid purge value |
2886 | * |
2887 | * Valid purge values come from makeTombstonePurgeValue()/makeCheckKeyPurgeValue() |
2888 | * |
2889 | * @param mixed $value Cached value |
2890 | * @return array|null Tuple of (UNIX timestamp, hold-off seconds); null if value is invalid |
2891 | */ |
2892 | private function parsePurgeValue( $value ) { |
2893 | if ( !is_string( $value ) ) { |
2894 | return null; |
2895 | } |
2896 | |
2897 | $segments = explode( ':', $value, 3 ); |
2898 | $prefix = $segments[0]; |
2899 | if ( $prefix !== self::PURGE_VAL_PREFIX ) { |
2900 | // Not a purge value |
2901 | return null; |
2902 | } |
2903 | |
2904 | $timestamp = (float)$segments[1]; |
2905 | // makeTombstonePurgeValue() doesn't store hold-off TTLs |
2906 | $holdoff = isset( $segments[2] ) ? (int)$segments[2] : self::HOLDOFF_TTL; |
2907 | |
2908 | if ( $timestamp < $this->epoch ) { |
2909 | // Purge value is too old |
2910 | return null; |
2911 | } |
2912 | |
2913 | return [ self::PURGE_TIME => $timestamp, self::PURGE_HOLDOFF => $holdoff ]; |
2914 | } |
2915 | |
2916 | /** |
2917 | * @param float $timestamp UNIX timestamp |
2918 | * @return string Wrapped purge value; format is "PURGED:<timestamp>" |
2919 | */ |
2920 | private function makeTombstonePurgeValue( float $timestamp ) { |
2921 | return self::PURGE_VAL_PREFIX . ':' . (int)$timestamp; |
2922 | } |
2923 | |
2924 | /** |
2925 | * @param float $timestamp UNIX timestamp |
2926 | * @param int $holdoff In seconds |
2927 | * @param array|null &$purge Unwrapped purge value array [returned] |
2928 | * @return string Wrapped purge value; format is "PURGED:<timestamp>:<holdoff>" |
2929 | */ |
2930 | private function makeCheckPurgeValue( float $timestamp, int $holdoff, array &$purge = null ) { |
2931 | $normalizedTime = (int)$timestamp; |
2932 | // Purge array that matches what parsePurgeValue() would have returned |
2933 | $purge = [ self::PURGE_TIME => (float)$normalizedTime, self::PURGE_HOLDOFF => $holdoff ]; |
2934 | |
2935 | return self::PURGE_VAL_PREFIX . ":$normalizedTime:$holdoff"; |
2936 | } |
2937 | |
2938 | /** |
2939 | * @param string $group |
2940 | * @return MapCacheLRU |
2941 | */ |
2942 | private function getProcessCache( $group ) { |
2943 | if ( !isset( $this->processCaches[$group] ) ) { |
2944 | [ , $size ] = explode( ':', $group ); |
2945 | $this->processCaches[$group] = new MapCacheLRU( (int)$size ); |
2946 | if ( $this->wallClockOverride !== null ) { |
2947 | $this->processCaches[$group]->setMockTime( $this->wallClockOverride ); |
2948 | } |
2949 | } |
2950 | |
2951 | return $this->processCaches[$group]; |
2952 | } |
2953 | |
2954 | /** |
2955 | * @param ArrayIterator $keys |
2956 | * @param array $opts |
2957 | * @return string[] Map of (ID => cache key) |
2958 | */ |
2959 | private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) { |
2960 | $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE; |
2961 | |
2962 | $keysMissing = []; |
2963 | if ( $pcTTL > 0 && $this->callbackDepth == 0 ) { |
2964 | $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY ); |
2965 | foreach ( $keys as $key => $id ) { |
2966 | if ( !$pCache->has( $key, $pcTTL ) ) { |
2967 | $keysMissing[$id] = $key; |
2968 | } |
2969 | } |
2970 | } |
2971 | |
2972 | return $keysMissing; |
2973 | } |
2974 | |
2975 | /** |
2976 | * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey() |
2977 | * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s)); |
2978 | * "check" keys must also be made with makeKey()/makeGlobalKey() |
2979 | * @return array<string,mixed> Map of (sister key => value, or, false if not found) |
2980 | */ |
2981 | private function fetchWrappedValuesForWarmupCache( array $keys, array $checkKeys ) { |
2982 | if ( !$keys ) { |
2983 | return []; |
2984 | } |
2985 | |
2986 | // Get all the value keys to fetch... |
2987 | $sisterKeys = $this->makeSisterKeys( $keys, self::TYPE_VALUE ); |
2988 | // Get all the "check" keys to fetch... |
2989 | foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) { |
2990 | // Note: avoid array_merge() inside loop in case there are many keys |
2991 | if ( is_int( $i ) ) { |
2992 | // Single "check" key that applies to all value keys |
2993 | $sisterKeys[] = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP ); |
2994 | } else { |
2995 | // List of "check" keys that apply to a specific value key |
2996 | foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) { |
2997 | $sisterKeys[] = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP ); |
2998 | } |
2999 | } |
3000 | } |
3001 | |
3002 | $wrappedBySisterKey = $this->cache->getMulti( $sisterKeys ); |
3003 | $wrappedBySisterKey += array_fill_keys( $sisterKeys, false ); |
3004 | |
3005 | return $wrappedBySisterKey; |
3006 | } |
3007 | |
3008 | /** |
3009 | * @param string $key Cache key made with makeKey()/makeGlobalKey() |
3010 | * @param float $now Current UNIX timestamp |
3011 | * @return float|null Seconds since the last logged get() miss for this key, or, null |
3012 | */ |
3013 | private function timeSinceLoggedMiss( $key, $now ) { |
3014 | for ( end( $this->missLog ); $miss = current( $this->missLog ); prev( $this->missLog ) ) { |
3015 | if ( $miss[0] === $key ) { |
3016 | return ( $now - $miss[1] ); |
3017 | } |
3018 | } |
3019 | |
3020 | return null; |
3021 | } |
3022 | |
3023 | /** |
3024 | * @return float UNIX timestamp |
3025 | * @codeCoverageIgnore |
3026 | */ |
3027 | protected function getCurrentTime() { |
3028 | return $this->wallClockOverride ?: microtime( true ); |
3029 | } |
3030 | |
3031 | /** |
3032 | * @param float|null &$time Mock UNIX timestamp for testing |
3033 | * @codeCoverageIgnore |
3034 | */ |
3035 | public function setMockTime( &$time ) { |
3036 | $this->wallClockOverride =& $time; |
3037 | $this->cache->setMockTime( $time ); |
3038 | foreach ( $this->processCaches as $pCache ) { |
3039 | $pCache->setMockTime( $time ); |
3040 | } |
3041 | } |
3042 | } |