-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStarCache.php
More file actions
432 lines (377 loc) · 15.2 KB
/
Copy pathStarCache.php
File metadata and controls
432 lines (377 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php
declare(strict_types=1);
namespace StarCache;
use Exception;
/**
* StarCache
*
* Primary public API for data caching in WordPress.
*
* Delegates all backend I/O to StarCacheAdapter so the same call works
* transparently regardless of whether Redis, Memcached, Memcache, or the
* WordPress built-in object cache is active.
*
* Usage (programmatic)
* --------------------
* $cache = new \StarCache\StarCache();
* $cache->star_setCachedData(['key' => 'value'], 'my_feature');
* $data = $cache->star_getCachedData('my_feature');
* $cache->star_flushReloadCachedData('my_feature');
*
* The class is also instantiated internally by starcache.php and wired up
* via WordPress hooks so that it operates automatically.
*
* Multisite
* ---------
* Cache keys are generated by StarCacheKey which embeds the current blog ID,
* giving each site in a network its own isolated cache space.
*
* @package StarCache
* @author MaximillianGroup (Max Barrett) <maximilliangroup@gmail.com>
* @version 2.1.1
* @license Apache 2.0
*/
class StarCache
{
// ------------------------------------------------------------------
// Expiration constants
// ------------------------------------------------------------------
/** One year – for content that should be considered permanently cached. */
public const CACHE_EXPIRATION_STATIC = 31536000; // 365 * 24 * 3600
/** One hour – for content that changes occasionally. */
public const CACHE_EXPIRATION_DYNAMIC = 3600;
/** Cache group used for all data managed by this class. */
public const CACHE_GROUP = 'starcache_data';
/** Internal envelope marker used by remember() payloads. */
private const REMEMBER_ENVELOPE_V1 = 'starcache.remember.v1';
/** Default soft-TTL ratio for remember() entries. */
private const DEFAULT_SOFT_TTL_RATIO = 0.8;
/** Default lock TTL in seconds for stampede protection. */
private const DEFAULT_REMEMBER_LOCK_TTL = 15;
/** Max lock wait in milliseconds when stale-while-revalidate is disabled. */
private const DEFAULT_REMEMBER_WAIT_MS = 200;
// ------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------
/**
* Initialise StarCache.
*
* The adapter is bootstrapped via StarCacheAdapter::init() which is
* idempotent – safe to call multiple times.
*/
public function __construct()
{
StarCacheAdapter::init();
}
// ------------------------------------------------------------------
// Public API
// ------------------------------------------------------------------
/**
* Build the user-group label for cache organisation.
*
* @param string $reference Feature / table name.
* @param string|null $userId Optional user identifier.
* @return string
*/
public function star_getUserGroup(string $reference, ?string $userId = null): string
{
return $userId ? 'user_' . $userId : $reference;
}
/**
* Retrieve cached data.
*
* @param string $reference Feature / table name.
* @param string|null $userId Optional user identifier.
* @param bool|null $found Optional hit flag (true = cache hit, false = cache miss).
* @return mixed Cached value or false on miss / error.
*/
public function star_getCachedData(string $reference, ?string $userId = null, ?bool &$found = null): mixed
{
try {
$key = $this->buildKey($reference, $userId);
$group = $this->star_getUserGroup($reference, $userId);
$hit = StarCacheAdapter::getWithFound($key, $group);
$found = $hit['found'];
return $hit['found'] ? $hit['value'] : false;
} catch (Exception $e) {
$this->logError('Error getting cached data', $e);
$found = false;
return false;
}
}
/**
* Store data in the cache.
*
* @param mixed $data Data to cache (any serialisable value).
* @param string $reference Feature / table name.
* @param string|null $userId Optional user identifier.
* @param bool $isStatic True = long-term (1 year), false = 1 hour.
* @return bool True on success, false on failure.
*/
public function star_setCachedData(mixed $data, string $reference, ?string $userId = null, bool $isStatic = false): bool
{
try {
$key = $this->buildKey($reference, $userId);
$group = $this->star_getUserGroup($reference, $userId);
$expiration = $isStatic ? self::CACHE_EXPIRATION_STATIC : self::CACHE_EXPIRATION_DYNAMIC;
$result = StarCacheAdapter::set($key, $data, $expiration, $group);
if (!$result) {
throw new Exception('Failed to write to cache backend: ' . StarCacheAdapter::getBackend());
}
return true;
} catch (Exception $e) {
$this->logError('Error setting cached data', $e);
return false;
}
}
/**
* Delete a specific cache entry.
*
* @param string $reference
* @param string|null $userId
* @return bool
*/
public function star_deleteCachedData(string $reference, ?string $userId = null): bool
{
try {
$key = $this->buildKey($reference, $userId);
$group = $this->star_getUserGroup($reference, $userId);
return StarCacheAdapter::delete($key, $group);
} catch (Exception $e) {
$this->logError('Error deleting cached data', $e);
return false;
}
}
/**
* Flush the cache entry for a reference (alias for delete, kept for
* backwards compatibility with callers expecting this method name).
*
* @param string $reference
* @param string|null $userId
*/
public function star_flushReloadCachedData(string $reference, ?string $userId = null): void
{
$this->star_deleteCachedData($reference, $userId);
}
/**
* Get or set a cached value using a callback (cache-aside pattern).
*
* Uses lock-based soft-TTL stale protection. When stale data exists, the
* lock holder recomputes synchronously while other callers can reuse stale
* data (or briefly wait when stale reuse is disabled via filter).
*
* @param string $reference
* @param callable $callback Must return the value to cache.
* @param int $ttl Time-to-live in seconds. 0 = use DYNAMIC default.
* @param string|null $userId
* @return mixed
*/
public function star_remember(string $reference, callable $callback, int $ttl = 0, ?string $userId = null): mixed
{
$hardTtl = $ttl > 0 ? $ttl : self::CACHE_EXPIRATION_DYNAMIC;
$softTtl = $this->resolveSoftTtl($hardTtl);
$staleWhileRevalidate = (bool) apply_filters('starcache_remember_swr_enabled', true);
$key = $this->buildKey($reference, $userId);
$group = $this->star_getUserGroup($reference, $userId);
$lockKey = $this->buildRememberLockKey($key);
$hit = StarCacheAdapter::getWithFound($key, $group);
if ($hit['found']) {
$entry = $this->normalizeRememberEntry($hit['value'], $softTtl, $hardTtl);
if ($entry['isFresh']) {
return $entry['value'];
}
if (StarCacheAdapter::add($lockKey, 1, self::DEFAULT_REMEMBER_LOCK_TTL, $group)) {
try {
$value = $callback();
$this->storeRememberEntry($key, $group, $value, $softTtl, $hardTtl);
return $value;
} finally {
StarCacheAdapter::delete($lockKey, $group);
}
}
if ($staleWhileRevalidate && !$entry['isPastHardTtl']) {
return $entry['value'];
}
$reloaded = $this->waitForRememberRefresh($key, $group);
if ($reloaded['found']) {
$latest = $this->normalizeRememberEntry($reloaded['value'], $softTtl, $hardTtl);
if (!$latest['isPastHardTtl']) {
return $latest['value'];
}
}
}
if (StarCacheAdapter::add($lockKey, 1, self::DEFAULT_REMEMBER_LOCK_TTL, $group)) {
try {
$race = StarCacheAdapter::getWithFound($key, $group);
if ($race['found']) {
$entry = $this->normalizeRememberEntry($race['value'], $softTtl, $hardTtl);
if ($entry['isFresh']) {
return $entry['value'];
}
}
$value = $callback();
$this->storeRememberEntry($key, $group, $value, $softTtl, $hardTtl);
return $value;
} finally {
StarCacheAdapter::delete($lockKey, $group);
}
}
$reloaded = $this->waitForRememberRefresh($key, $group);
if ($reloaded['found']) {
$entry = $this->normalizeRememberEntry($reloaded['value'], $softTtl, $hardTtl);
if (!$entry['isPastHardTtl']) {
return $entry['value'];
}
}
$value = $callback();
$this->storeRememberEntry($key, $group, $value, $softTtl, $hardTtl);
return $value;
}
/**
* Store data with an explicit TTL in seconds.
*
* @param mixed $data
* @param string $reference
* @param int $ttl Seconds until expiry.
* @param string|null $userId
* @return bool
*/
public function star_setCachedDataWithTtl(mixed $data, string $reference, int $ttl, ?string $userId = null): bool
{
try {
$key = $this->buildKey($reference, $userId);
$group = $this->star_getUserGroup($reference, $userId);
$result = StarCacheAdapter::set($key, $data, $ttl, $group);
if (!$result) {
throw new Exception('Failed to write to cache backend: ' . StarCacheAdapter::getBackend());
}
return true;
} catch (Exception $e) {
$this->logError('Error setting cached data with TTL', $e);
return false;
}
}
/**
* Return the name of the active cache backend.
*
* @return string One of: 'redis', 'memcached', 'memcache', 'wp'
*/
public function star_getBackend(): string
{
return StarCacheAdapter::getBackend();
}
/**
* Returns true when PHP OPcache is active.
*/
public function star_isOpcacheEnabled(): bool
{
return StarCacheAdapter::isOpcacheEnabled();
}
/**
* Close the underlying connection (no-op for WP cache).
*
* @param bool $isStatic When false, also purge any transients matching the key pattern.
* @param string|null $cacheKey Key prefix for transient cleanup (optional).
*/
public function star_closeConnections(bool $isStatic = false, ?string $cacheKey = null): void
{
StarCacheAdapter::close();
if (!$isStatic && $cacheKey) {
global $wpdb;
if (!is_object($wpdb)) {
return;
}
// Safely search for matching transient keys and delete them
$likePattern = $wpdb->esc_like($cacheKey) . '%';
$transients = $wpdb->get_col($wpdb->prepare(
"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
'_transient_' . $likePattern
));
foreach ($transients as $optionName) {
// option_name is '_transient_{key}', strip prefix for delete_transient()
$transientKey = substr($optionName, strlen('_transient_'));
delete_transient($transientKey);
}
}
}
// ------------------------------------------------------------------
// Private helpers
// ------------------------------------------------------------------
/**
* Build a cache key via StarCacheKey::build() (static, context + version aware).
*/
private function buildKey(string $reference, ?string $userId): string
{
return StarCacheKey::build($reference, $userId, StarVersionStore::GROUP_OBJECTS);
}
private function buildRememberLockKey(string $key): string
{
return 'remember_lock:' . $key;
}
/**
* @return array{value:mixed,isFresh:bool,isPastHardTtl:bool}
*/
private function normalizeRememberEntry(mixed $raw, int $softTtl, int $hardTtl): array
{
if (
is_array($raw)
&& ($raw['marker'] ?? '') === self::REMEMBER_ENVELOPE_V1
&& array_key_exists('value', $raw)
) {
$createdAt = (int) ($raw['created_at'] ?? 0);
$soft = max(1, (int) ($raw['soft_ttl'] ?? $softTtl));
$hard = max($soft, (int) ($raw['hard_ttl'] ?? $hardTtl));
$age = max(0, time() - $createdAt);
$fresh = $age < $soft;
$isPastHardTtl = $age >= $hard;
return ['value' => $raw['value'], 'isFresh' => $fresh && !$isPastHardTtl, 'isPastHardTtl' => $isPastHardTtl];
}
return ['value' => $raw, 'isFresh' => true, 'isPastHardTtl' => false];
}
private function storeRememberEntry(string $key, string $group, mixed $value, int $softTtl, int $hardTtl): bool
{
$payload = [
'marker' => self::REMEMBER_ENVELOPE_V1,
'value' => $value,
'created_at' => time(),
'soft_ttl' => $softTtl,
'hard_ttl' => $hardTtl,
];
return StarCacheAdapter::set($key, $payload, $hardTtl, $group);
}
private function resolveSoftTtl(int $hardTtl): int
{
$default = max(1, (int) floor($hardTtl * self::DEFAULT_SOFT_TTL_RATIO));
$softTtl = (int) apply_filters('starcache_remember_soft_ttl', $default, $hardTtl);
// Keep soft TTL valid even for very short hard TTLs.
return max(1, min($softTtl, $hardTtl));
}
/**
* @return array{found:bool,value:mixed}
*/
private function waitForRememberRefresh(string $key, string $group): array
{
$waitMs = (int) apply_filters('starcache_remember_lock_wait_ms', self::DEFAULT_REMEMBER_WAIT_MS);
$waitMs = max(0, $waitMs);
if ($waitMs <= 0) {
return ['found' => false, 'value' => false];
}
usleep($waitMs * 1000);
return StarCacheAdapter::getWithFound($key, $group);
}
/**
* Log errors via StarExceptionHandler when available, otherwise error_log().
*
* StarExceptionHandler is an optional external class expected in the global
* namespace (not within StarCache\). The leading backslash is intentional.
*/
private function logError(string $message, Exception $e): void
{
if (class_exists('\StarExceptionHandler')) {
$logger = \StarExceptionHandler::star_getInstance();
$logger->star_handleException($e);
} else {
error_log("[StarCache] {$message}: {$e->getMessage()}\n{$e->getTraceAsString()}");
}
}
}