PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.7
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.7
1.3.7 1.3.6 1.3.5 1.3.4 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 All 33 releases
← All changes | includes/modules/Cloudflare/CloudflareModule.php +380 -11 1.3.0 → 1.3.7 View file →
@@ -34,14 +34,52 @@
34 34 * warning when Cloudflare is silently failing. (#119)
35 35 */
36 36 private const HEALTH_OPTION = 'xspeed_cloudflare_health';
37 37
38 + /** Cron event that does the edge call for a batch of purged URLs. */
39 + private const PURGE_URLS_EVENT = 'xspeed_cloudflare_purge_urls';
40 +
41 + /** Cron event for the zone-wide fallback when a batch is too large. */
42 + private const PURGE_ALL_EVENT = 'xspeed_cloudflare_purge_edge_all';
43 +
44 + /**
45 + * Above this many URLs, purge the zone instead of naming every page.
46 + *
47 + * The batch travels as the cron event's ARGUMENT, and the cron table is
48 + * an autoloaded option, so an unbounded batch is an unbounded payload in
49 + * `alloptions` for as long as the event is pending. A bulk product
50 + * import, or an `xspeed_purge_product_urls` filter that expands to a few
51 + * hundred URLs, is enough. Past the threshold the zone purge is one call
52 + * with no payload, and it is what the site would have got from
53 + * `purge_all()` anyway.
54 + */
55 + private const MAX_DEFERRED_URLS = 100;
56 +
57 + /**
58 + * URLs purged this request, awaiting a batched call at shutdown.
59 + *
60 + * Keyed blog id => URL => true. By URL so the same page arriving twice —
61 + * a post and the archive that lists it can resolve to the same address —
62 + * is sent once. By BLOG because one module instance serves the whole
63 + * process: a `Cache::purge_url()` raised inside `switch_to_blog()` would
64 + * otherwise land in a batch sent against whatever blog happened to be
65 + * current at shutdown, merging several sites' URLs into one zone with one
66 + * site's token, and writing the health record and activity log to the
67 + * wrong site too. Nothing does that today — Pro's network purge goes
68 + * through `purge_all()` — but the re-entry guard in Cache anticipates a
69 + * network purge that loops blogs in one request.
70 + *
71 + * @var array<int,array<string,true>>
72 + */
73 + private array $pending_edge_urls = array();
74 +
38 75 public function ui_metadata(): array {
39 76 return array(
40 77 'label' => __( 'Cloudflare', 'xspeed' ),
41 78 'icon' => 'Cloud',
42 - 'description' => __( 'Connect a Cloudflare zone for automatic edge purging when xSpeed clears its cache, plus a dev-mode toggle.', 'xspeed' ),
79 + 'description' => __( 'Clear the Cloudflare cache whenever xSpeed clears its own cache.', 'xspeed' ),
43 80 'custom_panel' => 'CloudflarePanel',
81 + 'group' => 'network',
44 82 );
45 83 }
46 84
47 85 /**
@@ -61,10 +99,10 @@
61 99 return array(
62 100 'enabled' => array(
63 101 'type' => 'bool',
64 102 'default' => false,
65 - 'label' => __( 'Enable Cloudflare integration', 'xspeed' ),
66 - 'description' => __( 'Use the credentials below to verify your zone and run purges.', 'xspeed' ),
103 + 'label' => __( 'Connect Cloudflare', 'xspeed' ),
104 + 'description' => __( 'Lets xSpeed clear the Cloudflare cache for your domain, using the details below.', 'xspeed' ),
67 105 ),
68 106 'auth_method' => array(
69 107 'type' => 'enum',
70 108 'default' => 'token',
@@ -73,9 +111,9 @@
73 111 'token' => 'API Token',
74 112 'key' => 'Global API Key',
75 113 ),
76 114 'label' => __( 'Authentication', 'xspeed' ),
77 - 'description' => __( 'API Tokens (scoped, recommended) or the legacy Global API Key with your account email.', 'xspeed' ),
115 + 'description' => __( 'An API token is safer and recommended. The older Global API Key also needs your account email.', 'xspeed' ),
78 116 'dependsOn' => array( 'field' => 'enabled' ),
79 117 ),
80 118 'api_token' => array(
81 119 'type' => 'secret',
@@ -80,9 +118,9 @@
80 118 'api_token' => array(
81 119 'type' => 'secret',
82 120 'default' => '',
83 121 'label' => __( 'API Token', 'xspeed' ),
84 - 'description' => __( 'Create a token at dash.cloudflare.com → My Profile → API Tokens. Needs "Zone → Cache Purge" + "Zone Settings" permissions.', 'xspeed' ),
122 + 'description' => __( 'Create one at dash.cloudflare.com → My Profile → API Tokens. Give it the "Zone → Cache Purge" and "Zone Settings" permissions.', 'xspeed' ),
85 123 // Only the token auth branch (and only while CF is enabled, via
86 124 // the transitive gate on auth_method → enabled).
87 125 'dependsOn' => array( 'field' => 'auth_method', 'value' => 'token' ),
88 126 ),
@@ -88,10 +126,10 @@
88 126 ),
89 127 'email' => array(
90 128 'type' => 'string',
91 129 'default' => '',
92 - 'label' => __( 'Account Email', 'xspeed' ),
93 - 'description' => __( 'Only used when Authentication is set to Global API Key.', 'xspeed' ),
130 + 'label' => __( 'Account email', 'xspeed' ),
131 + 'description' => __( 'The email address of your Cloudflare account.', 'xspeed' ),
94 132 'dependsOn' => array( 'field' => 'auth_method', 'value' => 'key' ),
95 133 ),
96 134 'api_key' => array(
97 135 'type' => 'secret',
@@ -96,9 +134,9 @@
96 134 'api_key' => array(
97 135 'type' => 'secret',
98 136 'default' => '',
99 137 'label' => __( 'Global API Key', 'xspeed' ),
100 - 'description' => __( 'Found at dash.cloudflare.com → My Profile → API Tokens → Global API Key.', 'xspeed' ),
138 + 'description' => __( 'Find it at dash.cloudflare.com → My Profile → API Tokens → Global API Key.', 'xspeed' ),
101 139 'dependsOn' => array( 'field' => 'auth_method', 'value' => 'key' ),
102 140 ),
103 141 'zone_id' => array(
104 142 'type' => 'string',
@@ -103,16 +141,16 @@
103 141 'zone_id' => array(
104 142 'type' => 'string',
105 143 'default' => '',
106 144 'label' => __( 'Zone ID', 'xspeed' ),
107 - 'description' => __( 'The 32-character hex Zone ID from your domain overview page.', 'xspeed' ),
145 + 'description' => __( 'The 32-character Zone ID shown on your domain overview page in Cloudflare.', 'xspeed' ),
108 146 'dependsOn' => array( 'field' => 'enabled' ),
109 147 ),
110 148 'auto_purge_on_update' => array(
111 149 'type' => 'bool',
112 150 'default' => true,
113 - 'label' => __( 'Auto-purge Cloudflare on xSpeed purge', 'xspeed' ),
114 - 'description' => __( 'When xSpeed clears its own cache (post save, settings change, manual purge), trigger a Cloudflare purge too.', 'xspeed' ),
151 + 'label' => __( 'Clear Cloudflare with xSpeed', 'xspeed' ),
152 + 'description' => __( 'Clear the Cloudflare cache each time xSpeed clears its own, for example after you save a post.', 'xspeed' ),
115 153 'dependsOn' => array( 'field' => 'enabled' ),
116 154 ),
117 155 );
118 156 }
@@ -187,8 +225,25 @@
187 225 add_action( 'init', array( $this, 'boot_on_init' ) );
188 226 }
189 227
190 228 /**
229 + * Leave no queued edge calls behind.
230 + *
231 + * A batch scheduled seconds before the module was switched off would
232 + * otherwise fire against a zone the site no longer manages, and the
233 + * event would sit in the cron table with no listener after that.
234 + */
235 + public function deactivate(): void {
236 + // `wp_unschedule_hook()`, not `wp_clear_scheduled_hook()`. The latter
237 + // keys on `md5( serialize( $args ) )` and defaults `$args` to an
238 + // empty array, so it only ever clears the no-arguments key. Every
239 + // event this module schedules carries the URL batch as its argument,
240 + // so clear_scheduled_hook cleared nothing at all here.
241 + wp_unschedule_hook( self::PURGE_URLS_EVENT );
242 + wp_unschedule_hook( self::PURGE_ALL_EVENT );
243 + }
244 +
245 + /**
191 246 * The real boot body — see boot() for why it runs on `init`.
192 247 */
193 248 public function boot_on_init(): void {
194 249 $opts = $this->get_settings();
@@ -199,8 +254,11 @@
199 254 // xSpeed fires this action whenever it purges its own
200 255 // cache (see Cache::purge_all). Listening here keeps
201 256 // CF in sync without any new wiring elsewhere.
202 257 add_action( 'xspeed_after_purge_all', array( $this, 'on_xspeed_purge' ), 10, 0 );
258 + add_action( 'xspeed_after_purge_url', array( $this, 'on_xspeed_purge_url' ), 10, 1 );
259 + add_action( self::PURGE_URLS_EVENT, array( $this, 'purge_edge_urls' ), 10, 1 );
260 + add_action( self::PURGE_ALL_EVENT, array( $this, 'purge_edge_all' ), 10, 0 );
203 261 }
204 262 }
205 263
206 264 public function on_xspeed_purge(): void {
@@ -222,8 +280,319 @@
222 280 if ( true !== $this->can_purge_edge() ) {
223 281 return;
224 282 }
225 283 $this->purge_edge( 'auto-purge' );
284 + }
285 +
286 + /**
287 + * Mirror a single-URL purge at the edge.
288 + *
289 + * NOT about post edits — `on_save_post()` calls `purge_all()`, so those
290 + * have always reached Cloudflare through the full-purge listener above.
291 + * What reaches `purge_url()` is the narrower set: the two admin purge
292 + * buttons, an approved comment, a user change, a WooCommerce product or
293 + * stock change, `--url` on the CLI and REST, and MCP. Every one of those
294 + * cleared xSpeed's copy and left Cloudflare's, so the page stayed stale
295 + * at the edge until its lifetime ran out or somebody pressed Purge All —
296 + * which is a whole-zone purge to fix one page.
297 + *
298 + * Single-file purge is also the cheap call, which is the opposite of how
299 + * it looks. Cloudflare's tightest documented purge limit is the one on
300 + * purge-everything, hostname, tag and prefix; file purges are metered
301 + * separately and far more generously. The `purge_all` listener above is
302 + * the one near a limit, not this.
303 + *
304 + * @param array<string,mixed> $context The event payload. See the
305 + * `xspeed_after_purge_url` docblock.
306 + */
307 + public function on_xspeed_purge_url( $context ): void {
308 + if ( ! is_array( $context ) || 'urls' !== ( $context['scope'] ?? '' ) ) {
309 + return;
310 + }
311 + $urls = array_filter( array_map( 'strval', (array) ( $context['urls'] ?? array() ) ) );
312 + if ( array() === $urls ) {
313 + return;
314 + }
315 + // Same guard as the full-purge listener: `wp xspeed purge` reports
316 + // the edge as its own line item, and purging here as well would make
317 + // the outcome nobody reported the one that lands in the health record.
318 + if ( class_exists( '\\XSpeed\\Purge_Runner' ) && \XSpeed\Purge_Runner::covers( 'cloudflare' ) ) {
319 + return;
320 + }
321 + if ( true !== $this->can_purge_edge() ) {
322 + return;
323 + }
324 +
325 + // Collected and sent once, not one API call per URL. `Purge_Ui`'s
326 + // post purge and the WooCommerce product path both fire a handful of
327 + // these in a loop, and a round trip each would be a wait each.
328 + if ( array() === $this->pending_edge_urls ) {
329 + add_action( 'shutdown', array( $this, 'flush_edge_url_purges' ), 20 );
330 + }
331 + $blog = function_exists( 'get_current_blog_id' ) ? (int) get_current_blog_id() : 0;
332 + foreach ( $urls as $url ) {
333 + $this->pending_edge_urls[ $blog ][ $url ] = true;
334 + }
335 + }
336 +
337 + /**
338 + * Hand whatever `on_xspeed_purge_url()` collected to cron.
339 + *
340 + * Three of the callers are ordinary visitor traffic — an approved
341 + * comment, a user registration, a WooCommerce stock change during
342 + * checkout — and none of them made an outbound request before this
343 + * listener existed. Doing the HTTPS inline would put a blocking round
344 + * trip to Cloudflare on the end of a shopper's checkout, once per
345 + * request, with the timeout as the worst case. So the batch is scheduled
346 + * and the request ends.
347 + *
348 + * Inline when there is nothing to defer to: cron cannot defer to itself,
349 + * and a CLI run exits before a spawned cron request would be served.
350 + * Both are contexts where a blocking call is the right answer anyway.
351 + *
352 + * Deliberately not what WP Rocket does — its Cloudflare add-on calls
353 + * `purge_files()` straight from `after_rocket_clean_post`, so a visitor
354 + * leaving a comment waits on Cloudflare. LiteSpeed sidesteps it by never
355 + * purging Cloudflare per URL at all. Deferring is the same thing
356 + * `Preloader` and `Cookie_Inspector` already do here for the same
357 + * reason: outbound HTTP belongs in a later request, not on the one that
358 + * happened to trigger it.
359 + *
360 + * Three ways a batch can still be lost, all silent because the health
361 + * record is only written inside the flush: a PHP fatal (WordPress's own
362 + * fatal handler is registered before `shutdown_action_hook` and ends the
363 + * process first), another plugin calling `exit` from a `shutdown`
364 + * callback at a priority below 20, and a `purge_url()` raised during
365 + * `shutdown` ABOVE priority 20, which re-arms a hook that has already
366 + * dispatched. Rare, but this is the note that saves the next person
367 + * debugging "the edge kept a stale page" from rediscovering them.
368 + *
369 + * Public because it is a `shutdown` callback; not part of the module's
370 + * contract.
371 + */
372 + public function flush_edge_url_purges(): void {
373 + $batches = $this->pending_edge_urls;
374 + $this->pending_edge_urls = array();
375 + $current = function_exists( 'get_current_blog_id' ) ? (int) get_current_blog_id() : 0;
376 +
377 + foreach ( $batches as $blog => $keyed ) {
378 + $urls = array_keys( $keyed );
379 + if ( array() === $urls ) {
380 + continue;
381 + }
382 + // Each batch is scheduled and sent as the site that raised it,
383 + // because the cron table, the settings, the health record and the
384 + // activity log are all per-site.
385 + $switched = (int) $blog !== $current && function_exists( 'switch_to_blog' );
386 + if ( $switched ) {
387 + switch_to_blog( (int) $blog );
388 + }
389 + try {
390 + $this->dispatch_edge_url_batch( $urls );
391 + } finally {
392 + // A throwing adapter must not leave the rest of shutdown
393 + // running as the wrong site.
394 + if ( $switched ) {
395 + restore_current_blog();
396 + }
397 + }
398 + }
399 + }
400 +
401 + /** Schedule one site's batch, or send it now where there is nothing to defer to. */
402 + private function dispatch_edge_url_batch( array $urls ): void {
403 + // Too many to name. Purge the zone instead of carrying every URL in
404 + // an autoloaded option, and say so, because a zone purge costs more
405 + // origin traffic than the page purges it replaces and nobody should
406 + // have to infer that it happened.
407 + if ( count( $urls ) > self::max_deferred_urls() ) {
408 + $this->dispatch_edge_purge_all( count( $urls ) );
409 + return;
410 + }
411 +
412 + if ( ! self::must_purge_inline() && function_exists( 'wp_schedule_single_event' ) ) {
413 + // `$wp_error = true`, because the bare form returns false for two
414 + // opposite situations and only one of them is a failure.
415 + //
416 + // Scheduling at `time()` puts the timestamp in the past by the
417 + // time core compares it, which sets core's `$min_timestamp` to 0
418 + // (wp-includes/cron.php) — so ANY identical event anywhere in the
419 + // cron table, however old, counts as a duplicate and the call
420 + // returns false. Two comments on the same post produce
421 + // byte-identical args, so the second one would have taken the
422 + // inline fallback: a blocking call to Cloudflare on a visitor's
423 + // request, which is the exact thing this deferral exists to
424 + // avoid, while the already-queued event fired anyway and sent
425 + // the batch twice.
426 + //
427 + // A duplicate means the work is already queued. That is success.
428 + $scheduled = wp_schedule_single_event( time(), self::PURGE_URLS_EVENT, array( $urls ), true );
429 + if ( true === $scheduled ) {
430 + return;
431 + }
432 + if ( is_wp_error( $scheduled ) && 'duplicate_event' === $scheduled->get_error_code() ) {
433 + return;
434 + }
435 + // Anything else — a filter vetoing the event, a broken cron
436 + // table — is a real refusal, and dropping the purge silently
437 + // would leave the edge stale with nothing to say so.
438 + }
439 +
440 + $this->purge_edge_urls( $urls );
441 + }
442 +
443 + /** Is this a context with no later request to defer the edge call to? */
444 + private static function must_purge_inline(): bool {
445 + if ( defined( 'WP_CLI' ) && WP_CLI ) {
446 + return true;
447 + }
448 + return function_exists( 'wp_doing_cron' ) && wp_doing_cron();
449 + }
450 +
451 + /**
452 + * How many URLs may ride along in a deferred batch.
453 + *
454 + * Filterable because the right answer depends on how long a site's cron
455 + * backlog sits: the cost is the payload's time in `alloptions`, not the
456 + * URL count itself.
457 + */
458 + private static function max_deferred_urls(): int {
459 + if ( ! function_exists( 'apply_filters' ) ) {
460 + return self::MAX_DEFERRED_URLS;
461 + }
462 +
463 + /**
464 + * Filter the batch size above which a zone purge replaces named URLs.
465 + *
466 + * @param int $max URLs per deferred batch.
467 + */
468 + $max = (int) apply_filters( 'xspeed_cloudflare_max_deferred_purge_urls', self::MAX_DEFERRED_URLS );
469 +
470 + // A filter of zero would send every single-page purge to the zone.
471 + return $max > 0 ? $max : self::MAX_DEFERRED_URLS;
472 + }
473 +
474 + /** Queue the zone-wide fallback, or run it now where cron cannot. */
475 + private function dispatch_edge_purge_all( int $url_count ): void {
476 + if ( class_exists( '\\XSpeed\\Activity_Log' ) ) {
477 + \XSpeed\Activity_Log::record(
478 + 'cache_purged',
479 + sprintf(
480 + /* translators: %d: number of URLs that changed at once. */
481 + __( 'Purging the whole Cloudflare zone: %d URLs changed at once, too many to purge individually', 'xspeed' ),
482 + $url_count
483 + )
484 + );
485 + }
486 +
487 + if ( ! self::must_purge_inline() && function_exists( 'wp_schedule_single_event' ) ) {
488 + // No arguments, so every oversized batch in a request collapses
489 + // onto one event. `duplicate_event` is the wanted outcome here,
490 + // not a failure.
491 + $scheduled = wp_schedule_single_event( time(), self::PURGE_ALL_EVENT, array(), true );
492 + if ( true === $scheduled ) {
493 + return;
494 + }
495 + if ( is_wp_error( $scheduled ) && 'duplicate_event' === $scheduled->get_error_code() ) {
496 + return;
497 + }
498 + }
499 +
500 + $this->purge_edge_all();
501 + }
502 +
503 + /**
504 + * Purge the whole zone, as the fallback for an oversized batch.
505 + *
506 + * Public because it is the `PURGE_ALL_EVENT` cron callback. Re-checks the
507 + * connection for the same reason the URL batch does: this runs in a later
508 + * request than the one that queued it.
509 + */
510 + public function purge_edge_all(): void {
511 + if ( true !== $this->can_purge_edge() ) {
512 + return;
513 + }
514 + $this->purge_edge( 'auto-purge' );
515 + }
516 +
517 + /**
518 + * Purge a batch of URLs at the edge and record the outcome.
519 + *
520 + * Public because it is the `PURGE_URLS_EVENT` cron callback.
521 + *
522 + * @param string[] $urls
523 + */
524 + public function purge_edge_urls( $urls ): void {
525 + $urls = array_values( array_filter( array_map( 'strval', (array) $urls ) ) );
526 + if ( array() === $urls ) {
527 + return;
528 + }
529 + // Re-checked here rather than trusted from collect time: a scheduled
530 + // batch runs in a later request, and the credentials or the switch
531 + // may have changed between the two.
532 + if ( true !== $this->can_purge_edge() ) {
533 + // Said out loud, because otherwise "the credentials were removed
534 + // between queueing and running" and "the purge succeeded" look
535 + // identical from the panel, and the pages stay stale at the edge
536 + // either way.
537 + if ( class_exists( '\\XSpeed\\Activity_Log' ) ) {
538 + \XSpeed\Activity_Log::record(
539 + 'cache_purge_skipped',
540 + sprintf(
541 + /* translators: %d: number of URLs. */
542 + _n(
543 + 'Skipped a queued Cloudflare purge of %d URL: the connection is no longer available',
544 + 'Skipped a queued Cloudflare purge of %d URLs: the connection is no longer available',
545 + count( $urls ),
546 + 'xspeed'
547 + ),
548 + count( $urls )
549 + ),
550 + \XSpeed\Activity_Log::WARN
551 + );
552 + }
553 + return;
554 + }
555 +
556 + $result = Cloudflare::purge_urls( $this->get_settings(), $urls );
557 + $ok = ! empty( $result['ok'] );
558 + $reason = $ok ? '' : $this->message_of( $result );
559 +
560 + // Recorded for the same reason the full purge is: a token that passes
561 + // verify can still lack "Zone → Cache Purge", and a silent auth
562 + // failure here means stale pages at the edge with nothing to say so.
563 + $this->record_health( $ok, 'purge', $reason );
564 +
565 + if ( ! class_exists( '\\XSpeed\\Activity_Log' ) ) {
566 + return;
567 + }
568 + if ( $ok ) {
569 + \XSpeed\Activity_Log::record(
570 + 'cache_purged',
571 + sprintf(
572 + /* translators: %d: number of URLs purged. */
573 + _n(
574 + 'Purged %d URL from the Cloudflare edge cache',
575 + 'Purged %d URLs from the Cloudflare edge cache',
576 + count( $urls ),
577 + 'xspeed'
578 + ),
579 + count( $urls )
580 + ),
581 + \XSpeed\Activity_Log::INFO
582 + );
583 + return;
584 + }
585 + \XSpeed\Activity_Log::record(
586 + 'cloudflare_purge_failed',
587 + sprintf(
588 + /* translators: 1: number of URLs, 2: failure reason. */
589 + __( 'Cloudflare URL purge failed (%1$d URL(s)): %2$s', 'xspeed' ),
590 + count( $urls ),
591 + $reason ? $reason : __( 'unknown error', 'xspeed' )
592 + ),
593 + \XSpeed\Activity_Log::WARN
594 + );
226 595 }
227 596
228 597 /**
229 598 * Whether this site can purge its Cloudflare zone right now.