Changeset 3785142
- Timestamp:
- 11/05/2026 03:17:04 AM (3 weeks ago)
- Location:
- nahnu-cache-connector-bunny-net
- Files:
-
- 30 added
- 12 edited
-
tags/1.0.14 (added)
-
tags/1.0.14/assets (added)
-
tags/1.0.14/assets/admin.css (added)
-
tags/1.0.14/assets/admin.js (added)
-
tags/1.0.14/assets/logo.jpg (added)
-
tags/1.0.14/assets/smartphonefield-icon.png (added)
-
tags/1.0.14/assets/wp-media-cloud.png (added)
-
tags/1.0.14/assets/wplinkcanvas-icon.png (added)
-
tags/1.0.14/assets/wpsmartconsent-icon.png (added)
-
tags/1.0.14/assets/wpsuperdocs-icon.png (added)
-
tags/1.0.14/includes (added)
-
tags/1.0.14/includes/class-wpbc-admin.php (added)
-
tags/1.0.14/includes/class-wpbc-api.php (added)
-
tags/1.0.14/includes/class-wpbc-cli.php (added)
-
tags/1.0.14/includes/class-wpbc-edge-rules.php (added)
-
tags/1.0.14/includes/class-wpbc-hooks.php (added)
-
tags/1.0.14/includes/class-wpbc-integrations.php (added)
-
tags/1.0.14/includes/class-wpbc-mainwp.php (added)
-
tags/1.0.14/includes/class-wpbc-managers.php (added)
-
tags/1.0.14/includes/class-wpbc-perma-cache.php (added)
-
tags/1.0.14/includes/class-wpbc-public-api.php (added)
-
tags/1.0.14/includes/class-wpbc-purge.php (added)
-
tags/1.0.14/includes/class-wpbc-rest.php (added)
-
tags/1.0.14/includes/class-wpbc-stats.php (added)
-
tags/1.0.14/includes/class-wpbc-throttle.php (added)
-
tags/1.0.14/includes/class-wpbc-warmer.php (added)
-
tags/1.0.14/languages (added)
-
tags/1.0.14/readme.txt (added)
-
tags/1.0.14/uninstall.php (added)
-
tags/1.0.14/wp-bunny-connector.php (added)
-
trunk/assets/admin.js (modified) (2 diffs)
-
trunk/includes/class-wpbc-admin.php (modified) (7 diffs)
-
trunk/includes/class-wpbc-api.php (modified) (4 diffs)
-
trunk/includes/class-wpbc-edge-rules.php (modified) (14 diffs)
-
trunk/includes/class-wpbc-hooks.php (modified) (1 diff)
-
trunk/includes/class-wpbc-public-api.php (modified) (4 diffs)
-
trunk/includes/class-wpbc-purge.php (modified) (3 diffs)
-
trunk/includes/class-wpbc-throttle.php (modified) (6 diffs)
-
trunk/includes/class-wpbc-warmer.php (modified) (6 diffs)
-
trunk/readme.txt (modified) (6 diffs)
-
trunk/uninstall.php (modified) (2 diffs)
-
trunk/wp-bunny-connector.php (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
-
nahnu-cache-connector-bunny-net/trunk/assets/admin.js
r3751963 r3785142 309 309 // Zone now selected — update badge immediately (still needs Save to persist) 310 310 updateBadges({ zone: true }); 311 buildZone2(zone2Zones); 311 312 // Close 312 313 closeZonePicker(); … … 362 363 function populateZones(zones, savedId) { 363 364 buildZoneList(zones, savedId); 364 } 365 buildZone2(zones); 366 } 367 368 /* ── Second pull zone (www and non-www on separate zones) ─────────────── */ 369 let zone2Zones = []; 370 function zoneHasHost(z, host) { 371 return !!host && (z?.hostnames || []).some(h => String(h).toLowerCase() === host); 372 } 373 function buildZone2(zones) { 374 zone2Zones = Array.isArray(zones) ? zones : []; 375 const sel = document.getElementById('wpbc-pull-zone-2-select'); 376 if (!sel) { zone2Hint(); return; } 377 const current = sel.value || String(cfg.savedZoneId2 || ''); 378 const primary = document.getElementById('wpbc-pull-zone-select')?.value || cfg.savedZoneId; 379 const none = sel.options[0] ? sel.options[0].textContent : 'None'; 380 sel.innerHTML = ''; 381 sel.appendChild(new Option(none, '')); 382 zone2Zones.forEach(z => { 383 if (String(z.id) === String(primary)) return; 384 const label = z.name + (z.hostnames?.length ? ' (' + z.hostnames.join(', ') + ')' : ''); 385 sel.appendChild(new Option(label, z.id, false, String(z.id) === String(current))); 386 }); 387 zone2Hint(); 388 } 389 function zone2Hint() { 390 const hint = document.getElementById('wpbc-zone2-hint'); 391 if (!hint || !zone2Zones.length) return; 392 const hosts = (cfg.siteHosts || []).map(h => String(h).toLowerCase()); 393 const host = hosts[0], other = hosts[1]; 394 const sel = document.getElementById('wpbc-pull-zone-2-select'); 395 const primary = document.getElementById('wpbc-pull-zone-select')?.value || cfg.savedZoneId; 396 const pz = zone2Zones.find(z => String(z.id) === String(primary)); 397 const chosen = sel ? sel.value : String(cfg.savedZoneId2 || ''); 398 const match = zone2Zones.find(z => String(z.id) !== String(primary) && zoneHasHost(z, other)); 399 let msg = ''; 400 if (pz && zoneHasHost(pz, host) && zoneHasHost(pz, other)) { 401 msg = 'Your main pull zone already serves ' + host + ' and ' + other + '. No second zone is needed.'; 402 if (chosen) msg += ' You can set this to None.'; 403 } else if (chosen) { 404 const cz = zone2Zones.find(z => String(z.id) === String(chosen)); 405 msg = cz && !zoneHasHost(cz, other) && !zoneHasHost(cz, host) 406 ? 'Check this choice: ' + cz.name + ' has neither ' + host + ' nor ' + other + ' as a hostname.' 407 : ''; 408 } else if (match) { 409 msg = match.name + ' serves ' + other + '. Pick it here and save, so both hostnames get the edge rules.'; 410 } else if (pz && !zoneHasHost(pz, other)) { 411 msg = 'No pull zone lists ' + other + '. If ' + other + ' redirects to ' + host + ' before it reaches Bunny, no second zone is needed.'; 412 } 413 hint.textContent = msg; 414 } 415 function syncZone2Name() { 416 const sel = document.getElementById('wpbc-pull-zone-2-select'); 417 const name = document.getElementById('wpbc-pull-zone-name-2'); 418 if (!sel || !name) return; 419 const z = zone2Zones.find(x => String(x.id) === String(sel.value)); 420 name.value = z ? z.name : ''; 421 } 422 document.getElementById('wpbc-pull-zone-2-select')?.addEventListener('change', () => { syncZone2Name(); zone2Hint(); }); 365 423 366 424 function fetchAndPopulateZones(btn) { -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-admin.php
r3782406 r3785142 244 244 } 245 245 246 // Second pull zone (www / non-www on separate zones). Kept as is when 247 // the field is not in the form; never the same as the main zone. 248 if ( WPBC_API::secondary_zone_is_constant() || ! array_key_exists( 'pull_zone_id_2', $raw ) ) { 249 $pull_zone_id_2 = (string) ( $existing['pull_zone_id_2'] ?? '' ); 250 $pull_zone_name_2 = (string) ( $existing['pull_zone_name_2'] ?? '' ); 251 } else { 252 $pull_zone_id_2 = (string) preg_replace( '/\D/', '', (string) $raw['pull_zone_id_2'] ); 253 $pull_zone_name_2 = sanitize_text_field( $raw['pull_zone_name_2'] ?? '' ); 254 } 255 $main_zone = WPBC_API::pull_zone_is_constant() ? WPBC_API::primary_zone_id() : (string) preg_replace( '/\D/', '', (string) $pull_zone_id ); 256 if ( $pull_zone_id_2 === '' || $pull_zone_id_2 === $main_zone ) { 257 $pull_zone_id_2 = ''; 258 $pull_zone_name_2 = ''; 259 } 260 if ( $pull_zone_id_2 !== (string) ( $existing['pull_zone_id_2'] ?? '' ) ) { 261 // New second zone: it needs the rules, so flag a redeploy. 262 update_option( 'wpbc_rules_stale', 1, false ); 263 } 264 246 265 // DNS zone ID: constant-locked or form value 247 266 $dns_zone_id = WPBC_API::dns_zone_is_constant() … … 273 292 'pull_zone_id' => $pull_zone_id, 274 293 'pull_zone_name' => $pull_zone_name, 294 'pull_zone_id_2' => $pull_zone_id_2, 295 'pull_zone_name_2' => $pull_zone_name_2, 275 296 'dns_zone_id' => $dns_zone_id, 276 297 'shield_zone_id' => sanitize_text_field( $raw['shield_zone_id'] ?? '' ), … … 406 427 // Pre-load data so JS can auto-populate on page load 407 428 'savedZoneId' => $opts['pull_zone_id'] ?? '', 429 'savedZoneId2' => WPBC_API::secondary_zone_id(), 430 'siteHosts' => WPBC_API::site_hosts(), 408 431 'savedDnsZoneId' => WPBC_API::get_dns_zone_id(), 409 432 'shieldZoneId' => $opts['shield_zone_id'] ?? '', … … 456 479 /** API client built from the form's current key and pull zone, falling back to saved values. */ 457 480 private function api_from_request(): WPBC_API { 458 $zone = isset( $_POST['pull_zone_id']) ? preg_replace( '/\D/', '', (string) wp_unslash( $_POST['pull_zone_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing481 $zone = ( ! WPBC_API::pull_zone_is_constant() && isset( $_POST['pull_zone_id'] ) ) ? preg_replace( '/\D/', '', (string) wp_unslash( $_POST['pull_zone_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing 459 482 return new WPBC_API( $this->posted_api_key(), (string) $zone ); 460 483 } … … 1162 1185 </div> 1163 1186 1187 <?php 1188 $zone2_via_constant = WPBC_API::secondary_zone_is_constant(); 1189 $zone2_id = WPBC_API::secondary_zone_id(); 1190 [ $site_host, $site_host_alt ] = WPBC_API::site_hosts(); 1191 ?> 1192 <div class="wpbc-field-row"> 1193 <div> 1194 <div class="wpbc-field-label"><?php esc_html_e( 'Second pull zone (optional)', 'nahnu-cache-connector-bunny-net' ); ?></div> 1195 <div class="wpbc-field-hint"> 1196 <?php 1197 printf( 1198 /* translators: 1: site hostname, 2: the www / non-www hostname */ 1199 esc_html__( 'Only if %1$s and %2$s are on separate pull zones. That zone then gets the same edge rules and every purge.', 'nahnu-cache-connector-bunny-net' ), 1200 '<code>' . esc_html( $site_host ) . '</code>', 1201 '<code>' . esc_html( $site_host_alt ) . '</code>' 1202 ); 1203 ?> 1204 </div> 1205 </div> 1206 <div class="wpbc-field-ctrl"> 1207 <?php if ( $zone2_via_constant ) : ?> 1208 <div class="wpbc-locked-field"> 1209 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> 1210 <span><?php esc_html_e( 'Locked, set via WPBC_PULL_ZONE_ID_2 in wp-config.php', 'nahnu-cache-connector-bunny-net' ); ?></span> 1211 </div> 1212 <?php else : ?> 1213 <input type="hidden" name="<?php echo esc_attr( self::OPT ); ?>[pull_zone_name_2]" id="wpbc-pull-zone-name-2" value="<?php echo esc_attr( $opts['pull_zone_name_2'] ?? '' ); ?>"> 1214 <select name="<?php echo esc_attr( self::OPT ); ?>[pull_zone_id_2]" id="wpbc-pull-zone-2-select" style="width:100%"> 1215 <option value=""><?php esc_html_e( 'None (one pull zone serves both)', 'nahnu-cache-connector-bunny-net' ); ?></option> 1216 <?php if ( $zone2_id !== '' ) : ?> 1217 <option value="<?php echo esc_attr( $zone2_id ); ?>" selected><?php echo esc_html( ( $opts['pull_zone_name_2'] ?? '' ) !== '' ? $opts['pull_zone_name_2'] : 'Zone #' . $zone2_id ); ?></option> 1218 <?php endif; ?> 1219 </select> 1220 <?php endif; ?> 1221 <div class="wpbc-field-hint" id="wpbc-zone2-hint" aria-live="polite"></div> 1222 </div> 1223 </div> 1224 1164 1225 <!-- wp-config.php constants notice --> 1165 1226 <div class="wpbc-wpconfig-notice"> … … 1172 1233 "define( 'WPBC_API_KEY', 'your-bunny-api-key-here' );", 1173 1234 "define( 'WPBC_PULL_ZONE_ID', '123456' );", 1235 "define( 'WPBC_PULL_ZONE_ID_2', '123457' ); // optional: www / non-www zone", 1174 1236 "define( 'WPBC_DNS_ZONE_ID', '789012' );", 1175 1237 "define( 'WPBC_PERMA_ZONE_NAME', 'your-storage-zone' );", … … 1293 1355 <div class="wpbc-card-title"><?php esc_html_e( 'Purge triggers', 'nahnu-cache-connector-bunny-net' ); ?></div> 1294 1356 <?php $this->toggle( 'trigger_post_save', $opts, __( 'Post publish / update', 'nahnu-cache-connector-bunny-net' ), __( 'Purge on post/page save, classic editor and REST-based editors (Gutenberg, Bricks Builder)', 'nahnu-cache-connector-bunny-net' ) ); ?> 1295 <?php $this->toggle( 'trigger_plugin_update', $opts, __( 'Plugin / theme updates', 'nahnu-cache-connector-bunny-net' ), __( 'Purge on plugin/theme/core updates, theme switch,plugin activate/deactivate', 'nahnu-cache-connector-bunny-net' ) ); ?>1357 <?php $this->toggle( 'trigger_plugin_update', $opts, __( 'Plugin / theme updates', 'nahnu-cache-connector-bunny-net' ), __( 'Purge once plugin, theme and core updates have finished, and on theme switch or plugin activate/deactivate', 'nahnu-cache-connector-bunny-net' ) ); ?> 1296 1358 <?php $this->toggle( 'enable_admin_bar', $opts, __( 'Admin bar purge button', 'nahnu-cache-connector-bunny-net' ), __( 'Adds a Purge Bunny button to the WordPress admin bar', 'nahnu-cache-connector-bunny-net' ) ); ?> 1297 1359 <?php $this->toggle( 'enable_logging', $opts, __( 'Enable debug logging', 'nahnu-cache-connector-bunny-net' ), __( 'Log API errors to PHP error_log (requires WP_DEBUG_LOG). Successful purges are not logged.', 'nahnu-cache-connector-bunny-net' ) ); ?> -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-api.php
r3765468 r3785142 17 17 * (settings screen: a key typed but not saved yet). 18 18 * @param string|null $zone_override Same for the Pull Zone ID. 19 * Constants defined in wp-config.php always win over both.19 * WPBC_API_KEY always wins. WPBC_PULL_ZONE_ID wins over the saved zone. 20 20 */ 21 21 public function __construct( ?string $api_key_override = null, ?string $zone_override = null ) { … … 25 25 ? (string) WPBC_API_KEY 26 26 : ( ( $api_key_override !== null && $api_key_override !== '' ) ? $api_key_override : (string) ( $opts['api_key'] ?? '' ) ); 27 $this->zone_id = defined( 'WPBC_PULL_ZONE_ID' ) 28 ? (string) WPBC_PULL_ZONE_ID 29 : ( ( $zone_override !== null && $zone_override !== '' ) ? $zone_override : (string) ( $opts['pull_zone_id'] ?? '' ) ); 27 // An explicit zone (the second pull zone) wins over the constant, so 28 // the second zone's rules are never sent to the first zone. 29 $this->zone_id = ( $zone_override !== null && $zone_override !== '' ) 30 ? $zone_override 31 : ( defined( 'WPBC_PULL_ZONE_ID' ) ? (string) WPBC_PULL_ZONE_ID : (string) ( $opts['pull_zone_id'] ?? '' ) ); 30 32 $this->logging = ! empty( $opts['enable_logging'] ); 31 33 } … … 77 79 } 78 80 $this->log( 'Full purge OK.' ); 79 return true; 81 82 // The second pull zone (www / non-www) is purged with the main one. 83 $z2 = self::secondary_zone_id(); 84 if ( $z2 !== '' && $z2 !== $this->zone_id ) { 85 $r2 = $this->request( 'POST', self::ZONE_BASE . '/' . $z2 . '/purgeCache' ); 86 if ( is_wp_error( $r2 ) ) { 87 $this->log( 'purge_all (second pull zone) failed: ' . $r2->get_error_message() ); 88 return $r2; 89 } 90 $this->log( 'Full purge OK (second pull zone).' ); 91 } 92 return true; 93 } 94 95 /** Pull zone from wp-config (WPBC_PULL_ZONE_ID) or Settings. */ 96 public static function primary_zone_id(): string { 97 if ( defined( 'WPBC_PULL_ZONE_ID' ) ) { 98 return (string) preg_replace( '/\D/', '', (string) WPBC_PULL_ZONE_ID ); 99 } 100 $opts = get_option( 'wpbc_settings', [] ); 101 return (string) preg_replace( '/\D/', '', (string) ( $opts['pull_zone_id'] ?? '' ) ); 102 } 103 104 /** 105 * Optional second pull zone, for sites whose www and non-www hostnames are 106 * on separate Bunny pull zones. It gets the same edge rules and purges. 107 * Set in Settings or with WPBC_PULL_ZONE_ID_2. Empty when not used. 108 */ 109 public static function secondary_zone_id(): string { 110 if ( defined( 'WPBC_PULL_ZONE_ID_2' ) ) { 111 $z2 = (string) WPBC_PULL_ZONE_ID_2; 112 } else { 113 $opts = get_option( 'wpbc_settings', [] ); 114 $z2 = (string) ( $opts['pull_zone_id_2'] ?? '' ); 115 } 116 $z2 = (string) preg_replace( '/\D/', '', $z2 ); 117 return ( $z2 === '' || $z2 === self::primary_zone_id() ) ? '' : $z2; 118 } 119 120 public static function secondary_zone_is_constant(): bool { 121 return defined( 'WPBC_PULL_ZONE_ID_2' ); 122 } 123 124 /** 125 * The site's hostname and its www / non-www counterpart: 126 * example.com gives [example.com, www.example.com], 127 * www.example.com gives [www.example.com, example.com]. 128 * 129 * @return array{0:string,1:string} 130 */ 131 public static function site_hosts(): array { 132 $host = strtolower( (string) ( wp_parse_url( home_url(), PHP_URL_HOST ) ?? '' ) ); 133 if ( $host === '' ) { 134 return [ '', '' ]; 135 } 136 $other = str_starts_with( $host, 'www.' ) ? substr( $host, 4 ) : 'www.' . $host; 137 return [ $host, $other ]; 138 } 139 140 /** 141 * The URL with the site's hostname swapped for its www / non-www 142 * counterpart. Empty when no second pull zone is set or the URL is 143 * on another host. 144 */ 145 public static function alternate_host_url( string $url ): string { 146 if ( self::secondary_zone_id() === '' ) { 147 return ''; 148 } 149 [ $host, $other ] = self::site_hosts(); 150 if ( $host === '' ) { 151 return ''; 152 } 153 $u_host = strtolower( (string) ( wp_parse_url( $url, PHP_URL_HOST ) ?? '' ) ); 154 if ( $u_host === $host ) { 155 $swap = $other; 156 } elseif ( $u_host === $other ) { 157 $swap = $host; 158 } else { 159 return ''; 160 } 161 $pos = stripos( $url, '//' . $u_host ); 162 return $pos === false ? '' : substr_replace( $url, '//' . $swap, $pos, strlen( $u_host ) + 2 ); 80 163 } 81 164 … … 93 176 return new WP_Error( 'empty_url', __( 'URL cannot be empty.', 'nahnu-cache-connector-bunny-net' ) ); 94 177 } 178 $result = $this->purge_one_url( $url ); 179 if ( is_wp_error( $result ) ) { 180 return $result; 181 } 182 // With a second pull zone, the same page under the other hostname 183 // (www / non-www) is cached there, so purge that URL too. 184 $alt = self::alternate_host_url( $url ); 185 if ( $alt !== '' ) { 186 $this->purge_one_url( $alt ); 187 } 188 return true; 189 } 190 191 private function purge_one_url( string $url ): bool|WP_Error { 95 192 // Endpoint: POST /purge?url=<encoded-url>&async=false 96 193 // Note: url is a query parameter, NOT a request body, different from purge_all. -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-edge-rules.php
r3782406 r3785142 117 117 private string $host; 118 118 private string $host_www; 119 120 /** True for the second pull zone (www / apex on its own zone). */ 121 private bool $secondary = false; 122 123 /** Per-zone option names: the second zone keeps its own rule tracking. */ 124 private string $guids_opt = self::GUIDS_OPT; 125 private string $order_opt = self::ORDER_OPT; 119 126 private array|null $enabled_rules_cache = null; // loaded once per deploy 120 127 121 public function __construct() { 122 $this->api = new WPBC_API(); 123 $parsed = wp_parse_url( home_url() ); 124 $this->host = $parsed['host'] ?? ''; 125 $this->host_www = str_starts_with( $this->host, 'www.' ) 126 ? $this->host 127 : 'www.' . $this->host; 128 /** 129 * @param string|null $zone_id A pull zone other than the one in Settings 130 * (the second zone). Null for the main zone. 131 */ 132 public function __construct( ?string $zone_id = null ) { 133 $this->secondary = $zone_id !== null && $zone_id !== ''; 134 $this->api = new WPBC_API( null, $this->secondary ? $zone_id : null ); 135 if ( $this->secondary ) { 136 $this->guids_opt = self::GUIDS_OPT . '_z2'; 137 $this->order_opt = self::ORDER_OPT . '_z2'; 138 } 139 // The site's own hostname and its www / apex counterpart. Every rule 140 // matches both. Before 1.0.14 a site whose address starts with www. 141 // got www.example.com twice, so example.com was never covered. 142 [ $this->host, $this->host_www ] = WPBC_API::site_hosts(); 128 143 } 129 144 … … 382 397 } 383 398 399 /** 400 * Deploy to the main pull zone and, when one is set, the second pull zone 401 * (www and apex on separate zones). Counted as a success only when every 402 * zone succeeded. 403 */ 384 404 private function deploy_unlocked( int $ttl, bool $force_cache ): array { 385 if ( ! $this->api->is_configured() ) {386 return [ 'success' => false, 'results' => [ [ 'label' => 'Error', 'success' => false, 'message' => __( 'Configure API key and Pull Zone first.', 'nahnu-cache-connector-bunny-net' ) ] ] ];387 }388 389 405 // Recorded on success. Automatic deploys requested before this moment 390 406 // are already covered by this run and skip themselves. 391 407 $started_at = microtime( true ); 408 409 if ( $this->secondary ) { 410 // Second zone on its own (a bypass-list fallback). The deploy 411 // status belongs to the main zone, so record nothing here. 412 return $this->deploy_zone( $ttl, $force_cache ); 413 } 414 415 $res = $this->deploy_zone( $ttl, $force_cache ); 416 $results = $res['results']; 417 $stats = $res['stats']; 418 419 $zone2 = WPBC_API::secondary_zone_id(); 420 if ( ! $this->secondary && $zone2 !== '' && $this->api->is_configured() ) { 421 $second = new self( $zone2 ); 422 $second->is_manual = $this->is_manual; 423 $res2 = $second->deploy_zone( $ttl, $force_cache ); 424 /* translators: %s: rule or step name */ 425 $prefix = __( 'Second pull zone: %s', 'nahnu-cache-connector-bunny-net' ); 426 foreach ( $res2['results'] as $key => $row ) { 427 $row['label'] = sprintf( $prefix, (string) ( $row['label'] ?? $key ) ); 428 $results[ 'zone2:' . $key ] = $row; 429 } 430 foreach ( [ 'unchanged', 'updated', 'created', 'removed', 'calls' ] as $k ) { 431 $stats[ $k ] = (int) ( $stats[ $k ] ?? 0 ) + (int) ( $res2['stats'][ $k ] ?? 0 ); 432 } 433 if ( ( $res2['stats']['mode'] ?? '' ) === 'full' ) { 434 $stats['mode'] = 'full'; 435 } 436 $stats['zones'] = 2; 437 } 438 439 $all_ok = ! in_array( false, array_column( $results, 'success' ), true ); 440 if ( $all_ok ) { 441 // Record the plugin version and timestamp of the last successful deploy. 442 // Used by the admin notice and the status display. 443 update_option( 'wpbc_deployed_rule_version', WPBC_VERSION, false ); 444 update_option( 'wpbc_deployed_rule_time', current_time( 'mysql' ), false ); 445 // Start time of the last successful deploy (any source). Automatic 446 // deploys requested earlier than this skip themselves. 447 update_option( 'wpbc_last_deploy_ts', $started_at, false ); 448 // The "rules are being updated after a plugin was activated" notice is 449 // satisfied by any successful deploy, manual or automatic. 450 delete_option( 'wpbc_plugin_toggle_notice' ); 451 // Clear any pending redeploy notice dismiss so it doesn't re-show after next update. 452 delete_option( 'wpbc_redeploy_notice_dismissed' ); 453 // A full deploy also clears any "rules are stale" flag set via wpbc_mark_rules_stale. 454 delete_option( 'wpbc_rules_stale' ); 455 delete_option( self::FAILURE_OPT ); 456 } else { 457 self::record_failure( $results ); 458 } 459 $this->stats = $stats; 460 return [ 'success' => $all_ok, 'results' => $results, 'stats' => $stats ]; 461 } 462 463 /** Deploy all rules to this instance's pull zone. Records nothing global. */ 464 private function deploy_zone( int $ttl, bool $force_cache ): array { 465 if ( ! $this->api->is_configured() ) { 466 return [ 'success' => false, 'results' => [ [ 'label' => 'Error', 'success' => false, 'message' => __( 'Configure API key and Pull Zone first.', 'nahnu-cache-connector-bunny-net' ) ] ] ]; 467 } 392 468 393 469 $this->pending = []; … … 485 561 ] ) ), 486 562 ]; 487 if ( ! empty( $mainwp_pz ) && class_exists( 'WPBC_MainWP' ) ) {563 if ( ! $this->secondary && ! empty( $mainwp_pz ) && class_exists( 'WPBC_MainWP' ) ) { 488 564 WPBC_MainWP::refresh_origin_host( $zone ); // Reported to the dashboard in sync data; reuses the read above. 489 565 } … … 1869 1945 $this->stats['calls'] += 1 + ( $pz_same ? 0 : 1 ); // The pull zone read, and the settings write if sent. 1870 1946 1871 update_option( self::GUIDS_OPT, $guids, false );1947 update_option( $this->guids_opt, $guids, false ); 1872 1948 $all_ok = ! in_array( false, array_column( $results, 'success' ), true ); 1873 if ( $all_ok ) {1874 // Record the plugin version and timestamp of the last successful deploy.1875 // Used by the admin notice and the status display.1876 update_option( 'wpbc_deployed_rule_version', WPBC_VERSION, false );1877 update_option( 'wpbc_deployed_rule_time', current_time( 'mysql' ), false );1878 // Start time of the last successful deploy (any source). Automatic1879 // deploys requested earlier than this skip themselves.1880 update_option( 'wpbc_last_deploy_ts', $started_at, false );1881 // The "rules are being updated after a plugin was activated" notice is1882 // satisfied by any successful deploy, manual or automatic.1883 delete_option( 'wpbc_plugin_toggle_notice' );1884 // Clear any pending redeploy notice dismiss so it doesn't re-show after next update.1885 delete_option( 'wpbc_redeploy_notice_dismissed' );1886 // A full deploy also clears any "rules are stale" flag set via wpbc_mark_rules_stale.1887 delete_option( 'wpbc_rules_stale' );1888 delete_option( self::FAILURE_OPT );1889 } else {1890 self::record_failure( $results );1891 }1892 1949 return [ 'success' => $all_ok, 'results' => $results, 'stats' => $this->stats ]; 1893 1950 } 1894 1951 1895 1952 public function remove_all(): array { 1953 $res = $this->remove_all_zone(); 1954 $zone2 = WPBC_API::secondary_zone_id(); 1955 if ( ! $this->secondary && $zone2 !== '' ) { 1956 $res2 = ( new self( $zone2 ) )->remove_all_zone(); 1957 /* translators: %s: rule name */ 1958 $prefix = __( 'Second pull zone: %s', 'nahnu-cache-connector-bunny-net' ); 1959 foreach ( $res2['results'] as $row ) { 1960 $row['label'] = sprintf( $prefix, (string) $row['label'] ); 1961 $res['results'][] = $row; 1962 } 1963 $res['success'] = $res['success'] && $res2['success']; 1964 } 1965 return $res; 1966 } 1967 1968 /** Remove the plugin's rules from this instance's pull zone only. */ 1969 private function remove_all_zone(): array { 1896 1970 $results = []; 1897 1971 $live = $this->api->get_edge_rules(); … … 1907 1981 } 1908 1982 } 1909 foreach ( get_option( self::GUIDS_OPT, [] ) as $key => $guid ) {1983 foreach ( get_option( $this->guids_opt, [] ) as $key => $guid ) { 1910 1984 if ( isset( $results[ $guid ] ) ) { 1911 1985 continue; … … 1914 1988 $results[ $guid ] = [ 'label' => $key, 'success' => ! is_wp_error( $r ), 'message' => is_wp_error( $r ) ? $r->get_error_message() : 'Deleted' ]; 1915 1989 } 1916 delete_option( self::GUIDS_OPT);1990 delete_option( $this->guids_opt ); 1917 1991 $all_ok = empty( $results ) || ! in_array( false, array_column( $results, 'success' ), true ); 1918 1992 return [ 'success' => $all_ok, 'results' => array_values( $results ) ]; … … 1920 1994 1921 1995 public function get_deployed_guids(): array { 1922 return get_option( self::GUIDS_OPT, [] );1996 return get_option( $this->guids_opt, [] ); 1923 1997 } 1924 1998 … … 2050 2124 } 2051 2125 try { 2052 return $this->deploy_bypass_urls_unlocked(); 2126 $res = $this->deploy_bypass_urls_unlocked(); 2127 $zone2 = WPBC_API::secondary_zone_id(); 2128 if ( ! $this->secondary && $zone2 !== '' ) { 2129 $res2 = ( new self( $zone2 ) )->deploy_bypass_urls_unlocked(); 2130 foreach ( (array) ( $res2['results'] ?? [] ) as $key => $row ) { 2131 $res['results'][ 'zone2:' . $key ] = $row; 2132 } 2133 $res['success'] = ! empty( $res['success'] ) && ! empty( $res2['success'] ); 2134 } 2135 return $res; 2053 2136 } finally { 2054 2137 self::release_lock(); … … 2058 2141 private function deploy_bypass_urls_unlocked(): array { 2059 2142 $results = []; 2060 $guids = (array) get_option( self::GUIDS_OPT, [] );2143 $guids = (array) get_option( $this->guids_opt, [] ); 2061 2144 $base = self::RULE_BYPASS_CUSTOM_URLS; 2062 2145 … … 2077 2160 // list grew and needs a position that was never assigned, no safe unique 2078 2161 // index exists in between, so rebuild everything with a full deploy. 2079 $order = (array) get_option( self::ORDER_OPT, [] );2162 $order = (array) get_option( $this->order_opt, [] ); 2080 2163 foreach ( $this->pending as $item ) { 2081 2164 if ( ! isset( $order[ $item['key'] ] ) ) { 2082 2165 $this->pending = []; 2083 update_option( self::GUIDS_OPT, $guids, false );2166 update_option( $this->guids_opt, $guids, false ); 2084 2167 $opts = get_option( 'wpbc_settings', [] ); 2085 2168 return $this->deploy_unlocked( … … 2091 2174 $guids = $this->flush_pending( $guids, $results, $order ); 2092 2175 2093 update_option( self::GUIDS_OPT, $guids, false );2176 update_option( $this->guids_opt, $guids, false ); 2094 2177 $all_ok = ! in_array( false, array_column( $results, 'success' ), true ); 2095 2178 return [ 'success' => $all_ok, 'results' => $results ]; … … 2384 2467 $results[ $key ] = $row; 2385 2468 } 2386 update_option( self::ORDER_OPT, $map, false );2469 update_option( $this->order_opt, $map, false ); 2387 2470 return $incremental['guids']; 2388 2471 } … … 2587 2670 } 2588 2671 } 2589 update_option( self::ORDER_OPT, $map, false );2672 update_option( $this->order_opt, $map, false ); 2590 2673 return $guids; 2591 2674 } … … 2682 2765 2683 2766 if ( $fixed === null ) { 2684 update_option( self::ORDER_OPT, $map, false );2767 update_option( $this->order_opt, $map, false ); 2685 2768 } 2686 2769 return $guids; -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-hooks.php
r3765468 r3785142 164 164 165 165 public function on_upgrade( WP_Upgrader $upgrader, array $hook_extra ): void { 166 if ( isset( $hook_extra['type'] ) && in_array( $hook_extra['type'], [ 'plugin', 'theme', 'core' ], true ) ) { 166 // Queued like any purge; at shutdown it becomes one purge after the 167 // updates are over (WPBC_Purge::defer_update_purge()). 168 if ( WPBC_Purge::update_needs_purge( $hook_extra ) ) { 167 169 $this->purge->purge_all(); 168 170 } -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-public-api.php
r3751963 r3785142 74 74 * pull_zone_id (string) — Bunny pull zone numeric ID 75 75 * pull_zone_name (string) — Bunny pull zone display name 76 * pull_zone_id_2 (string) — Second pull zone (www / non-www), or empty string 76 77 * plugin_version (string) — Current plugin version (e.g. '1.0.3') 77 78 * deployed_version (string) — Plugin version when rules were last deployed … … 103 104 'connected' => $api->is_configured(), 104 105 'pull_zone_id' => $opts['pull_zone_id'] ?? '', 106 'pull_zone_id_2' => WPBC_API::secondary_zone_id(), 105 107 'pull_zone_name' => $opts['pull_zone_name'] ?? '', 106 108 'shield_zone_id' => (string) ( $opts['shield_zone_id'] ?? '' ), … … 149 151 * 150 152 * @param array $conn Default empty array. 151 * @return array{api_key: string, pull_zone_id: string, shield_zone_id: string, from_constants: bool}|array{}153 * @return array{api_key: string, pull_zone_id: string, pull_zone_id_2: string, shield_zone_id: string, from_constants: bool}|array{} 152 154 * 153 155 * @example … … 168 170 'api_key' => $key, 169 171 'pull_zone_id' => $zone, 172 'pull_zone_id_2' => class_exists( 'WPBC_API' ) ? WPBC_API::secondary_zone_id() : '', 170 173 'shield_zone_id' => (string) ( $opts['shield_zone_id'] ?? '' ), 171 174 'from_constants' => defined( 'WPBC_API_KEY' ), -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-purge.php
r3765468 r3785142 51 51 return; 52 52 } 53 // Purges caused by an update (ours, or a cache plugin clearing itself 54 // during the update) wait until the updates are over. See defer_update_purge(). 55 if ( self::in_update_request() || ( self::update_purge_pending() && self::is_unattended() ) ) { 56 self::defer_update_purge(); 57 return; 58 } 53 59 ( new self() )->purge_all_now(); 60 } 61 62 // ── Purge after updates ─────────────────────────────────────────────────── 63 // 64 // Before 1.0.14 every update request purged the whole pull zone right away. 65 // A MainWP "update everything" sends plugins, themes and translations as 66 // separate requests, and the Plugins screen updates one plugin per request, 67 // so a site was emptied 3-10 times in a few minutes and its origin rebuilt 68 // every page each time. In a bulk update, every site on the server did it in 69 // the same minute. Now the purge waits until no update has run for 70 // UPDATE_QUIET seconds, plus this site's stagger slot for unattended updates, 71 // and runs once. It never waits more than UPDATE_MAX_WAIT in total. 72 73 public const DEFER_HOOK = 'wpbc_deferred_purge'; 74 private const DEFER_OPT = 'wpbc_update_purge'; 75 private const UPDATE_QUIET = 60; 76 private const UPDATE_MAX_WAIT = 600; 77 78 /** True during a request that installed or updated something. */ 79 private static function in_update_request(): bool { 80 return function_exists( 'did_action' ) && did_action( 'upgrader_process_complete' ) > 0; 81 } 82 83 private static function is_unattended(): bool { 84 return class_exists( 'WPBC_Throttle' ) && WPBC_Throttle::is_unattended(); 85 } 86 87 /** True while a purge after updates is waiting to run. */ 88 public static function update_purge_pending(): bool { 89 $p = get_option( self::DEFER_OPT, [] ); 90 return is_array( $p ) && ! empty( $p['due'] ); 91 } 92 93 /** Schedule (or push back) the single purge that follows a run of updates. */ 94 public static function defer_update_purge(): void { 95 $now = time(); 96 $pending = get_option( self::DEFER_OPT, [] ); 97 $first = ( is_array( $pending ) && ! empty( $pending['first'] ) ) ? (int) $pending['first'] : $now; 98 $stagger = class_exists( 'WPBC_Throttle' ) ? WPBC_Throttle::delay() : 0; 99 $quiet = max( 0, (int) apply_filters( 'wpbc_update_purge_delay', self::UPDATE_QUIET ) ); 100 $due = min( $now + $quiet + $stagger, $first + self::UPDATE_MAX_WAIT + $stagger ); 101 $due = max( $due, $now + 5 ); 102 update_option( self::DEFER_OPT, [ 'first' => $first, 'due' => $due ], true ); 103 if ( $first === $now && empty( $pending['due'] ) ) { 104 self::add_log_entry( 'full (after updates)', true, sprintf( 105 /* translators: %d: seconds */ 106 __( 'Scheduled. Runs once updates have finished, in about %d seconds.', 'nahnu-cache-connector-bunny-net' ), 107 $due - $now 108 ) ); 109 } 110 $next = wp_next_scheduled( self::DEFER_HOOK ); 111 if ( $next && $next !== $due ) { 112 wp_unschedule_event( $next, self::DEFER_HOOK ); 113 } 114 if ( $next !== $due ) { 115 wp_schedule_single_event( $due, self::DEFER_HOOK ); 116 } 117 } 118 119 /** WP-Cron handler: the updates are over, purge once. */ 120 public static function run_deferred(): void { 121 if ( ! self::update_purge_pending() ) { 122 return; 123 } 124 $p = get_option( self::DEFER_OPT, [] ); 125 if ( (int) ( $p['due'] ?? 0 ) > time() + 2 ) { 126 // Pushed back by a later update; its own event will run. 127 if ( ! wp_next_scheduled( self::DEFER_HOOK ) ) { 128 wp_schedule_single_event( (int) $p['due'], self::DEFER_HOOK ); 129 } 130 return; 131 } 132 delete_option( self::DEFER_OPT ); 133 $api = new WPBC_API(); 134 if ( ! $api->is_configured() ) { 135 return; 136 } 137 // Already staggered: start warming a minute after the purge. 138 ( new self() )->purge_all_now( 60, 'full (after updates)' ); 139 } 140 141 /** 142 * Safety net for sites where WP-Cron does not run (DISABLE_WP_CRON without a 143 * server cron): an admin or remote-manager request runs an overdue purge. 144 * One autoloaded option read; no work unless a purge is overdue. 145 */ 146 public static function run_if_overdue(): void { 147 if ( ! ( is_admin() || wp_doing_ajax() || self::is_unattended() ) || wp_doing_cron() ) { 148 return; 149 } 150 $p = get_option( self::DEFER_OPT, [] ); 151 if ( is_array( $p ) && ! empty( $p['due'] ) && (int) $p['due'] + 180 < time() ) { 152 self::run_deferred(); 153 } 154 } 155 156 /** 157 * Whether an update can change what visitors see. Updates that only touch 158 * admin-side tools (this plugin, remote management connectors, backup 159 * plugins) do not need a purge. Themes and core always do. 160 * 161 * @param array $hook_extra From upgrader_process_complete. 162 */ 163 public static function update_needs_purge( array $hook_extra ): bool { 164 $type = (string) ( $hook_extra['type'] ?? '' ); 165 if ( $type !== 'plugin' ) { 166 return in_array( $type, [ 'theme', 'core' ], true ); 167 } 168 $plugins = array_filter( array_merge( [ (string) ( $hook_extra['plugin'] ?? '' ) ], array_map( 'strval', (array) ( $hook_extra['plugins'] ?? [] ) ) ) ); 169 if ( empty( $plugins ) ) { 170 return true; // Unknown: purge to be safe. 171 } 172 $own = defined( 'WPBC_FILE' ) ? dirname( plugin_basename( WPBC_FILE ) ) : 'nahnu-cache-connector-bunny-net'; 173 $skip = (array) apply_filters( 'wpbc_no_purge_plugin_folders', [ 174 $own, 175 'mainwp-child', 'mainwp-child-reports', 'worker', 'iwp-client', 'wp-health', 176 'modular-connector', 'watchfulli', 'updraftplus', 'updraftcentral', 177 'mainwp', 'wp-crontrol', 'query-monitor', 178 ] ); 179 foreach ( $plugins as $file ) { 180 if ( ! in_array( strtok( $file, '/' ), $skip, true ) ) { 181 return true; 182 } 183 } 184 return false; 54 185 } 55 186 … … 61 192 * @return true|WP_Error 62 193 */ 63 public function purge_all_now(): bool|WP_Error { 194 /** 195 * @param int $warm_delay Seconds before the cache warmer starts. -1: one 196 * minute plus this site's stagger slot. 197 */ 198 public function purge_all_now( int $warm_delay = -1, string $context = 'full' ): bool|WP_Error { 64 199 self::$queued = false; // This purge satisfies any queued one. 65 200 66 201 $result = $this->api->purge_all(); 67 $this->log_result( $result, 'full');202 $this->log_result( $result, $context ); 68 203 69 204 if ( is_wp_error( $result ) ) { … … 76 211 // update every site purges at once, so each site starts warming at its 77 212 // own offset in the stagger window instead of all in the same minute. 78 WPBC_Warmer::schedule( 60 + ( class_exists( 'WPBC_Throttle' ) ? WPBC_Throttle::delay() : 0 ) );213 WPBC_Warmer::schedule( $warm_delay >= 0 ? $warm_delay : 60 + ( class_exists( 'WPBC_Throttle' ) ? WPBC_Throttle::delay() : 0 ) ); 79 214 WPBC_Perma_Cache::schedule_cleanup(); // Only schedules; storage API runs in cron. 80 215 return true; -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-throttle.php
r3765468 r3785142 15 15 * given site always waits the same time. Updates clicked in the site's 16 16 * own admin are not delayed. 17 * 2. Server slots. At most two automatic deploys run at the same time on one 18 * server, whatever triggered them. Coordinated with flock() on a file in 17 * 2. Server slots. At most two automatic deploys, and separately at most 18 * two cache warmer batches, run at the same time on one server, whatever 19 * triggered them. Coordinated with flock() on a file in 19 20 * the system temp folder, which every site on the server shares. Locks 20 21 * are released by the OS if PHP dies. If the temp folder is not usable … … 34 35 public const SLOTS = 2; 35 36 36 /** @var resource|null Held slot lock for this request. */ 37 private static $slot = null; 37 /** Default concurrent cache warmer batches per server. Filter: wpbc_server_warm_slots. */ 38 public const WARM_SLOTS = 2; 39 40 /** @var array<string,resource> Held slot locks for this request, by kind. */ 41 private static array $slots = []; 38 42 39 43 /** … … 77 81 * (or the safeguard is unavailable), false when every slot is busy. 78 82 */ 79 public static function acquire_slot(): bool { 80 if ( self::$slot !== null ) { 83 public static function acquire_slot( string $kind = 'deploy' ): bool { 84 $kind = $kind === 'warm' ? 'warm' : 'deploy'; 85 if ( isset( self::$slots[ $kind ] ) ) { 81 86 return true; 82 87 } 83 $slots = max( 1, min( 16, (int) apply_filters( 'wpbc_server_deploy_slots', self::SLOTS ) ) ); 88 $slots = $kind === 'warm' 89 ? (int) apply_filters( 'wpbc_server_warm_slots', self::WARM_SLOTS ) 90 : (int) apply_filters( 'wpbc_server_deploy_slots', self::SLOTS ); 91 $slots = max( 1, min( 16, $slots ) ); 84 92 $dir = self::lock_dir(); 85 93 if ( $dir === '' ) { … … 88 96 $usable = 0; 89 97 for ( $i = 0; $i < $slots; $i++ ) { 90 $file = $dir . '/wpbc- deploy-slot-' . $i . '.lock';98 $file = $dir . '/wpbc-' . $kind . '-slot-' . $i . '.lock'; 91 99 $exists = file_exists( $file ); 92 100 $handle = @fopen( $file, 'c' ); … … 100 108 } 101 109 if ( flock( $handle, LOCK_EX | LOCK_NB ) ) { 102 self::$slot = $handle;110 self::$slots[ $kind ] = $handle; 103 111 return true; 104 112 } … … 109 117 } 110 118 111 public static function release_slot(): void { 112 if ( self::$slot !== null ) { 113 flock( self::$slot, LOCK_UN ); 114 fclose( self::$slot ); 115 self::$slot = null; 119 public static function release_slot( string $kind = 'deploy' ): void { 120 $kind = $kind === 'warm' ? 'warm' : 'deploy'; 121 if ( isset( self::$slots[ $kind ] ) ) { 122 flock( self::$slots[ $kind ], LOCK_UN ); 123 fclose( self::$slots[ $kind ] ); 124 unset( self::$slots[ $kind ] ); 116 125 } 126 } 127 128 /** 129 * True when the server is already busy: the 1-minute load average is above 130 * the number of CPU cores (times the wpbc_load_threshold filter, default 1). 131 * Optional background work (the cache warmer) waits while this is true. 132 * Always false when the load or core count cannot be read. 133 */ 134 public static function server_busy(): bool { 135 if ( ! function_exists( 'sys_getloadavg' ) ) { 136 return false; 137 } 138 $load = @sys_getloadavg(); // phpcs:ignore WordPress.PHP.NoSilencedErrors -- disabled on some hosts. 139 if ( ! is_array( $load ) || ! isset( $load[0] ) ) { 140 return false; 141 } 142 $cores = self::cpu_cores(); 143 if ( $cores < 1 ) { 144 return false; 145 } 146 $factor = (float) apply_filters( 'wpbc_load_threshold', 1.0 ); 147 if ( $factor <= 0 ) { 148 return false; 149 } 150 return (float) $load[0] > $cores * $factor; 151 } 152 153 /** Number of CPU cores, or 0 when unknown. */ 154 public static function cpu_cores(): int { 155 static $cores = null; 156 if ( $cores !== null ) { 157 return $cores; 158 } 159 $cores = (int) apply_filters( 'wpbc_cpu_cores', 0 ); 160 if ( $cores > 0 ) { 161 return $cores; 162 } 163 $info = @is_readable( '/proc/cpuinfo' ) ? @file_get_contents( '/proc/cpuinfo' ) : false; // phpcs:ignore WordPress.WP.AlternativeFunctions,WordPress.PHP.NoSilencedErrors -- local proc file, open_basedir may forbid it. 164 $cores = is_string( $info ) ? (int) preg_match_all( '/^processor\s*:/m', $info ) : 0; 165 return $cores; 117 166 } 118 167 -
nahnu-cache-connector-bunny-net/trunk/includes/class-wpbc-warmer.php
r3751273 r3785142 14 14 public static function register_hooks(): void { 15 15 add_action( self::CRON_HOOK, [ static::class, 'process_batch' ] ); 16 // The cached URL list is rebuilt when the sitemap setting changes or a 17 // new page is published. 18 add_action( 'update_option_wpbc_settings', static function ( $old, $new ): void { 19 if ( ( is_array( $old ) ? ( $old['sitemap_url'] ?? '' ) : '' ) !== ( is_array( $new ) ? ( $new['sitemap_url'] ?? '' ) : '' ) ) { 20 self::forget_urls(); 21 } 22 }, 10, 2 ); 23 add_action( 'transition_post_status', static function ( $new_status, $old_status ): void { 24 if ( $new_status === 'publish' && $old_status !== 'publish' ) { 25 self::forget_urls(); 26 } 27 }, 10, 2 ); 16 28 } 17 29 … … 39 51 if ( $collect_now ) { 40 52 $urls = self::collect_urls(); 53 update_option( self::URLS_OPT, [ 't' => time(), 'urls' => $urls ], false ); 41 54 if ( empty( $urls ) ) { 42 55 return; … … 48 61 update_option( self::COLLECT_FLAG, 1, false ); 49 62 } 63 delete_option( self::POSTPONE_OPT ); 50 64 $next = wp_next_scheduled( self::CRON_HOOK ); 51 65 if ( $next ) { … … 55 69 } 56 70 71 /** Cached URL list: rebuilt from the sitemap at most this often. */ 72 private const URLS_OPT = 'wpbc_warm_urls'; 73 private const URLS_TTL = 6 * HOUR_IN_SECONDS; 74 75 /** Postponements while the server is busy, before the run is dropped. */ 76 private const POSTPONE_OPT = 'wpbc_warm_postponed'; 77 private const POSTPONE_MAX = 30; 78 79 /** A batch stops starting new requests after this many seconds. */ 80 private const BATCH_BUDGET = 25; 81 82 /** 83 * Warm one batch. 84 * 85 * Before 1.0.14 a batch sent all its requests at once (non-blocking), every 86 * site warmed whenever it liked, and the sitemap was fetched again after 87 * every purge. On a server with many sites, a bulk update had dozens of 88 * sites rebuilding pages in parallel. Now: 89 * - pages are requested one after another, so one site never has more 90 * than one warm request on the origin; 91 * - at most two sites warm at the same time on one server (wpbc_server_warm_slots); 92 * - warming waits while the server load is above its core count 93 * (wpbc_load_threshold), and gives up after about an hour; 94 * - the sitemap is read at most every 6 hours. 95 */ 57 96 public static function process_batch(): void { 58 97 if ( get_option( self::COLLECT_FLAG ) ) { 59 98 delete_option( self::COLLECT_FLAG ); 60 update_option( self::QUEUE_OPT, self::c ollect_urls(), false );99 update_option( self::QUEUE_OPT, self::cached_urls(), false ); 61 100 } 62 101 $queue = get_option( self::QUEUE_OPT, [] ); … … 69 108 $delay = max( 5, min( 300, (int) ( $opts['warmer_batch_delay'] ?? self::DEFAULT_DELAY ) ) ); 70 109 110 // Warming is optional. A busy server, or two other sites already 111 // warming, comes first: try again in a minute or two. 112 $throttle = class_exists( 'WPBC_Throttle' ); 113 if ( $throttle && ( WPBC_Throttle::server_busy() || ! WPBC_Throttle::acquire_slot( 'warm' ) ) ) { 114 $tries = (int) get_option( self::POSTPONE_OPT, 0 ) + 1; 115 if ( $tries > self::POSTPONE_MAX ) { 116 self::cancel(); // The server stayed busy: visitors will fill the cache. 117 return; 118 } 119 update_option( self::POSTPONE_OPT, $tries, false ); 120 wp_schedule_single_event( time() + WPBC_Throttle::retry_delay(), self::CRON_HOOK ); 121 return; 122 } 123 delete_option( self::POSTPONE_OPT ); 124 71 125 $batch = array_splice( $queue, 0, $batch_size ); 126 $start = microtime( true ); 127 try { 128 while ( $batch ) { 129 if ( microtime( true ) - $start > self::BATCH_BUDGET ) { 130 break; // Slow origin: leave the rest for the next batch. 131 } 132 $url = array_shift( $batch ); 133 wp_remote_get( $url, [ 134 'timeout' => 15, 135 'user-agent' => 'WP-Bunny-Warmer/1.0', 136 'sslverify' => false, 137 'limit_response_size' => 2 * MB_IN_BYTES, 138 ] ); 139 } 140 } finally { 141 if ( $throttle ) { 142 WPBC_Throttle::release_slot( 'warm' ); 143 } 144 } 145 $queue = array_merge( $batch, $queue ); 72 146 update_option( self::QUEUE_OPT, $queue, false ); 73 74 foreach ( $batch as $url ) {75 wp_remote_get( $url, [76 'timeout' => 10,77 'blocking' => false,78 'user-agent' => 'WP-Bunny-Warmer/1.0',79 'sslverify' => false,80 ] );81 }82 147 83 148 if ( ! empty( $queue ) ) { 84 149 wp_schedule_single_event( time() + $delay, self::CRON_HOOK ); 85 150 } 151 } 152 153 /** URL list from the last 6 hours, or a fresh one from the sitemap. */ 154 private static function cached_urls(): array { 155 $cached = get_option( self::URLS_OPT, [] ); 156 if ( is_array( $cached ) && ! empty( $cached['urls'] ) && (int) ( $cached['t'] ?? 0 ) > time() - self::URLS_TTL ) { 157 return (array) $cached['urls']; 158 } 159 $urls = self::collect_urls(); 160 update_option( self::URLS_OPT, [ 't' => time(), 'urls' => $urls ], false ); 161 return $urls; 162 } 163 164 /** Forget the cached URL list (sitemap setting changed). */ 165 public static function forget_urls(): void { 166 delete_option( self::URLS_OPT ); 86 167 } 87 168 … … 101 182 delete_option( self::QUEUE_OPT ); 102 183 delete_option( self::COLLECT_FLAG ); 184 delete_option( self::POSTPONE_OPT ); 103 185 } 104 186 -
nahnu-cache-connector-bunny-net/trunk/readme.txt
r3782406 r3785142 4 4 Requires at least: 6.0 5 5 Tested up to: 7.1 6 Stable tag: 1.0.1 36 Stable tag: 1.0.14 7 7 Requires PHP: 8.0 8 8 License: GPLv2 or later … … 173 173 = Cache warmer = 174 174 175 After a full purge, a background job crawls your sitemap to pre-warm the CDN edge. 175 After a full purge, a background job crawls your sitemap to pre-warm the CDN edge. It requests one page at a time, at most two sites warm at once on the same server, and it waits while the server is busy, so warming never competes with real visitors. 176 176 177 177 **Supported SEO plugins for sitemap auto-detection:** … … 281 281 It integrates with the 18 cache plugins listed above. Without one of them you can still use the edge rules, manual purge, admin bar button, CDN stats and the post save and update purge triggers. Purges just are not mirrored from a cache plugin. 282 282 283 = My site uses www and non-www on two pull zones. Does that work? = 284 Yes. Pick the second pull zone under Settings, Second pull zone (optional), or define WPBC_PULL_ZONE_ID_2 in wp-config.php. Both zones then get the same edge rules, and every purge clears both. If one pull zone already lists both hostnames, or one hostname redirects to the other before it reaches Bunny, you do not need a second zone. The settings screen tells you which case applies once your zones are loaded. 285 283 286 = Do I need to redeploy edge rules after updating the plugin? = 284 287 … … 312 315 313 316 To avoid a CPU spike on servers that host many sites. Updates pushed from a dashboard, by WordPress auto-updates or by WP-CLI give each site its own fixed slot of up to 5 minutes, and at most two sites on one server deploy at once. Updates you click in a site's own admin deploy straight away. Developers can change the window with the `wpbc_stagger_window` filter and the per-server limit with `wpbc_server_deploy_slots`. 317 318 = Why does the purge after an update happen a minute or two later? = 319 320 So the site is purged once, after all the updates have finished, instead of after every single plugin or theme. A dashboard update usually arrives as several separate requests, and each one used to empty the CDN, so the server rebuilt every page several times. Updates pushed from a dashboard also wait for the site's own slot, so the sites on one server do not all purge in the same minute. Updates to admin-only plugins (this plugin, remote management connectors, backup plugins) do not purge at all. Developers can change the wait with the `wpbc_update_purge_delay` filter and the skipped plugins with `wpbc_no_purge_plugin_folders`. 314 321 315 322 = The Bricks code editor or WordPress 7.1 image uploads fail with Shield on. What do I do? = … … 382 389 == Upgrade Notice == 383 390 391 = 1.0.14 = 392 Adds a second pull zone for www and non-www on separate zones, fixes rules on www sites never matching the non-www address, and cuts server load after updates: one purge once updates finish, and a gentler cache warmer. Edge rules update automatically after updating. 393 384 394 = 1.0.13 = 385 395 Fixes sites going down for up to 10 minutes after a long theme update from MainWP or another dashboard. Updates now always finish, even when the CDN cuts the connection at 60 seconds. … … 410 420 411 421 == Changelog == 422 423 = 1.0.14 = 424 * Added: Second pull zone support, for sites whose www and non-www hostnames are on separate Bunny pull zones. Choose it in Settings or define WPBC_PULL_ZONE_ID_2 in wp-config.php. Both zones get the same edge rules from one deploy, every full purge clears both zones, and every URL purge clears the page under both hostnames. A deploy only counts as done when both zones succeed. 425 * Added: Once your zones are loaded, the settings screen says whether a second zone is needed: it points out a zone that serves the other hostname, or tells you the main zone already serves both. 426 * Fixed: On sites whose address starts with www, every edge rule matched the www hostname twice and the non-www hostname never, so bypass and cache rules did not apply to visitors on the non-www address. Rules now match both, whichever one the site uses. 427 * Added: pull_zone_id_2 in the wpbc_status and wpbc_bunny_connection filters for other plugins. 428 * Improved: High CPU after updates. Every update request emptied the whole CDN straight away. A dashboard update usually arrives as several requests (plugins, themes, translations), and the Plugins screen updates one plugin per request, so a site was purged up to 10 times in a few minutes and the server rebuilt every page each time. Now the site is purged once, a minute after the last update. Updates pushed from a dashboard, by auto-updates or by WP-CLI also wait for the site's own slot of up to 5 minutes, so the sites on one server do not all purge together. 429 * Improved: Updates to admin-only plugins no longer purge the CDN: this plugin, MainWP Dashboard and Child, ManageWP Worker, InfiniteWP, WP Umbrella, Modular DS, Watchful, UpdraftPlus, WP Crontrol and Query Monitor. 430 * Improved: The cache warmer requests one page at a time instead of a whole batch at once, at most two sites warm at the same time on one server, and it waits while the server load is above its number of CPU cores. If the server stays busy for about an hour, that warm run is skipped and visitors fill the cache. 431 * Improved: The cache warmer reuses its URL list for 6 hours instead of reading every sitemap after each purge. The list is rebuilt when a new page is published or the sitemap setting changes. 432 * Added: Filters wpbc_update_purge_delay, wpbc_no_purge_plugin_folders, wpbc_server_warm_slots, wpbc_load_threshold and wpbc_cpu_cores. 412 433 413 434 = 1.0.13 = -
nahnu-cache-connector-bunny-net/trunk/uninstall.php
r3765468 r3785142 42 42 'wpbc_deploy_last_failure', // Last failed deploy + retry back-off 43 43 'wpbc_edge_rule_order', // Edge rule key => OrderIndex from last deploy 44 'wpbc_edge_rule_guids_z2', // Same, second pull zone (www / non-www) 45 'wpbc_edge_rule_order_z2', // Same, second pull zone 46 'wpbc_update_purge', // Pending purge after updates 47 'wpbc_warm_urls', // Cached cache warmer URL list 48 'wpbc_warm_postponed', // Warmer waits while the server is busy 44 49 'wpbc_deploy_preempt', // Manual deploy asking an automatic one to yield 45 50 'wpbc_deploy_requested_at', // Post-update deploy request time … … 76 81 wp_clear_scheduled_hook( 'wpbc_warm_batch' ); 77 82 wp_clear_scheduled_hook( 'wpbc_auto_deploy' ); 83 wp_clear_scheduled_hook( 'wpbc_deferred_purge' ); 78 84 wp_clear_scheduled_hook( 'wpbc_check_rules' ); 79 85 wp_clear_scheduled_hook( 'wpbc_perma_cleanup' ); -
nahnu-cache-connector-bunny-net/trunk/wp-bunny-connector.php
r3782406 r3785142 4 4 * Plugin URI: https://www.wpbunnyconnector.com/ 5 5 * Description: Connects WordPress cache plugins to Bunny.net CDN. Automatic purging, 75 edge rules, cache warming, Perma-Cache cleanup, and live CDN stats, all in one place. 6 * Version: 1.0.1 36 * Version: 1.0.14 7 7 * Requires at least: 6.0 8 8 * Requires PHP: 8.0 … … 46 46 } 47 47 48 define( 'WPBC_VERSION', '1.0.1 3' );48 define( 'WPBC_VERSION', '1.0.14' ); 49 49 define( 'WPBC_FILE', __FILE__ ); 50 50 define( 'WPBC_DIR', plugin_dir_path( __FILE__ ) ); … … 130 130 131 131 WPBC_Warmer::register_hooks(); 132 add_action( WPBC_Purge::DEFER_HOOK, [ 'WPBC_Purge', 'run_deferred' ] ); 133 add_action( 'shutdown', [ 'WPBC_Purge', 'run_if_overdue' ], 5 ); 132 134 add_action( 'wpbc_perma_cleanup', [ 'WPBC_Perma_Cache', 'maybe_cleanup' ] ); 133 135 … … 165 167 register_deactivation_hook( __FILE__, static function (): void { 166 168 wp_clear_scheduled_hook( 'wpbc_auto_deploy' ); 169 wp_clear_scheduled_hook( 'wpbc_deferred_purge' ); 170 delete_option( 'wpbc_update_purge' ); 167 171 wp_clear_scheduled_hook( 'wpbc_check_rules' ); 168 172 wp_clear_scheduled_hook( 'wpbc_perma_cleanup' );
Note:
See TracChangeset
for help on using the changeset viewer.