-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpressable-solutions-cache-warmer.php
More file actions
722 lines (641 loc) · 26 KB
/
Copy pathpressable-solutions-cache-warmer.php
File metadata and controls
722 lines (641 loc) · 26 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<?php
/**
* Plugin Name: Pressable Solutions Cache Warmer
* Description: Warm + measure + recommend. Tick-endpoint-driven edge/Batcache warmer with built-in cache-health measurement and verdict reporting. Install as mu-plugin.
* Version: 1.2.0
* Author: Pressable Solutions (Phillip Clapham)
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
* ARCHITECTURE
* - NO WP-cron dependency. WP Cloud containers have no platform cron runner; wp-cron is
* traffic-spawned, and a fully-warm site generates zero PHP requests (edge HITs never
* reach origin, Batcache HITs exit in advanced-cache.php) -> a cron-scheduled warmer
* self-oscillates. Instead: an external pinger (GitHub Actions / uptime monitor / fleet
* pinger) hits /?pscw_tick=<secret> every ~5 min; the handler runs ONE time-boxed,
* interval-gated warm/measure cycle inline at muplugins_loaded and exits before
* themes/plugins load.
* - Polite by construction: 1 concurrent fetch ever, sleep between fetches,
* responsiveness pre-check (skips the whole cycle if the site is slow/erroring),
* time-boxed cycles with cursor resume.
* - Measure-first: installs in `measure` mode (observe, log, no behavior change).
* `wp pscw report` issues the verdict: healthy-warm / needs-warming / cache-poisoned /
* inconclusive. Warming (`warm` mode) is an explicit opt-in.
*
* KILL SWITCH: define('PSCW_DISABLED', true) in wp-config.php, or delete this file.
* CONFIG: wp-content/mu-plugins/pscw-config.json (hot-reload, read each cycle).
* SECRET: auto-generated on first use; `wp pscw secret` to view/rotate.
*/
if ( defined( 'PSCW_DISABLED' ) && PSCW_DISABLED ) {
return;
}
if ( ! defined( 'ABSPATH' ) ) {
return;
}
define( 'PSCW_VERSION', '1.2.0' );
final class PSCW_Warmer {
const OPT_SECRET = 'pscw_secret';
const OPT_LOCK = 'pscw_lock';
const OPT_LAST_HOT = 'pscw_last_hot';
const OPT_LAST_BROAD = 'pscw_last_broad';
const OPT_CURSOR = 'pscw_broad_cursor';
const OPT_SITEMAP = 'pscw_sitemap_cache';
const OPT_PURGEQ = 'pscw_purge_queue';
const OPT_AGG = 'pscw_aggregates';
/** Defaults — overridable via pscw-config.json (hot-reload). */
private static $defaults = array(
'mode' => 'measure', // off | measure | warm
'hot_urls' => array( '/' ),
'broad_source' => 'sitemap', // sitemap | none
'broad_cap' => 100,
'hot_interval_s' => 240,
'broad_interval_s' => 3600,
'sleep_ms' => 2000,
'fetch_timeout_s' => 10,
'cycle_budget_s' => 90,
'backoff_ms' => 3000, // front-page probe slower than this -> skip cycle
'log_max_bytes' => 1048576, // 1MB then rotate (one .1 generation kept)
'user_agent' => 'Pressable-Solutions-CacheWarmer/1.0',
);
private $config;
public static function boot() {
$self = new self();
// Tick endpoint — handled as early as possible, exits before themes/plugins load.
if ( isset( $_GET['pscw_tick'] ) ) {
$self->handle_tick( (string) $_GET['pscw_tick'] );
// handle_tick() exits.
}
// Purge-awareness: re-warm content that just changed (fires during editor traffic,
// which by definition exists when content changes).
add_action( 'transition_post_status', array( $self, 'on_transition' ), 10, 3 );
// Opportunistic WP-cron bonus on sites with organic traffic. Never relied upon.
add_action( 'pscw_opportunistic_cycle', array( $self, 'opportunistic_cycle' ) );
add_action( 'init', array( $self, 'maybe_schedule_opportunistic' ), 99 );
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'pscw', 'PSCW_CLI' );
}
}
/* ---------------------------------------------------------------------
* Config
* ------------------------------------------------------------------- */
public function config() {
if ( null !== $this->config ) {
return $this->config;
}
$cfg = self::$defaults;
$path = __DIR__ . '/pscw-config.json';
if ( is_readable( $path ) ) {
$json = json_decode( (string) file_get_contents( $path ), true );
if ( is_array( $json ) ) {
$cfg = array_merge( $cfg, array_intersect_key( $json, self::$defaults ) );
}
}
// Sanity clamps — the tool must stay polite no matter what config says.
$cfg['broad_cap'] = min( 500, max( 0, (int) $cfg['broad_cap'] ) );
$cfg['sleep_ms'] = max( 500, (int) $cfg['sleep_ms'] );
$cfg['cycle_budget_s'] = min( 240, max( 10, (int) $cfg['cycle_budget_s'] ) );
$cfg['fetch_timeout_s'] = min( 30, max( 3, (int) $cfg['fetch_timeout_s'] ) );
$this->config = $cfg;
return $cfg;
}
private function secret() {
$s = get_option( self::OPT_SECRET );
if ( ! is_string( $s ) || strlen( $s ) < 32 ) {
$s = bin2hex( random_bytes( 24 ) ); // wp_generate_password is pluggable = unavailable at muplugins_loaded
update_option( self::OPT_SECRET, $s, false );
}
return $s;
}
/* ---------------------------------------------------------------------
* Tick endpoint
* ------------------------------------------------------------------- */
private function handle_tick( $token ) {
// Never cacheable: explicit headers (edge + Batcache both honor no-store),
// pinger contract additionally appends a timestamp param as belt-and-braces.
header( 'Cache-Control: no-cache, no-store, must-revalidate, max-age=0' );
header( 'X-PSCW: ' . PSCW_VERSION );
if ( ! hash_equals( $this->secret(), $token ) ) {
status_header( 403 );
exit;
}
$cfg = $this->config();
if ( 'off' === $cfg['mode'] ) {
status_header( 204 );
exit;
}
// Interval gate: cheapest possible no-op when nothing is due.
if ( ! $this->anything_due( $cfg ) ) {
status_header( 204 );
exit;
}
// Lock (stale-takeover at 2x budget) — two overlapping ticks must not double-fetch.
$now = time();
$lock = (int) get_option( self::OPT_LOCK, 0 );
if ( $lock && ( $now - $lock ) < ( 2 * $cfg['cycle_budget_s'] ) ) {
status_header( 204 );
exit;
}
update_option( self::OPT_LOCK, $now, false );
$summary = $this->run_cycle( $cfg );
delete_option( self::OPT_LOCK );
header( 'Content-Type: application/json' );
echo wp_json_encode( $summary );
exit;
}
private function anything_due( $cfg ) {
$now = time();
if ( $this->purge_queue_due( $now ) ) {
return true;
}
if ( 'warm' === $cfg['mode'] && ( $now - (int) get_option( self::OPT_LAST_HOT, 0 ) ) >= $cfg['hot_interval_s'] ) {
return true;
}
// measure mode samples everything on the broad cadence
if ( ( $now - (int) get_option( self::OPT_LAST_BROAD, 0 ) ) >= $cfg['broad_interval_s'] ) {
return true;
}
return false;
}
/* ---------------------------------------------------------------------
* Cycle
* ------------------------------------------------------------------- */
public function run_cycle( $cfg, $force = false ) {
$now = time();
$budget_end = $now + $cfg['cycle_budget_s'];
$summary = array(
'ran' => true,
'mode' => $cfg['mode'],
'fetched' => 0,
'hits' => 0,
'misses' => 0,
);
// Responsiveness pre-check: the warmer yields to a struggling site by construction.
// Errors/5xx/timeouts back off immediately. Slowness alone needs the catastrophic
// threshold (3x backoff_ms): a 1-4s cold render is NORMAL on the sites this tool
// exists for — it's the disease being treated, not a reason to abort treatment.
$probe = $this->fetch( home_url( '/' ), $cfg, 'probe' );
if ( false === $probe || $probe['code'] >= 500 || $probe['ms'] > ( 3 * $cfg['backoff_ms'] ) ) {
$this->log_record( array( 'event' => 'backoff', 'ts' => $now ), $cfg );
$summary['backoff'] = true;
return $summary;
}
$summary['fetched']++;
$this->tally( $summary, $probe );
$worklist = array();
// 1) Purge queue (highest priority — content that just changed)
foreach ( $this->drain_purge_queue( $now ) as $u ) {
$worklist[] = array( $u, 'purge-rewarm' );
}
// 2) Hot set (warm mode only, on its own cadence)
$hot_due = ( 'warm' === $cfg['mode'] ) && ( $now - (int) get_option( self::OPT_LAST_HOT, 0 ) ) >= $cfg['hot_interval_s'];
if ( $hot_due || $force ) {
foreach ( (array) $cfg['hot_urls'] as $u ) {
$worklist[] = array( $this->absolutize( $u ), 'hot' );
}
update_option( self::OPT_LAST_HOT, $now, false );
}
// 3) Broad set (sitemap), cursor-resumed across cycles
$broad_due = ( $now - (int) get_option( self::OPT_LAST_BROAD, 0 ) ) >= $cfg['broad_interval_s'];
if ( ( $broad_due || $force ) && 'sitemap' === $cfg['broad_source'] && $cfg['broad_cap'] > 0 ) {
$broad = $this->sitemap_urls( $cfg );
$cursor = (int) get_option( self::OPT_CURSOR, 0 );
if ( $cursor >= count( $broad ) ) {
$cursor = 0;
}
for ( $i = $cursor; $i < count( $broad ); $i++ ) {
$worklist[] = array( $broad[ $i ], 'broad:' . $i );
}
}
// Dedupe by URL, preserving first (highest-priority) occurrence.
$seen = array();
$worklist = array_values( array_filter( $worklist, function ( $item ) use ( &$seen ) {
if ( isset( $seen[ $item[0] ] ) ) {
return false;
}
$seen[ $item[0] ] = true;
return true;
} ) );
$home_host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
foreach ( $worklist as $item ) {
list( $url, $tier ) = $item;
if ( time() >= $budget_end ) {
// Save broad cursor so the next cycle resumes instead of restarting.
if ( 0 === strpos( $tier, 'broad:' ) ) {
update_option( self::OPT_CURSOR, (int) substr( $tier, 6 ), false );
}
$summary['budget_exhausted'] = true;
break;
}
// Same-host guard — never fetch off-site no matter what the sitemap says.
if ( wp_parse_url( $url, PHP_URL_HOST ) !== $home_host ) {
continue;
}
usleep( $cfg['sleep_ms'] * 1000 ); // serialized + paced, always
$rec = $this->fetch( $url, $cfg, $tier );
if ( false !== $rec ) {
$summary['fetched']++;
$this->tally( $summary, $rec );
}
if ( 0 === strpos( $tier, 'broad:' ) ) {
update_option( self::OPT_CURSOR, (int) substr( $tier, 6 ) + 1, false );
}
}
// Broad pass completed without exhausting budget -> reset cursor + stamp cadence.
if ( empty( $summary['budget_exhausted'] ) && ( $broad_due || $force ) ) {
update_option( self::OPT_CURSOR, 0, false );
update_option( self::OPT_LAST_BROAD, $now, false );
}
$this->update_aggregates( $summary );
return $summary;
}
private function tally( &$summary, $rec ) {
// "warm" = anything that didn't pay a full PHP render: edge HIT, edge STALE
// (stale-while-revalidate — observed on yyz POP 6/5), or a fast 200 MISS
// served by Batcache at origin (observed live: 38ms vs 1945ms).
$is_edge = isset( $rec['xac'] ) && preg_match( '/hit|stale/i', $rec['xac'] );
if ( $is_edge || ( 200 === (int) $rec['code'] && $rec['ms'] < 300 ) ) {
$summary['hits']++;
} else {
$summary['misses']++;
}
}
/* ---------------------------------------------------------------------
* Fetch + measure (the fetch stream IS the measurement stream)
* ------------------------------------------------------------------- */
private function fetch( $url, $cfg, $tier ) {
$t0 = microtime( true );
$res = wp_remote_get( $url, array(
'timeout' => $cfg['fetch_timeout_s'],
'redirection' => 0, // 301s are a finding (slug drift), not something to follow
'user-agent' => $cfg['user_agent'],
'sslverify' => true,
'cookies' => array(), // anonymous, always
) );
$ms = (int) round( ( microtime( true ) - $t0 ) * 1000 );
if ( is_wp_error( $res ) ) {
$this->log_record( array(
'ts' => time(),
'url' => $url,
'tier' => $tier,
'error' => $res->get_error_code(),
'ms' => $ms,
), $cfg );
return false;
}
$rec = array(
'ts' => time(),
'url' => $url,
'tier' => $tier,
'code' => (int) wp_remote_retrieve_response_code( $res ),
'ms' => $ms,
'xac' => (string) wp_remote_retrieve_header( $res, 'x-ac' ),
'bytes' => strlen( (string) wp_remote_retrieve_body( $res ) ),
);
$xsc = (string) wp_remote_retrieve_header( $res, 'x-sc' );
if ( '' !== $xsc ) {
$rec['xsc'] = $xsc; // platform preload layer detected — report, don't double-warm
}
$cc = wp_remote_retrieve_header( $res, 'cache-control' );
$cc = is_array( $cc ) ? implode( ', ', $cc ) : (string) $cc;
if ( '' !== $cc && preg_match( '/no-store|no-cache|private/i', $cc ) ) {
$rec['nocache'] = 1; // page declares itself uncacheable (password-protected? plugin nocache? 404 path?)
}
$bn = (string) wp_remote_retrieve_header( $res, 'x-nananana' );
if ( '' !== $bn ) {
$rec['bn'] = $bn; // Batcache-Hit / Batcache-Set — direct Batcache layer visibility
}
$setcookie = wp_remote_retrieve_header( $res, 'set-cookie' );
if ( ! empty( $setcookie ) ) {
$rec['set_cookie'] = 1; // anon response carrying Set-Cookie = cache-poisoning signal
}
$this->log_record( $rec, $cfg );
return $rec;
}
/* ---------------------------------------------------------------------
* Sitemap (broad set source), cached 12h
* ------------------------------------------------------------------- */
private function sitemap_urls( $cfg ) {
$cache = get_option( self::OPT_SITEMAP );
if ( is_array( $cache ) && isset( $cache['ts'], $cache['urls'] ) && ( time() - $cache['ts'] ) < 12 * HOUR_IN_SECONDS ) {
return $cache['urls'];
}
$urls = array();
$candidates = array( home_url( '/sitemap_index.xml' ), home_url( '/wp-sitemap.xml' ), home_url( '/sitemap.xml' ) );
foreach ( $candidates as $sm ) {
$found = $this->parse_sitemap( $sm, $cfg, $urls, 0 );
if ( $found ) {
break;
}
}
$urls = array_slice( array_values( array_unique( $urls ) ), 0, $cfg['broad_cap'] );
update_option( self::OPT_SITEMAP, array( 'ts' => time(), 'urls' => $urls ), false );
return $urls;
}
/** Returns true if this sitemap (or its children) yielded URLs. Depth-limited. */
private function parse_sitemap( $sm_url, $cfg, &$urls, $depth ) {
if ( $depth > 2 || count( $urls ) >= $cfg['broad_cap'] ) {
return count( $urls ) > 0;
}
$res = wp_remote_get( $sm_url, array(
'timeout' => $cfg['fetch_timeout_s'],
'user-agent' => $cfg['user_agent'],
) );
if ( is_wp_error( $res ) || 200 !== (int) wp_remote_retrieve_response_code( $res ) ) {
return false;
}
$xml = @simplexml_load_string( (string) wp_remote_retrieve_body( $res ) );
if ( false === $xml ) {
return false;
}
$name = strtolower( $xml->getName() );
if ( 'sitemapindex' === $name ) {
foreach ( $xml->sitemap as $child ) {
$this->parse_sitemap( (string) $child->loc, $cfg, $urls, $depth + 1 );
if ( count( $urls ) >= $cfg['broad_cap'] ) {
break;
}
}
} elseif ( 'urlset' === $name ) {
foreach ( $xml->url as $u ) {
$urls[] = (string) $u->loc;
if ( count( $urls ) >= $cfg['broad_cap'] ) {
break;
}
}
}
return count( $urls ) > 0;
}
/* ---------------------------------------------------------------------
* Purge-awareness
* ------------------------------------------------------------------- */
public function on_transition( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
return;
}
$q = get_option( self::OPT_PURGEQ, array() );
$q[] = array( 'url' => get_permalink( $post ), 'ts' => time() );
$q[] = array( 'url' => home_url( '/' ), 'ts' => time() );
// Bounded + deduped by URL (keep newest entry per URL).
$by_url = array();
foreach ( $q as $e ) {
if ( ! empty( $e['url'] ) ) {
$by_url[ $e['url'] ] = $e;
}
}
update_option( self::OPT_PURGEQ, array_slice( array_values( $by_url ), -20 ), false );
}
private function purge_queue_due( $now ) {
foreach ( (array) get_option( self::OPT_PURGEQ, array() ) as $e ) {
if ( ( $now - (int) $e['ts'] ) >= 60 ) { // let the purge propagate first
return true;
}
}
return false;
}
private function drain_purge_queue( $now ) {
$q = (array) get_option( self::OPT_PURGEQ, array() );
$due = array();
$later = array();
foreach ( $q as $e ) {
if ( ( $now - (int) $e['ts'] ) >= 60 ) {
$due[] = $e['url'];
} else {
$later[] = $e;
}
}
update_option( self::OPT_PURGEQ, $later, false );
return $due;
}
/* ---------------------------------------------------------------------
* Opportunistic WP-cron bonus (never relied upon)
* ------------------------------------------------------------------- */
public function maybe_schedule_opportunistic() {
if ( ! wp_next_scheduled( 'pscw_opportunistic_cycle' ) ) {
wp_schedule_event( time() + 300, 'hourly', 'pscw_opportunistic_cycle' );
}
}
public function opportunistic_cycle() {
$cfg = $this->config();
if ( 'off' === $cfg['mode'] || ! $this->anything_due( $cfg ) ) {
return;
}
$lock = (int) get_option( self::OPT_LOCK, 0 );
if ( $lock && ( time() - $lock ) < ( 2 * $cfg['cycle_budget_s'] ) ) {
return;
}
update_option( self::OPT_LOCK, time(), false );
$this->run_cycle( $cfg );
delete_option( self::OPT_LOCK );
}
/* ---------------------------------------------------------------------
* Logging (JSONL ring file) + aggregates
* ------------------------------------------------------------------- */
public function log_dir() {
$base = wp_upload_dir( null, false );
// Random-suffix dir: log contents are low-sensitivity (own URLs + timings) but
// there's no reason to make the path guessable. nginx ignores .htaccess on
// WP Cloud, so obscurity + index.php is the v1 posture (documented in README).
$suffix = get_option( 'pscw_log_suffix' );
if ( ! $suffix ) {
$suffix = bin2hex( random_bytes( 6 ) );
update_option( 'pscw_log_suffix', $suffix, false );
}
$dir = trailingslashit( $base['basedir'] ) . 'pscw-' . $suffix;
if ( ! is_dir( $dir ) ) {
wp_mkdir_p( $dir );
@file_put_contents( $dir . '/index.php', "<?php // silence\n" );
}
return $dir;
}
private function log_record( $rec, $cfg ) {
$file = $this->log_dir() . '/log.jsonl';
if ( file_exists( $file ) && filesize( $file ) > $cfg['log_max_bytes'] ) {
@rename( $file, $file . '.1' ); // keep one rotated generation
}
@file_put_contents( $file, wp_json_encode( $rec ) . "\n", FILE_APPEND | LOCK_EX );
}
private function update_aggregates( $summary ) {
$agg = get_option( self::OPT_AGG, array( 'cycles' => 0, 'fetched' => 0, 'hits' => 0, 'misses' => 0 ) );
$agg['cycles']++;
$agg['fetched'] += $summary['fetched'];
$agg['hits'] += $summary['hits'];
$agg['misses'] += $summary['misses'];
$agg['last_cycle'] = time();
update_option( self::OPT_AGG, $agg, false );
}
private function absolutize( $u ) {
return ( 0 === strpos( $u, 'http' ) ) ? $u : home_url( $u );
}
}
/* -------------------------------------------------------------------------
* WP-CLI: wp pscw <status|secret|run|report>
* ----------------------------------------------------------------------- */
if ( defined( 'WP_CLI' ) && WP_CLI ) {
class PSCW_CLI {
/** Show config, last-cycle state, and tick URL. */
public function status( $args, $assoc ) {
$w = new PSCW_Warmer();
$cfg = $w->config();
WP_CLI::log( 'mode: ' . $cfg['mode'] );
WP_CLI::log( 'config: ' . wp_json_encode( $cfg ) );
WP_CLI::log( 'aggregates: ' . wp_json_encode( get_option( PSCW_Warmer::OPT_AGG, array() ) ) );
WP_CLI::log( 'broad cursor: ' . get_option( PSCW_Warmer::OPT_CURSOR, 0 ) );
WP_CLI::log( 'log dir: ' . $w->log_dir() );
}
/** Show (or --rotate) the tick secret + full tick URL. */
public function secret( $args, $assoc ) {
if ( isset( $assoc['rotate'] ) ) {
delete_option( PSCW_Warmer::OPT_SECRET );
}
$w = new PSCW_Warmer();
$r = new ReflectionMethod( 'PSCW_Warmer', 'secret' );
$r->setAccessible( true );
$s = $r->invoke( $w );
WP_CLI::log( 'secret: ' . $s );
WP_CLI::log( 'tick URL: ' . home_url( '/?pscw_tick=' . $s . '&t=<timestamp>' ) );
}
/** Force one cycle now (ignores interval gates). For testing. */
public function run( $args, $assoc ) {
$w = new PSCW_Warmer();
$res = $w->run_cycle( $w->config(), true );
WP_CLI::log( wp_json_encode( $res, JSON_PRETTY_PRINT ) );
WP_CLI::success( 'cycle complete' );
}
/**
* Aggregate the JSONL log into per-URL stats + a site verdict.
*
* Three serving layers per record (observed live 6/5: edge entries on idle sites
* evict in ~minutes while Batcache holds for hours — a fast x-ac MISS is a
* Batcache serve, which is a user WIN, not a cold render):
* edge — x-ac HIT
* bcache — x-ac MISS but fast (< 300ms): served by warm Batcache at origin
* render — x-ac MISS and slow: full PHP render (the cost warming eliminates)
*
* ## OPTIONS
* [--days=<n>]
* : Only consider records from the last N days. Default 7.
*/
public function report( $args, $assoc ) {
$days = isset( $assoc['days'] ) ? max( 1, (int) $assoc['days'] ) : 7;
$since = time() - $days * DAY_IN_SECONDS;
$w = new PSCW_Warmer();
$files = array( $w->log_dir() . '/log.jsonl.1', $w->log_dir() . '/log.jsonl' );
$bc_ms = 300; // Batcache-vs-render discrimination threshold (observed: 38ms vs 1945ms)
$stats = array();
$site = array( 'fetches' => 0, 'edge' => 0, 'bcache' => 0, 'render' => 0, 'set_cookie' => 0, 'xsc_seen' => 0, 'errors' => 0, 'nocache' => 0, 'non200' => 0 );
foreach ( $files as $f ) {
if ( ! is_readable( $f ) ) {
continue;
}
$fh = fopen( $f, 'r' );
while ( false !== ( $line = fgets( $fh ) ) ) {
$r = json_decode( $line, true );
if ( ! is_array( $r ) || empty( $r['url'] ) || ( isset( $r['ts'] ) && $r['ts'] < $since ) ) {
continue;
}
$u = $r['url'];
if ( ! isset( $stats[ $u ] ) ) {
$stats[ $u ] = array( 'n' => 0, 'edge' => 0, 'bcache' => 0, 'render' => 0, 'warm_ms' => array(), 'render_ms' => array(), 'codes' => array() );
}
$stats[ $u ]['n']++;
$site['fetches']++;
if ( isset( $r['error'] ) ) {
$site['errors']++;
continue;
}
if ( 200 !== (int) $r['code'] ) {
$site['non200']++;
}
if ( ! empty( $r['nocache'] ) ) {
$site['nocache']++;
}
// STALE = stale-while-revalidate = the visitor got an instant response: edge-warm.
$is_edge = isset( $r['xac'] ) && preg_match( '/hit|stale/i', $r['xac'] );
if ( $is_edge ) {
$layer = 'edge';
} elseif ( 200 === (int) $r['code'] && $r['ms'] < $bc_ms ) {
$layer = 'bcache';
} else {
$layer = 'render';
}
$stats[ $u ][ $layer ]++;
$site[ $layer ]++;
if ( 'render' === $layer ) {
$stats[ $u ]['render_ms'][] = $r['ms'];
} else {
$stats[ $u ]['warm_ms'][] = $r['ms'];
}
if ( ! empty( $r['set_cookie'] ) ) {
$site['set_cookie']++;
}
if ( ! empty( $r['xsc'] ) ) {
$site['xsc_seen']++;
}
$stats[ $u ]['codes'][ $r['code'] ] = true;
}
fclose( $fh );
}
if ( 0 === $site['fetches'] ) {
WP_CLI::warning( 'No records in window. Is the pinger running? (wp pscw secret for the tick URL)' );
return;
}
$rows = array();
foreach ( $stats as $u => $s ) {
$classified = max( 1, $s['edge'] + $s['bcache'] + $s['render'] );
$rows[] = array(
'url' => $u,
'fetches' => $s['n'],
'edge_pct' => round( 100 * $s['edge'] / $classified ),
'bcache_pct' => round( 100 * $s['bcache'] / $classified ),
'render_pct' => round( 100 * $s['render'] / $classified ),
'med_warm_ms' => self::median( $s['warm_ms'] ),
'med_render_ms'=> self::median( $s['render_ms'] ),
'codes' => implode( ',', array_keys( $s['codes'] ) ),
);
}
// Worst-served URLs first.
usort( $rows, function ( $a, $b ) { return $b['render_pct'] - $a['render_pct']; } );
WP_CLI\Utils\format_items( 'table', $rows, array( 'url', 'fetches', 'edge_pct', 'bcache_pct', 'render_pct', 'med_warm_ms', 'med_render_ms', 'codes' ) );
// Verdict: "effective warmth" = anything that didn't pay a full PHP render.
$classified = max( 1, $site['edge'] + $site['bcache'] + $site['render'] );
$warm_rate = ( $site['edge'] + $site['bcache'] ) / $classified;
$cookie_rate = $site['set_cookie'] / $site['fetches'];
$verdict = 'inconclusive (need more data — let measure mode run longer)';
if ( $cookie_rate > 0.5 ) {
$verdict = 'CACHE-POISONED: anonymous responses carry Set-Cookie (' . round( 100 * $cookie_rate ) . '%). Fix the cookie problem first (cookie-strip family) — warming cannot help an uncacheable site.';
} elseif ( $warm_rate > 0.8 ) {
$verdict = 'HEALTHY-WARM: ' . round( 100 * $warm_rate ) . '% effective warmth (edge ' . round( 100 * $site['edge'] / $classified ) . '% + Batcache ' . round( 100 * $site['bcache'] / $classified ) . '%).';
} elseif ( $site['fetches'] >= 20 && $warm_rate < 0.5 ) {
$verdict = 'NEEDS-WARMING: only ' . round( 100 * $warm_rate ) . '% of responses avoid a full render. Enable warm mode (or platform preload when it matures).';
}
if ( $site['xsc_seen'] > 0 ) {
$verdict .= ' NOTE: x-sc header observed — WP Cloud preload layer is active on this site; do not double-warm.';
}
if ( $site['nocache'] > 0 ) {
$verdict .= ' NOTE: ' . $site['nocache'] . ' fetches returned no-cache/no-store/private — those URLs declare themselves uncacheable (password-protected content? plugin nocache? 404 path?). Warming cannot help them; fix the cause or exclude them.';
}
if ( $site['non200'] > 0 ) {
$verdict .= ' NOTE: ' . $site['non200'] . ' non-200 responses — check the URL source (404s = wrong/hand-built URLs; 30x = slug drift since the sitemap was cached).';
}
WP_CLI::log( '' );
WP_CLI::log( sprintf(
'Site: %d fetches | edge %d%% / bcache %d%% / render %d%% | %d errors.',
$site['fetches'],
round( 100 * $site['edge'] / $classified ),
round( 100 * $site['bcache'] / $classified ),
round( 100 * $site['render'] / $classified ),
$site['errors']
) );
WP_CLI::success( 'Verdict: ' . $verdict );
WP_CLI::log( '(unpredictable-GET pattern cannot be auto-detected from the warmer\'s own fetch stream — flag from audit context if applicable.)' );
}
private static function median( $arr ) {
if ( empty( $arr ) ) {
return '';
}
sort( $arr );
return $arr[ (int) floor( count( $arr ) / 2 ) ];
}
}
}
PSCW_Warmer::boot();