PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.2.0
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.2.0
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 1.2.0 All 28 releases
xspeed / includes / modules / Preloader / PreloaderModule.php

PreloaderModule.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.2.0, at includes/modules/Preloader/PreloaderModule.php

343 lines 11.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Cache Preloader module.
4 *
5 * Owns the preloader's settings + the dashboard custom panel that pairs
6 * the schema controls with a Start/Stop/Status surface.
7 *
8 * Tier: Free (LiteSpeed parity — their crawler is free).
9 * Roadmap: §3 P3.1.
10 *
11 * @package XSpeed
12 */
13
14 declare(strict_types=1);
15
16 namespace XSpeed\Modules\Preloader;
17
18 defined( 'ABSPATH' ) || exit;
19
20 use XSpeed\Module;
21 use XSpeed\Preloader;
22 use XSpeed\Settings_Manager;
23
24 final class PreloaderModule extends Module {
25
26 public const SLUG = 'preloader';
27 public const TIER = self::TIER_FREE;
28 public const VERSION = '1.0.0';
29
30 public function ui_metadata(): array {
31 return array(
32 'label' => 'Preloader',
33 'tab_label' => 'Crawl Now', // its own tab on the Preloader page
34 'icon' => 'Wand2',
35 'description' => 'Crawl the sitemap to warm cache so visitors never hit a cold MISS.',
36 // Custom panel wraps the schema-driven settings with a
37 // Start/Stop control surface + a live status readout
38 // (queue depth, last URL, recent errors).
39 'custom_panel' => 'PreloaderHost',
40 );
41 }
42
43 public function settings_schema(): array {
44 return array(
45 'enabled' => array(
46 'type' => 'bool',
47 'default' => false,
48 'label' => 'Enable Preloader',
49 'description' => 'When on, xSpeed crawls the sitemap on the schedule below and warms the page cache.',
50 ),
51 'schedule' => array(
52 'type' => 'enum',
53 'default' => 'manual',
54 'options' => array( 'manual', 'hourly', 'daily', 'weekly' ),
55 'option_labels' => array(
56 'manual' => 'Manual',
57 'hourly' => 'Hourly',
58 'daily' => 'Daily',
59 'weekly' => 'Weekly',
60 ),
61 'label' => 'Schedule',
62 'description' => 'How often to start a fresh crawl. Manual means you trigger it from the dashboard.',
63 'dependsOn' => array( 'field' => 'enabled' ),
64 ),
65 'batch_size' => array(
66 'type' => 'int',
67 'default' => 5,
68 'min' => 1,
69 'max' => 50,
70 'label' => 'Batch Size',
71 'description' => 'URLs warmed per cron tick. Higher = faster crawl, more load on the origin.',
72 'dependsOn' => array( 'field' => 'enabled' ),
73 ),
74 'sitemap_url' => array(
75 'type' => 'string',
76 'default' => '',
77 'label' => 'Sitemap URL (optional)',
78 'description' => 'Override the auto-detected WordPress core sitemap (/wp-sitemap.xml). Leave blank for default.',
79 'dependsOn' => array( 'field' => 'enabled' ),
80 ),
81 'warm_on_publish' => array(
82 'type' => 'bool',
83 'default' => true,
84 'label' => 'Warm new content immediately',
85 'description' => 'When a post or page is published, fetch it once so the first visitor sees a cache HIT, not a cold MISS.',
86 'dependsOn' => array( 'field' => 'enabled' ),
87 ),
88 'warm_on_comment' => array(
89 'type' => 'bool',
90 'default' => false,
91 'label' => 'Re-warm after comments',
92 'description' => 'Re-warm a page after a comment is posted (Cache purges the page on comment; this fetches it back into cache).',
93 'dependsOn' => array( 'field' => 'enabled' ),
94 ),
95 );
96 }
97
98 public function rest_routes(): array {
99 // Module base gives us GET + POST for settings under
100 // /xspeed/v1/preloader/. We add Start/Stop/Status alongside.
101 $default = parent::rest_routes();
102 return array_merge(
103 $default,
104 array(
105 array(
106 'path' => '/start',
107 'methods' => 'POST',
108 'callback' => array( $this, 'rest_start' ),
109 ),
110 array(
111 'path' => '/stop',
112 'methods' => 'POST',
113 'callback' => array( $this, 'rest_stop' ),
114 ),
115 array(
116 'path' => '/status',
117 'methods' => 'GET',
118 'callback' => array( $this, 'rest_status' ),
119 ),
120 )
121 );
122 }
123
124 public function cli_commands(): array {
125 return array(
126 array(
127 'name' => 'xspeed preloader',
128 'callback' => array( $this, 'cli_handler' ),
129 'shortdesc' => 'Drive the cache preloader (start | stop | status).',
130 'synopsis' => array(
131 array(
132 'type' => 'positional',
133 'name' => 'action',
134 'options' => array( 'start', 'stop', 'status' ),
135 'optional' => false,
136 ),
137 ),
138 ),
139 );
140 }
141
142 public function boot(): void {
143 add_action( Preloader::CRON_HOOK, array( Preloader::class, 'tick' ) );
144 add_action( 'xspeed_preloader_recurring', array( Preloader::class, 'recurring_kickoff' ) );
145
146 // Apply schedule changes immediately whenever this module's
147 // settings get written (the standard per-module option hook).
148 add_action( 'update_option_xspeed_module_preloader', array( $this, 'on_settings_change' ), 10, 2 );
149 add_action( 'add_option_xspeed_module_preloader', array( $this, 'on_settings_added' ), 10, 2 );
150
151 // Content warmer — auto-warm a single URL on post publish /
152 // comment so the first visitor after a publish/comment sees a
153 // HIT, not the cold MISS that Cache::purge_all just created.
154 $opts = Settings_Manager::get( self::SLUG );
155 if ( ! empty( $opts['warm_on_publish'] ) ) {
156 add_action( 'transition_post_status', array( $this, 'on_post_transition' ), 10, 3 );
157 }
158 if ( ! empty( $opts['warm_on_comment'] ) ) {
159 add_action( 'comment_post', array( $this, 'on_comment_post' ), 20, 2 );
160 }
161 }
162
163 /**
164 * Hook: a post transitioned to publish. Warm its permalink once on
165 * shutdown so the post-save request itself stays fast.
166 *
167 * @param string $new New post status.
168 * @param string $old Old post status.
169 * @param \WP_Post $post Post object.
170 */
171 public function on_post_transition( $new, $old, $post ): void {
172 if ( 'publish' !== $new || 'publish' === $old ) {
173 return;
174 }
175 // Only warm public post types so we don't crawl private CPTs.
176 $post_type_obj = get_post_type_object( $post->post_type );
177 if ( ! $post_type_obj || empty( $post_type_obj->public ) ) {
178 return;
179 }
180 $url = get_permalink( $post );
181 if ( ! $url ) {
182 return;
183 }
184 // Defer to shutdown so the user's "Publish" click returns fast.
185 // (Cache::purge_all has already fired by then on the save_post
186 // hook, so the warm fetch lands AFTER the purge.)
187 add_action(
188 'shutdown',
189 static function () use ( $url ) {
190 Preloader::warm_one( $url, 'post published' );
191 },
192 20
193 );
194 }
195
196 /**
197 * Hook: comment posted. Warm the post's permalink so the page is
198 * back in cache before the next visitor lands.
199 *
200 * @param int $comment_id The comment ID.
201 * @param int $approved 1, 0, or 'spam'.
202 */
203 public function on_comment_post( $comment_id, $approved ): void {
204 // Approved comments only — pending/spam don't show on the
205 // public page and shouldn't trigger a warm.
206 if ( 1 !== (int) $approved ) {
207 return;
208 }
209 $comment = get_comment( $comment_id );
210 if ( ! $comment || ! $comment->comment_post_ID ) {
211 return;
212 }
213 $url = get_permalink( (int) $comment->comment_post_ID );
214 if ( ! $url ) {
215 return;
216 }
217 add_action(
218 'shutdown',
219 static function () use ( $url ) {
220 Preloader::warm_one( $url, 'comment posted' );
221 },
222 20
223 );
224 }
225
226 public function deactivate(): void {
227 wp_clear_scheduled_hook( Preloader::CRON_HOOK );
228 wp_clear_scheduled_hook( 'xspeed_preloader_recurring' );
229 }
230
231 public function on_settings_change( $old, $new ): void {
232 $enabled = is_array( $new ) && ! empty( $new['enabled'] );
233 $schedule = is_array( $new ) ? (string) ( $new['schedule'] ?? 'manual' ) : 'manual';
234 Preloader::apply_schedule( $enabled ? $schedule : 'manual' );
235 }
236
237 public function on_settings_added( $name, $value ): void {
238 $enabled = is_array( $value ) && ! empty( $value['enabled'] );
239 $schedule = is_array( $value ) ? (string) ( $value['schedule'] ?? 'manual' ) : 'manual';
240 Preloader::apply_schedule( $enabled ? $schedule : 'manual' );
241 }
242
243 public function rest_start( \WP_REST_Request $request ) {
244 $opts = Settings_Manager::get( self::SLUG );
245 if ( empty( $opts['enabled'] ) ) {
246 return new \WP_Error(
247 'xspeed_preloader_disabled',
248 __( 'Enable the preloader before starting a crawl.', 'xspeed' ),
249 array( 'status' => 409 )
250 );
251 }
252 return rest_ensure_response( Preloader::start() );
253 }
254
255 public function rest_stop( \WP_REST_Request $request ) {
256 return rest_ensure_response( Preloader::stop() );
257 }
258
259 public function rest_status( \WP_REST_Request $request ) {
260 return rest_ensure_response( Preloader::status() );
261 }
262
263 public function cli_handler( array $args, array $assoc ): void {
264 $action = $args[0] ?? 'status';
265
266 switch ( $action ) {
267 case 'start':
268 $opts = Settings_Manager::get( self::SLUG );
269 if ( empty( $opts['enabled'] ) ) {
270 \WP_CLI::error( 'Preloader is disabled. Enable it via wp xspeed preloader set --enabled=1 first.' );
271 return;
272 }
273 $state = Preloader::start();
274 // Don't print a green Success over a crawl that queued
275 // nothing — that exit-0 was the whole complaint in #142.
276 $sitemap_error = (string) ( $state['sitemap_error'] ?? '' );
277 if ( 0 === (int) $state['total'] ) {
278 \WP_CLI::error(
279 '' !== $sitemap_error
280 ? sprintf( 'Queued 0 URLs. %s', $sitemap_error )
281 : 'Queued 0 URLs — nothing to warm. Check the sitemap URL and the cache exclusion rules.'
282 );
283 return;
284 }
285 if ( 'fallback' === ( $state['source'] ?? '' ) ) {
286 \WP_CLI::warning( $sitemap_error );
287 \WP_CLI::success(
288 sprintf(
289 'Queued %d URL%s from the site content instead of the sitemap.',
290 $state['total'],
291 1 === $state['total'] ? '' : 's'
292 )
293 );
294 return;
295 }
296 \WP_CLI::success( sprintf( 'Queued %d URL%s.', $state['total'], 1 === $state['total'] ? '' : 's' ) );
297 return;
298
299 case 'stop':
300 Preloader::stop();
301 \WP_CLI::success( 'Preloader stopped.' );
302 return;
303
304 case 'status':
305 $state = Preloader::status();
306 \WP_CLI::log( 'Running : ' . ( $state['running'] ? 'yes' : 'no' ) );
307 \WP_CLI::log( 'Processed : ' . $state['processed'] . ' / ' . $state['total'] );
308 if ( $state['last_url'] ) {
309 \WP_CLI::log( 'Last URL : ' . $state['last_url'] );
310 }
311 if ( ! empty( $state['errors'] ) ) {
312 \WP_CLI::log( 'Errors : ' . count( $state['errors'] ) );
313 foreach ( array_slice( $state['errors'], -5 ) as $e ) {
314 // Tolerate a bare string as well as the {url, error}
315 // shape. A string entry fataled this command outright
316 // ("Cannot access offset of type string on string"),
317 // which also took MCP's get_preloader_status down with
318 // it — an agent asking why a preload failed got a type
319 // error instead of the reason. The writer is fixed, but
320 // `status` is a diagnostic: it should survive whatever
321 // it is handed rather than die reporting on it. (QA F1)
322 if ( is_array( $e ) ) {
323 $url = isset( $e['url'] ) ? (string) $e['url'] : '';
324 $msg = isset( $e['error'] ) ? (string) $e['error'] : '';
325 // The sitemap message already names the URL, so
326 // prefixing it would print the URL twice on one line.
327 $line = ( '' !== $url && false === strpos( $msg, $url ) )
328 ? $url . '' . $msg
329 : $msg;
330 } else {
331 $line = (string) $e;
332 }
333 \WP_CLI::log( ' ' . $line );
334 }
335 }
336 return;
337
338 default:
339 \WP_CLI::error( "Unknown action: $action" );
340 }
341 }
342 }
343