-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStarPageCache.php
More file actions
512 lines (447 loc) · 17 KB
/
Copy pathStarPageCache.php
File metadata and controls
512 lines (447 loc) · 17 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
<?php
declare(strict_types=1);
namespace StarCache;
use Exception;
/**
* StarPageCache
*
* Provides full-page output-buffer caching and fragment (partial) caching for
* WordPress, with first-class Varnish integration.
*
* Architecture alignment
* ----------------------
* - Cache eligibility is determined by StarResponseController::isEligible()
* (single gate, no duplicate logic).
* - Cache-Control headers are set ONLY by StarResponseController::apply().
* - Context (device / experiment) is resolved by StarCacheContext::resolve()
* BEFORE startPageCache() is called. The context hash is embedded in every
* page and fragment cache key so different context buckets are served
* independently without cache poisoning.
* - Invalidation uses StarVersionStore::bump() rather than direct entry
* deletion. A version bump makes all keys built with the old version
* unreachable; entries expire naturally on their TTL.
* - Varnish PURGE requests are still sent for edge-cache invalidation.
* - X-Cache-Tags headers are emitted for targeted CDN tag-based purging.
*
* Fragment / partial cache
* ------------------------
* if (!\StarCache\StarPageCache::getFragment('sidebar')) {
* get_sidebar();
* \StarCache\StarPageCache::saveFragment('sidebar');
* }
*
* @package StarCache
* @author MaximillianGroup (Max Barrett) <maximilliangroup@gmail.com>
* @version 2.1.1
* @license Apache 2.0
*/
class StarPageCache
{
/** Cache group for full pages. */
private const GROUP_PAGE = 'starcache_page';
/** Cache group for fragments. */
private const GROUP_FRAG = 'starcache_frag';
/** Default full-page TTL in seconds (10 minutes). */
public const TTL_PAGE = 600;
/** Default fragment TTL in seconds (1 hour). */
public const TTL_FRAG = 3600;
/** Varnish host/port – override with VARNISH_HOST / VARNISH_PORT constants. */
private const VARNISH_HOST = '127.0.0.1';
private const VARNISH_PORT = 6081;
/** @var string|null Cache key for the page currently being buffered. */
private static ?string $currentPageKey = null;
// -------------------------------------------------------------------------
// Full-page cache
// -------------------------------------------------------------------------
/**
* Start output buffering for pages that are eligible for caching.
*
* Must be called AFTER StarCacheContext::resolve() has run.
* Called on the 'init' hook (priority 1) via starcache.php.
*/
public static function startPageCache(): void
{
if (!StarResponseController::isEligible()) {
// Signal to downstream observers (CDN, ops tools) that this response
// was not eligible for the page cache.
if (!headers_sent()) {
header('X-Cache: BYPASS');
}
return;
}
$key = self::buildPageKey();
// Serve from cache if available
$cached = StarCacheAdapter::get($key, self::GROUP_PAGE);
if ($cached !== false && is_array($cached)) {
self::serveCachedPage($cached);
exit;
}
// Begin buffering so capturePageOutput() is called at shutdown
self::$currentPageKey = $key;
ob_start([self::class, 'capturePageOutput']);
}
/**
* Output-buffer callback: persist the captured HTML and return it.
*
* Note: Cache-Control headers are NOT set here – that is StarResponseController's
* responsibility, which runs on the 'send_headers' / 'wp' action.
*
* @param string $html The complete page HTML.
* @return string The same HTML (unmodified).
*/
public static function capturePageOutput(string $html): string
{
if (self::$currentPageKey === null || strlen(trim($html)) < 10) {
return $html;
}
// Only cache successful, non-redirect responses.
// http_response_code() can return false in CLI / before headers are sent;
// treat that as 200 (cacheable) to avoid skipping valid buffered output.
$statusCode = http_response_code();
if ($statusCode !== false && $statusCode !== 200) {
return $html;
}
// Do not cache responses that carry a Location header (redirects that
// PHP already sent before the output buffer flushed).
$headers = self::collectSafeHeaders();
foreach ($headers as $h) {
if (stripos($h, 'Location:') === 0) {
return $html;
}
}
// Do not cache when another plugin/framework set Cache-Control or Expires
// BEFORE StarResponseController ran. We check the state captured at apply()
// time rather than calling upstreamHeadersExist() directly, because by the
// time this ob callback fires (PHP shutdown), StarCache's own Cache-Control
// header is already in headers_list() — a direct check would always return
// true and prevent any page from being stored.
if (StarResponseController::hadUpstreamHeadersBeforeApply()) {
return $html;
}
// Final eligibility gate immediately before persist so any late request
// state changes (method flags, auth state, bypass filters) are respected.
if (!StarResponseController::isEligible()) {
return $html;
}
$ttl = (int) apply_filters('starcache_page_ttl', self::TTL_PAGE);
$payload = ['html' => $html, 'headers' => $headers, 'time' => time()];
StarCacheAdapter::set(self::$currentPageKey, $payload, $ttl, self::GROUP_PAGE);
// Emit cache-tag header for targeted CDN/Varnish purging
self::sendCacheTags();
// Signal to downstream observers that this response was a cache miss
// (freshly generated and stored).
if (!headers_sent()) {
header('X-Cache: MISS');
}
return $html;
}
/**
* Serve a previously cached page, replaying its safe headers.
*
* @param array $cached Payload stored by capturePageOutput().
*/
private static function serveCachedPage(array $cached): void
{
if (!headers_sent()) {
foreach ($cached['headers'] ?? [] as $header) {
header($header);
}
// Response controller applies Cache-Control; tag header goes here
StarResponseController::apply();
self::sendCacheTags();
// Override X-Cache to indicate a cache HIT
header('X-Cache: HIT');
}
echo $cached['html'] ?? '';
}
// -------------------------------------------------------------------------
// Fragment / partial cache
// -------------------------------------------------------------------------
/**
* Return a cached fragment, or start output buffering so the caller can
* generate and cache it.
*
* Pattern:
* if (!StarPageCache::getFragment('sidebar')) {
* // … render sidebar …
* StarPageCache::saveFragment('sidebar');
* }
*
* The TTL is specified on the paired saveFragment() call, not here.
*
* @param string $name Unique fragment identifier.
* @return bool True if cached content was echoed; false if caller must render.
*/
public static function getFragment(string $name): bool
{
$key = self::buildFragmentKey($name);
$cached = StarCacheAdapter::get($key, self::GROUP_FRAG);
if ($cached !== false) {
echo $cached;
return true;
}
ob_start();
return false;
}
/**
* End output buffering, cache the output under $name, and echo it.
*
* @param string $name Same identifier used in the matching getFragment() call.
* @param int $ttl Time-to-live in seconds.
*/
public static function saveFragment(string $name, int $ttl = self::TTL_FRAG): void
{
$output = ob_get_clean();
if ($output === false) {
return;
}
$key = self::buildFragmentKey($name);
StarCacheAdapter::set($key, $output, $ttl, self::GROUP_FRAG);
echo $output;
}
/**
* Invalidate a single cached fragment by name.
*
* @param string $name
*/
public static function deleteFragment(string $name): void
{
$key = self::buildFragmentKey($name);
StarCacheAdapter::delete($key, self::GROUP_FRAG);
}
// -------------------------------------------------------------------------
// Cache invalidation
// -------------------------------------------------------------------------
/**
* Invalidate page and fragment caches when a post is saved.
*
* Uses version bumping (preferred) so that all cache entries that embedded
* the old content version naturally become unreachable. Also sends a
* targeted Varnish PURGE request for the specific post URL.
*
* @param int $postId
* @param \WP_Post $post
*/
public static function purgeOnSave(int $postId, \WP_Post $post): void
{
if (
(function_exists('wp_is_post_revision') && wp_is_post_revision($postId)) ||
(function_exists('wp_is_post_autosave') && wp_is_post_autosave($postId))
) {
return;
}
// Version bump makes ALL pages/fragments built with the old version
// unreachable – no need to enumerate individual keys.
StarVersionStore::bump(StarVersionStore::GROUP_PAGES);
StarVersionStore::bump(StarVersionStore::GROUP_OBJECTS);
// Send Varnish PURGE for the specific URL as well (edge cache)
if (self::isVarnishEnabled()) {
$url = function_exists('get_permalink') ? get_permalink($postId) : null;
if ($url) {
self::varnishPurge($url);
}
$homeUrl = function_exists('home_url') ? home_url('/') : null;
if ($homeUrl) {
self::varnishPurge($homeUrl);
}
}
do_action('starcache_after_purge', $postId, $post);
}
/**
* Invalidate on post status transition (e.g. draft → publish).
*
* @param string $new
* @param string $old
* @param \WP_Post $post
*/
public static function purgeOnStatusChange(string $new, string $old, \WP_Post $post): void
{
if ($new === $old) {
return;
}
if (in_array($new, ['publish', 'trash'], true) || $old === 'publish') {
self::purgeOnSave($post->ID, $post);
}
}
/**
* Purge a specific URL from the object cache and Varnish.
*
* This is kept for backward compatibility and for callers that need
* targeted invalidation of a known URL.
*
* @param string $url
*/
public static function purgeUrl(string $url): void
{
// Build the key that would have been used for this URL at the current
// version – note this will NOT clear entries built with older versions,
// but those will expire naturally.
$key = self::buildPageKeyFromUrl($url);
StarCacheAdapter::delete($key, self::GROUP_PAGE);
if (self::isVarnishEnabled()) {
self::varnishPurge($url);
}
}
// -------------------------------------------------------------------------
// Backward-compatible bypass helper
// -------------------------------------------------------------------------
/**
* Returns true when the current request must not be served from cache.
*
* Delegates to StarResponseController::isEligible() so the eligibility
* logic lives in exactly one place.
*/
public static function shouldBypass(): bool
{
return !StarResponseController::isEligible();
}
// -------------------------------------------------------------------------
// Varnish helpers
// -------------------------------------------------------------------------
/**
* Emit X-Cache-Tags header for targeted CDN / Varnish purging.
*
* This method only emits informational tag headers – it does NOT set
* Cache-Control (that is StarResponseController's job).
*/
public static function sendCacheTags(): void
{
if (headers_sent()) {
return;
}
if (!function_exists('is_singular') || !function_exists('is_archive')) {
return;
}
if (is_singular()) {
$postId = function_exists('get_queried_object_id') ? get_queried_object_id() : 0;
if ($postId) {
header('X-Cache-Tags: post-' . (int) $postId);
}
} elseif (is_archive() || is_home() || is_front_page()) {
header('X-Cache-Tags: archive');
}
}
/**
* Send an HTTP PURGE request to Varnish for the given URL.
*
* @param string $url
*/
private static function varnishPurge(string $url): void
{
$host = defined('VARNISH_HOST') ? VARNISH_HOST : self::VARNISH_HOST;
$port = defined('VARNISH_PORT') ? (int) VARNISH_PORT : self::VARNISH_PORT;
$parsed = wp_parse_url($url);
if (!is_array($parsed)) {
self::logMessage('Varnish PURGE skipped: malformed URL – ' . $url);
return;
}
$path = ($parsed['path'] ?? '/');
$requestHost = $parsed['host'] ?? ($_SERVER['HTTP_HOST'] ?? 'localhost');
if (!empty($parsed['query'])) {
$path .= '?' . $parsed['query'];
}
$args = [
'method' => 'PURGE',
'timeout' => 5,
'sslverify' => false,
'headers' => ['Host' => $requestHost],
];
$purgeUrl = 'http://' . $host . ':' . $port . $path;
$response = wp_remote_request($purgeUrl, $args);
if (is_wp_error($response)) {
self::logMessage('Varnish PURGE failed for ' . $url . ': ' . $response->get_error_message());
}
}
// -------------------------------------------------------------------------
// Key construction
// -------------------------------------------------------------------------
/**
* Build the context-aware, versioned cache key for the current request URL.
*/
private static function buildPageKey(): string
{
return self::buildPageKeyFromUrl(self::currentUrl());
}
/**
* Build the context-aware, versioned cache key for a given URL.
* Uses StarCacheKey::build() so that context and version are automatically
* included and all key construction rules are applied consistently.
*
* @param string $url
*/
private static function buildPageKeyFromUrl(string $url): string
{
return StarCacheKey::build('page|' . $url, null, StarVersionStore::GROUP_PAGES);
}
/**
* Build the context-aware, versioned cache key for a named fragment.
*
* @param string $name
*/
private static function buildFragmentKey(string $name): string
{
return StarCacheKey::build('fragment|' . $name, null, StarVersionStore::GROUP_OBJECTS);
}
// -------------------------------------------------------------------------
// Utilities
// -------------------------------------------------------------------------
/**
* Returns the full URL of the current request.
*/
private static function currentUrl(): string
{
$scheme = (function_exists('is_ssl') && is_ssl()) ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
return $scheme . '://' . $host . $uri;
}
/**
* Collect headers that are safe to replay from cache (skip Set-Cookie, etc.).
*
* @return string[]
*/
private static function collectSafeHeaders(): array
{
if (!function_exists('headers_list')) {
return [];
}
// Skip headers that StarResponseController owns (to avoid duplicates on replays),
// plus headers that must never be cached.
$skip = [
'set-cookie',
'cache-control',
'vary',
'x-cache',
'x-cache-tags',
'x-starcache-context',
];
$safe = [];
foreach (headers_list() as $header) {
$lower = strtolower(explode(':', $header, 2)[0]);
if (!in_array($lower, $skip, true)) {
$safe[] = $header;
}
}
return $safe;
}
/**
* Returns true when Varnish integration is enabled.
*/
private static function isVarnishEnabled(): bool
{
return (bool) apply_filters('starcache_varnish_enabled', defined('VARNISH_HOST'));
}
/**
* Log a page-cache warning via StarExceptionHandler when available.
*/
private static function logMessage(string $message): void
{
$exception = new \RuntimeException($message);
if (class_exists('\StarExceptionHandler')) {
$logger = \StarExceptionHandler::star_getInstance();
$logger->star_handleException($exception);
} else {
error_log("[StarCache] {$message}");
}
}
}