PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.1.1
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.1.1
1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 All 29 releases
xspeed / includes / modules / Health / HealthModule.php

HealthModule.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.1.1, at includes/modules/Health/HealthModule.php

252 lines 9.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Health module — read-only diagnostic surface for the dashboard.
4 *
5 * No settings_schema (this is a status panel, not a configuration
6 * surface). The React side renders a custom panel (HealthCard, declared
7 * via `ui_metadata.custom_panel`) instead of going through ModulePanel's
8 * schema-driven path.
9 *
10 * Data sources are all existing services:
11 * - Health::checks() — diagnostic rows
12 * - Cache::get_stats() — cached_pages / size / last_purge /
13 * hits_24h / misses_24h / hit_ratio
14 * - Hit_Counter::buckets() — 24 hourly buckets for the sparkline
15 * - Activity_Log::entries() — newest-first event log
16 *
17 * Tier: Free (per FEATURES.md "Cache Insights" — Cache Performance +
18 * Last 24h chart are Free; Recommendations + Frequently-missed-URLs
19 * stay Pro).
20 *
21 * @package XSpeed
22 */
23
24 declare(strict_types=1);
25
26 namespace XSpeed\Modules\Health;
27
28 defined( 'ABSPATH' ) || exit;
29
30 use XSpeed\Activity_Log;
31 use XSpeed\Cache;
32 use XSpeed\Health;
33 use XSpeed\Hit_Counter;
34 use XSpeed\Module;
35
36 final class HealthModule extends Module {
37
38 public const SLUG = 'health';
39 public const TIER = self::TIER_FREE;
40 public const VERSION = '1.0.0';
41
42 /**
43 * Surface the most important diagnostics in WordPress's built-in
44 * Site Health screen (Tools → Site Health → Status). Admins who
45 * never open the xSpeed dashboard still get a heads-up when
46 * static-rewrite is missing on Apache/LiteSpeed or when the nginx
47 * snippet hasn't been pasted yet — both lead to a 5-10× slowdown
48 * vs the optimal cache hit path.
49 */
50 public function boot(): void {
51 add_filter( 'site_status_tests', array( $this, 'register_site_status_tests' ) );
52
53 // Out-of-band refresh of the Set-Cookie probe. Health::checks()
54 // only ever reads the cached verdict, so the HTTP round-trip
55 // happens here instead of inside a request the user waits on.
56 add_action( \XSpeed\Cookie_Inspector::CRON_HOOK, array( $this, 'refresh_cookie_probe' ) );
57 }
58
59 /** Cron callback: perform the real (blocking) probe off-request. */
60 public function refresh_cookie_probe(): void {
61 \XSpeed\Cookie_Inspector::probe( true );
62 }
63
64 public function register_site_status_tests( array $tests ): array {
65 $tests['direct']['xspeed_static_rewrite'] = array(
66 'label' => __( 'xSpeed static-rewrite cache', 'xspeed' ),
67 'test' => array( $this, 'site_status_static_rewrite' ),
68 );
69 return $tests;
70 }
71
72 /**
73 * Site Health test row. Reports green when the .htaccess block is
74 * present (Apache/LiteSpeed) or yellow with the nginx snippet
75 * embedded when nginx is detected. Skipped entirely when cache is
76 * disabled — no point telling the user to install a rewrite they
77 * haven't opted into.
78 */
79 public function site_status_static_rewrite(): array {
80 $result = array(
81 'label' => __( 'xSpeed static-rewrite cache is active', 'xspeed' ),
82 'status' => 'good',
83 'badge' => array(
84 'label' => __( 'Performance', 'xspeed' ),
85 'color' => 'blue',
86 ),
87 'description' => '<p>' . esc_html__( 'Cache hits bypass PHP for ~5-15ms TTFB.', 'xspeed' ) . '</p>',
88 'test' => 'xspeed_static_rewrite',
89 );
90
91 $cache_enabled = (bool) ( \XSpeed\Settings::get()['cache_enabled'] ?? false );
92 if ( ! $cache_enabled ) {
93 $result['label'] = __( 'xSpeed cache is disabled', 'xspeed' );
94 $result['status'] = 'recommended';
95 $result['description'] = '<p>' . esc_html__( 'Enable the page cache in the xSpeed dashboard to start serving cached HTML for non-logged-in visitors.', 'xspeed' ) . '</p>';
96 return $result;
97 }
98
99 $server_type = \XSpeed\Server::type();
100 if ( \XSpeed\Server::APACHE === $server_type || \XSpeed\Server::LITESPEED === $server_type ) {
101 if ( ! \XSpeed\Cache::rewrite_installed() ) {
102 $result['label'] = __( 'xSpeed .htaccess rewrite block is missing', 'xspeed' );
103 $result['status'] = 'recommended';
104 $result['description'] = '<p>' . esc_html__( 'Without the static-rewrite block, cache hits go through the PHP drop-in (~85ms TTFB) instead of the web server (~5-15ms). Toggle Enable Cache off and on in xSpeed to reinstall the block.', 'xspeed' ) . '</p>';
105 }
106 return $result;
107 }
108
109 if ( \XSpeed\Server::NGINX === $server_type ) {
110 $snippet = \XSpeed\Cache::nginx_snippet();
111 $result['label'] = __( 'xSpeed nginx server config required', 'xspeed' );
112 $result['status'] = 'recommended';
113 $result['description'] = '<p>' . esc_html__( 'xSpeed can\'t write nginx config from PHP. Paste this snippet into your site\'s server { } block, then reload nginx so cache hits serve without booting PHP:', 'xspeed' ) . '</p>'
114 . '<pre style="white-space:pre;overflow-x:auto;background:#f6f7f7;border:1px solid #c3c4c7;border-radius:4px;padding:12px;font-size:12px;line-height:1.4;">'
115 . esc_html( (string) $snippet )
116 . '</pre>';
117 return $result;
118 }
119
120 // Unknown / IIS — no server-level rewrite path available; PHP
121 // drop-in is the best we can offer. Don't flag as broken.
122 $result['label'] = __( 'xSpeed PHP drop-in cache active', 'xspeed' );
123 $result['status'] = 'recommended';
124 $result['description'] = '<p>' . esc_html__( 'Static-rewrite caching needs Apache, LiteSpeed, or nginx. The PHP drop-in is still serving cache hits at ~85ms TTFB on this server.', 'xspeed' ) . '</p>';
125 return $result;
126 }
127
128 public function ui_metadata(): array {
129 return array(
130 'label' => 'Health',
131 'icon' => 'HeartPulse',
132 'description' => 'Diagnostics, hit ratio, and recent cache activity.',
133 // Health is the single host page for all Insights (FBS-83633):
134 // a Recommendations action card + Cache / Visitors / PageSpeed
135 // tabs. HealthPanel renders the Free cache diagnostics (the old
136 // HealthCard) as the Cache tab and hosts the Pro insight panels
137 // as the other tabs via ProSlot.
138 'custom_panel' => 'HealthPanel',
139 );
140 }
141
142 // No settings — explicit empty so Module::rest_routes() doesn't
143 // auto-wire the schema-driven GET+POST.
144 public function settings_schema(): array {
145 return array();
146 }
147
148 public function rest_routes(): array {
149 return array(
150 array(
151 'path' => '/',
152 'methods' => 'GET',
153 'callback' => array( $this, 'rest_get_payload' ),
154 ),
155 );
156 }
157
158 public function cli_commands(): array {
159 return array(
160 array(
161 'name' => 'xspeed health',
162 'callback' => array( $this, 'cli_handler' ),
163 'shortdesc' => 'Print diagnostic checks + cache stats + recent activity.',
164 'synopsis' => array(),
165 ),
166 array(
167 'name' => 'xspeed recommend',
168 'callback' => array( $this, 'cli_recommend' ),
169 'shortdesc' => 'List ranked next-best-action recommendations, or apply one by id.',
170 'synopsis' => array(
171 array(
172 'type' => 'positional',
173 'name' => 'action',
174 'options' => array( 'list', 'apply' ),
175 'optional' => true,
176 ),
177 array(
178 'type' => 'positional',
179 'name' => 'id',
180 'optional' => true,
181 ),
182 ),
183 ),
184 );
185 }
186
187 /** CLI: `wp xspeed recommend [list|apply <id>]` — MCP-reachable via run_command. */
188 public function cli_recommend( array $args, array $assoc ): void {
189 $action = isset( $args[0] ) ? (string) $args[0] : 'list';
190
191 if ( 'apply' === $action ) {
192 $id = isset( $args[1] ) ? (string) $args[1] : '';
193 if ( '' === $id ) {
194 \WP_CLI::error( 'Usage: wp xspeed recommend apply <id>' );
195 return;
196 }
197 $result = \XSpeed\Recommendations::apply( $id );
198 if ( is_wp_error( $result ) ) {
199 \WP_CLI::error( $result->get_error_message() );
200 return;
201 }
202 \WP_CLI::success( sprintf( 'Applied "%s". %d recommendation(s) remain.', $id, count( $result['recommendations'] ) ) );
203 return;
204 }
205
206 $recs = \XSpeed\Recommendations::all();
207 if ( empty( $recs ) ) {
208 \WP_CLI::success( 'No recommendations — configuration looks healthy.' );
209 return;
210 }
211 foreach ( $recs as $i => $rec ) {
212 $fixable = 'apply' === ( $rec['action']['type'] ?? '' ) ? ' (one-click: wp xspeed recommend apply ' . $rec['id'] . ')' : '';
213 \WP_CLI::log( sprintf( '%d. [%s] %s — %s%s', $i + 1, $rec['id'], $rec['title'], $rec['detail'], $fixable ) );
214 }
215 }
216
217 /**
218 * Single endpoint that backs the dashboard panel. Refreshed lazily by
219 * the React side; cheap enough that aggregating into one response is
220 * the right call (the buckets array is at most 24 entries; activity
221 * is capped at 50).
222 */
223 public function rest_get_payload( \WP_REST_Request $request ) {
224 return rest_ensure_response( $this->payload() );
225 }
226
227 public function payload(): array {
228 return array(
229 'checks' => Health::checks(),
230 'stats' => Cache::get_stats(),
231 'buckets' => Hit_Counter::buckets(),
232 'activity' => Activity_Log::entries(),
233 );
234 }
235
236 public function cli_handler( array $args, array $assoc ): void {
237 $payload = $this->payload();
238 \WP_CLI::log( '== Checks ==' );
239 foreach ( $payload['checks'] as $c ) {
240 \WP_CLI::log( sprintf( '[%s] %s — %s', strtoupper( $c['tone'] ), $c['label'], $c['detail'] ) );
241 }
242 \WP_CLI::log( '' );
243 \WP_CLI::log( '== Stats (24h) ==' );
244 \WP_CLI::log( sprintf( 'Hits %d · Misses %d · Hit ratio %.2f%%', $payload['stats']['hits_24h'], $payload['stats']['misses_24h'], $payload['stats']['hit_ratio'] * 100 ) );
245 \WP_CLI::log( '' );
246 \WP_CLI::log( '== Recent activity ==' );
247 foreach ( array_slice( $payload['activity'], 0, 10 ) as $e ) {
248 \WP_CLI::log( sprintf( '%s [%s] %s', gmdate( 'Y-m-d H:i:s', $e['ts'] ), $e['severity'], $e['message'] ) );
249 }
250 }
251 }
252