Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.77% covered (success)
94.77%
344 / 363
69.57% covered (warning)
69.57%
16 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Indexnow_Queue
94.77% covered (success)
94.77%
344 / 363
69.57% covered (warning)
69.57%
16 / 23
161.58
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 preference_changed
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 capacity
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 rows
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 size
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 row
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 compare_and_swap
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 delete_rows
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 lock
87.50% covered (warning)
87.50%
21 / 24
0.00% covered (danger)
0.00%
0 / 1
8.12
 generation
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 admit_simple
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
7.03
 enqueue
94.03% covered (success)
94.03%
63 / 67
0.00% covered (danger)
0.00%
0 / 1
22.10
 discard_post
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
9.00
 ensure_recovery
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 schedule
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 clear_if_used
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 clear
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
17
 record_status
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 store_status_option
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 invalidate_summary_cache
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 work
94.93% covered (success)
94.93%
131 / 138
0.00% covered (danger)
0.00%
0 / 1
56.41
 notification_bytes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 resolve
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
6.04
1<?php
2/**
3 * Durable IndexNow notifications with bounded reads and versioned ownership.
4 *
5 * @package automattic/jetpack-seo
6 */
7
8namespace Automattic\Jetpack\SEO;
9
10use Automattic\Jetpack\Status\Host;
11
12/**
13 * Stores pending URLs independently of caches and scheduler availability.
14 */
15class Indexnow_Queue {
16    const PREFIX               = 'jetpack_seo_indexnow_q_';
17    const CAPACITY             = 10000;
18    const HOOK                 = 'jetpack_seo_indexnow_worker';
19    const RECOVERY_HOOK        = 'jetpack_seo_indexnow_recovery';
20    const STATUS_OPTION        = 'jetpack_seo_indexnow_status';
21    const ACCEPTED_OPTION      = 'jetpack_seo_indexnow_last_accepted';
22    const GENERATION_OPTION    = 'jetpack_seo_indexnow_generation';
23    const CURSOR_OPTION        = 'jetpack_seo_indexnow_cursor';
24    const COOLDOWN_OPTION      = 'jetpack_seo_indexnow_cooldown';
25    const ADMISSION_LOCK       = 'jetpack_seo_indexnow_admission_lock';
26    const WORKER_LOCK          = 'jetpack_seo_indexnow_worker_lock';
27    const PAGE_SIZE            = 250;
28    const SCAN_LIMIT           = 5000;
29    const BATCH_BYTES          = 1048576;
30    const SIMPLE_OPTIONS_BYTES = 750000;
31
32    /** Register hooks without selecting a site or scheduling work. */
33    public static function init() {
34        add_action( 'jetpack_seo_indexnow_url_changed', array( __CLASS__, 'enqueue' ), 10, 3 );
35        add_action( 'jetpack_seo_indexnow_post_restricted', array( __CLASS__, 'discard_post' ) );
36        add_action( self::HOOK, array( __CLASS__, 'work' ) );
37        add_action( self::RECOVERY_HOOK, array( __CLASS__, 'work' ) );
38        add_action( 'jetpack_deactivate_module_seo-tools', array( __CLASS__, 'clear_if_used' ) );
39        add_action( 'update_option_home', array( __CLASS__, 'clear_if_used' ) );
40        add_action( 'update_option_' . Indexnow_Client::ENABLED_OPTION, array( __CLASS__, 'preference_changed' ), 10, 2 );
41    }
42
43    /**
44     * Reset pending work when consent is withdrawn outside the settings endpoint.
45     *
46     * @param mixed $old Previous preference.
47     * @param mixed $enabled Saved preference.
48     */
49    public static function preference_changed( $old, $enabled ) {
50        if ( ! $enabled ) {
51            self::clear();
52        }
53    }
54
55    /**
56     * Bound admissions without changing the identity or visibility of stored rows.
57     *
58     * @return int
59     */
60    public static function capacity() {
61        /**
62         * Filters the maximum pending IndexNow URLs admitted on a site.
63         *
64         * @since $$next-version$$
65         * @param int $capacity Pending URLs, between 1 and 50,000.
66         */
67        $capacity = apply_filters( 'jetpack_seo_indexnow_queue_capacity', self::CAPACITY );
68        return is_int( $capacity ) ? max( 1, min( 50000, $capacity ) ) : self::CAPACITY;
69    }
70
71    /**
72     * Read a bounded page directly from durable storage.
73     *
74     * @param int    $limit Maximum rows.
75     * @param string $after Previous row name for keyset pagination.
76     * @return array
77     */
78    public static function rows( $limit = self::PAGE_SIZE, $after = '' ) {
79        global $wpdb;
80        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Durable ownership must bypass option caches.
81        return $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s AND option_name > %s ORDER BY option_name LIMIT %d", $wpdb->esc_like( self::PREFIX ) . '%', $after, max( 1, min( 1000, $limit ) ) ), ARRAY_A );
82    }
83
84    /**
85     * Count pending rows without loading their payloads.
86     *
87     * @return int
88     */
89    public static function size() {
90        global $wpdb;
91        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Admission needs the current durable count.
92        return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->options WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX ) . '%' ) );
93    }
94
95    /**
96     * Read one durable row, bypassing stale option caches.
97     *
98     * @param string $name Option name.
99     * @return array|null
100     */
101    private static function row( $name ) {
102        global $wpdb;
103        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Compare-and-swap requires the actual persisted version.
104        return $wpdb->get_row( $wpdb->prepare( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name = %s", $name ), ARRAY_A );
105    }
106
107    /**
108     * Change a row only if its exact version remains owned.
109     *
110     * @param array       $row Observed durable row.
111     * @param array|null  $next Replacement, or null to delete.
112     * @param string|null $generation Required queue generation for a replacement.
113     * @return bool
114     */
115    public static function compare_and_swap( $row, $next, $generation = null ) {
116        global $wpdb;
117        $where = array(
118            'option_name'  => $row['option_name'],
119            'option_value' => $row['option_value'],
120        );
121        if ( null !== $generation && null !== $next ) {
122            // LIMIT keeps the generation subquery materialized, avoiding MySQL's target-table restriction.
123            // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Check the queue fence in the same statement as the conditional replacement.
124            $changed = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s AND option_value = %s AND EXISTS (SELECT 1 FROM (SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1) AS queue_generation WHERE queue_generation.option_value = %s)", wp_json_encode( $next, JSON_UNESCAPED_SLASHES ), $row['option_name'], $row['option_value'], self::GENERATION_OPTION, $generation ) );
125        } else {
126            // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Conditional writes prevent stale acknowledgments.
127            $changed = null === $next ? $wpdb->delete( $wpdb->options, $where ) : $wpdb->update( $wpdb->options, array( 'option_value' => wp_json_encode( $next, JSON_UNESCAPED_SLASHES ) ), $where );
128        }
129        wp_cache_delete( $row['option_name'], 'options' );
130        return 1 === $changed;
131    }
132
133    /**
134     * Delete a bounded snapshot without clearing newer row versions.
135     *
136     * @param array       $rows Observed rows.
137     * @param string|null $generation Required queue generation during a reset.
138     * @return int
139     */
140    private static function delete_rows( $rows, $generation = null ) {
141        global $wpdb;
142        $conditions = array();
143        $values     = array();
144        foreach ( $rows as $row ) {
145            $conditions[] = '(option_name = %s AND option_value = %s)';
146            $values[]     = $row['option_name'];
147            $values[]     = $row['option_value'];
148        }
149        $where = '(' . implode( ' OR ', $conditions ) . ')';
150        if ( null !== $generation ) {
151            $where   .= " AND EXISTS (SELECT 1 FROM (SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1) AS queue_generation WHERE queue_generation.option_value = %s)";
152            $values[] = self::GENERATION_OPTION;
153            $values[] = $generation;
154        }
155        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Conditions contain only bound placeholders.
156        $removed = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE $where", $values ) );
157        foreach ( $rows as $row ) {
158            wp_cache_delete( $row['option_name'], 'options' );
159        }
160        return (int) $removed;
161    }
162
163    /**
164     * Acquire an expiring lock with an owner token.
165     *
166     * @param string $name Lock name.
167     * @return array|null Owned durable row.
168     */
169    private static function lock( $name ) {
170        $value = array(
171            'owner'   => wp_generate_uuid4(),
172            'expires' => time() + 60,
173        );
174        $json  = wp_json_encode( $value, JSON_UNESCAPED_SLASHES );
175        $old   = self::row( $name );
176        if ( $old ) {
177            $previous = json_decode( $old['option_value'], true );
178            if ( ( $previous['expires'] ?? 0 ) >= time() || ! self::compare_and_swap( $old, $value ) ) {
179                return null;
180            }
181        } else {
182            global $wpdb;
183            if ( self::ADMISSION_LOCK === $name ) {
184                // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Avoid shared duplicate-key locks when writers concurrently create the lease.
185                $inserted = $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %s, 'no') ON DUPLICATE KEY UPDATE option_name = option_name", $name, $json ) );
186            } else {
187                // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Other requests cannot invalidate a nonpersistent option cache.
188                $inserted = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $name, $json ) );
189            }
190            wp_cache_delete( $name, 'options' );
191            if ( 1 !== $inserted ) {
192                return null;
193            }
194            if ( self::ADMISSION_LOCK === $name && self::row( $name ) !== array(
195                'option_name'  => $name,
196                'option_value' => $json,
197            ) ) {
198                return null;
199            }
200        }
201        return array(
202            'option_name'  => $name,
203            'option_value' => $json,
204        );
205    }
206
207    /**
208     * Read the current generation after establishing writer-consistent routing.
209     *
210     * @return string|null
211     */
212    private static function generation() {
213        global $wpdb;
214        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The write also pins subsequent options reads on replicated hosts.
215        $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, '0', 'no')", self::GENERATION_OPTION ) );
216        $row = self::row( self::GENERATION_OPTION );
217        return $row ? $row['option_value'] : null;
218    }
219
220    /**
221     * Bound growing Simple records while holding the admission lock.
222     *
223     * @param string     $name Option name.
224     * @param string     $value Encoded notification.
225     * @param array|null $old Previous durable row.
226     * @param array      $lock Admission lock.
227     * @param string     $generation Current queue generation.
228     * @return bool
229     */
230    private static function admit_simple( $name, $value, $old, $lock, $generation ) {
231        global $wpdb;
232        $delta = strlen( $name ) + strlen( $value ) + strlen( (string) strlen( $name ) ) + strlen( (string) strlen( $value ) ) + 12;
233        if ( $old ) {
234            $delta -= strlen( $name ) + strlen( $old['option_value'] ) + strlen( (string) strlen( $name ) ) + strlen( (string) strlen( $old['option_value'] ) ) + 12;
235        }
236        // Keep the scan read-only; queue writers serialize on the admission lock.
237        // The estimate includes string serialization and a conservative array header.
238        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Measure options without caching their values.
239        $storage = $wpdb->get_row( $wpdb->prepare( "SELECT COALESCE(SUM(OCTET_LENGTH(option_name) + OCTET_LENGTH(option_value) + OCTET_LENGTH(OCTET_LENGTH(option_name)) + OCTET_LENGTH(OCTET_LENGTH(option_value)) + 12), 0) + 64 AS bytes, COALESCE(SUM(option_name LIKE %s), 0) AS pending FROM $wpdb->options", $wpdb->esc_like( self::PREFIX ) . '%' ), ARRAY_A );
240        if ( ! $storage || $storage['bytes'] + $delta > self::SIMPLE_OPTIONS_BYTES || ( ! $old && $storage['pending'] >= self::capacity() ) ) {
241            return false;
242        }
243        $fence = $wpdb->prepare( "EXISTS (SELECT 1 FROM (SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1) AS queue_owner WHERE queue_owner.option_value = %s) AND EXISTS (SELECT 1 FROM (SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1) AS queue_generation WHERE queue_generation.option_value = %s)", self::ADMISSION_LOCK, $lock['option_value'], self::GENERATION_OPTION, $generation );
244        if ( $old ) {
245            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Fences contain bound values and prevent a stale size check from surviving another queue writer or reset.
246            $changed = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s AND option_value = %s AND $fence", $value, $name, $old['option_value'] ) );
247        } else {
248            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Verify ownership in the same statement as the admission without locking unrelated options.
249            $changed = $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) SELECT %s, %s, 'no' FROM DUAL WHERE $fence", $name, $value ) );
250        }
251        wp_cache_delete( $name, 'options' );
252        return 1 === $changed;
253    }
254
255    /**
256     * Admit or replace a URL without scanning pending payloads.
257     *
258     * @param string $url Public URL.
259     * @param int    $post_id Source post ID.
260     * @param bool   $deleted Whether this describes the previous public URL.
261     * @return bool
262     */
263    public static function enqueue( $url, $post_id, $deleted = false ) {
264        $post_id = (int) $post_id;
265        if ( $post_id < 1 || ! Indexnow_Client::enabled() || ! Indexnow_Client::in_scope( $url ) ) {
266            return false;
267        }
268        $generation = self::generation();
269        if ( null === $generation ) {
270            return false;
271        }
272        $name = self::PREFIX . ( $deleted ? hash( 'sha256', $url ) : 'p_' . $post_id );
273        $item = array(
274            'generation' => $generation,
275            'url'        => $url,
276            'post'       => $post_id,
277            'deleted'    => (bool) $deleted,
278            'scope'      => Indexnow_Client::scope(),
279            'version'    => wp_generate_uuid4(),
280            'due'        => time() + 300,
281            'attempt'    => 0,
282            'created'    => time(),
283        );
284        if ( ! $deleted ) {
285            unset( $item['url'] );
286        }
287        $json   = wp_json_encode( $item, JSON_UNESCAPED_SLASHES );
288        $simple = ( new Host() )->is_wpcom_simple();
289        for ( $attempt = 0; $attempt < 40; ++$attempt ) {
290            if ( $attempt && self::generation() !== $generation ) {
291                return false;
292            }
293            $old = self::row( $name );
294            if ( $old && ( ! $simple || strlen( $json ) <= strlen( $old['option_value'] ) ) ) {
295                if ( ! self::compare_and_swap( $old, $item, $generation ) ) {
296                    continue;
297                }
298            } else {
299                $lock = self::lock( self::ADMISSION_LOCK );
300                if ( ! $lock ) {
301                    usleep( 2000 );
302                    continue;
303                }
304                try {
305                    if ( $simple ) {
306                        $old = self::row( $name );
307                        if ( ! self::admit_simple( $name, $json, $old, $lock, $generation ) ) {
308                            if ( self::generation() !== $generation || ! Indexnow_Client::enabled() ) {
309                                return false;
310                            }
311                            break;
312                        }
313                    } else {
314                        if ( self::row( $name ) ) {
315                            continue;
316                        }
317                        if ( self::size() >= self::capacity() ) {
318                            break;
319                        }
320                        global $wpdb;
321                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Fence inserts against replacement of an expired admission lock.
322                        $added = $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) SELECT %s, %s, 'no' FROM DUAL WHERE EXISTS (SELECT 1 FROM $wpdb->options WHERE option_name = %s AND option_value = %s) AND EXISTS (SELECT 1 FROM $wpdb->options WHERE option_name = %s AND option_value = %s)", $name, wp_json_encode( $item, JSON_UNESCAPED_SLASHES ), $lock['option_name'], $lock['option_value'], self::GENERATION_OPTION, $generation ) );
323                        wp_cache_delete( $name, 'options' );
324                        if ( 1 !== $added ) {
325                            continue;
326                        }
327                    }
328                } finally {
329                    // Reuse the row to avoid duplicate-key gap-lock deadlocks during parallel admissions.
330                    self::compare_and_swap(
331                        $lock,
332                        array(
333                            'owner'   => '',
334                            'expires' => 0,
335                        )
336                    );
337                }
338            }
339            self::ensure_recovery();
340            self::schedule();
341            return true;
342        }
343        update_option(
344            'jetpack_seo_indexnow_enqueue_error',
345            array(
346                'state'   => 'queue_full_or_busy',
347                'time'    => time(),
348                'version' => wp_generate_uuid4(),
349            ),
350            false
351        );
352        return false;
353    }
354
355    /**
356     * Cancel matching URLs before deletion can erase a restriction.
357     *
358     * @param int $post_id Restricted post ID.
359     */
360    public static function discard_post( $post_id ) {
361        if ( ( new Host() )->is_vip_site() || ! Initializer::is_available() || ! get_option( Indexnow_Client::ENABLED_OPTION, false ) ) {
362            return;
363        }
364        if ( null === self::generation() ) {
365            return;
366        }
367        global $wpdb;
368        do {
369            // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Filter in storage to avoid loading unrelated URL payloads.
370            $rows      = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s AND option_value LIKE %s ORDER BY option_name LIMIT %d", $wpdb->esc_like( self::PREFIX ) . '%', '%"post":' . (int) $post_id . ',%', self::PAGE_SIZE ), ARRAY_A );
371            $removed   = $rows ? self::delete_rows( $rows ) : 0;
372            $full_page = is_array( $rows ) && count( $rows ) === self::PAGE_SIZE;
373        } while ( $full_page && $removed );
374    }
375
376    /** Recover work after a lost single-event schedule. */
377    public static function ensure_recovery() {
378        if ( ! wp_next_scheduled( self::RECOVERY_HOOK ) ) {
379            wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', self::RECOVERY_HOOK );
380        }
381    }
382
383    /**
384     * Schedule one bounded worker, respecting the site's service cooldown.
385     *
386     * @param int $delay Seconds until work may run.
387     */
388    public static function schedule( $delay = 300 ) {
389        $when = max( time() + $delay, (int) get_option( self::COOLDOWN_OPTION, 0 ) );
390        $next = wp_next_scheduled( self::HOOK );
391        if ( ! $next || $next > $when ) {
392            if ( $next ) {
393                wp_unschedule_event( $next, self::HOOK );
394            }
395            wp_schedule_single_event( $when, self::HOOK );
396        }
397    }
398
399    /**
400     * Avoid queue work for passive site changes before the first admission.
401     *
402     * @since $$next-version$$
403     */
404    public static function clear_if_used() {
405        if ( self::row( self::GENERATION_OPTION ) ) {
406            self::clear();
407        }
408    }
409
410    /** Discard pending work without depending on the current admission limit. */
411    public static function clear() {
412        if ( ( new Host() )->is_vip_site() || ! Initializer::is_available() ) {
413            return;
414        }
415        $generation = wp_generate_uuid4();
416        update_option( self::GENERATION_OPTION, $generation, false );
417        $after = '';
418        $rows  = self::rows();
419        while ( $rows ) {
420            $stale = array();
421            foreach ( $rows as $row ) {
422                $after = $row['option_name'];
423                if ( ( json_decode( $row['option_value'], true )['generation'] ?? '' ) !== $generation ) {
424                    $stale[] = $row;
425                }
426            }
427            if ( $stale ) {
428                self::delete_rows( $stale, $generation );
429            }
430            if ( self::generation() !== $generation ) {
431                return;
432            }
433            $rows = self::rows( self::PAGE_SIZE, $after );
434        }
435        $history = array();
436        foreach ( array( self::CURSOR_OPTION, self::COOLDOWN_OPTION, self::STATUS_OPTION, self::ACCEPTED_OPTION, 'jetpack_seo_indexnow_enqueue_error' ) as $option ) {
437            $row = self::row( $option );
438            if ( ! $row ) {
439                continue;
440            }
441            $receipt = maybe_unserialize( $row['option_value'] );
442            if ( self::ACCEPTED_OPTION === $option && is_array( $receipt ) && 'accepted' === ( $receipt['state'] ?? '' ) && get_option( Indexnow_Client::SCOPE_OPTION, '' ) === Indexnow_Client::scope() ) {
443                continue;
444            }
445            $history[] = $row;
446        }
447        if ( $history ) {
448            self::delete_rows( $history, $generation );
449            self::invalidate_summary_cache( array_column( $history, 'option_name' ) );
450        }
451        wp_clear_scheduled_hook( self::HOOK );
452        wp_clear_scheduled_hook( self::RECOVERY_HOOK );
453        if ( self::rows( 1 ) && Indexnow_Client::enabled() ) {
454            self::ensure_recovery();
455            self::schedule();
456        }
457    }
458
459    /**
460     * Preserve received status separately from later failed attempts.
461     *
462     * @param array  $status Delivery summary without URL payloads.
463     * @param string $generation Queue generation that produced the summary.
464     */
465    private static function record_status( $status, $generation ) {
466        if ( in_array( $status['state'], array( 'accepted', 'verification_pending' ), true ) ) {
467            self::store_status_option(
468                self::ACCEPTED_OPTION,
469                array(
470                    'time'  => $status['time'],
471                    'count' => $status['count'],
472                    'state' => $status['state'],
473                ),
474                $generation
475            );
476        }
477        self::store_status_option( self::STATUS_OPTION, $status, $generation );
478    }
479
480    /**
481     * Store worker state only while its queue generation still exists.
482     *
483     * @param string $name Status option name.
484     * @param mixed  $value Status value.
485     * @param string $generation Queue generation that produced this value.
486     */
487    private static function store_status_option( $name, $value, $generation ) {
488        global $wpdb;
489        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The same-statement fence prevents a reset from being followed by an obsolete status write.
490        $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) SELECT %s, %s, 'no' FROM DUAL WHERE EXISTS (SELECT 1 FROM $wpdb->options WHERE option_name = %s AND option_value = %s) ON DUPLICATE KEY UPDATE option_value = VALUES(option_value), autoload = 'no'", $name, maybe_serialize( $value ), self::GENERATION_OPTION, $generation ) );
491        wp_cache_delete( $name, 'options' );
492        wp_cache_delete( 'notoptions', 'options' );
493        self::invalidate_summary_cache( array( $name ) );
494    }
495
496    /**
497     * Preserve the shared cache on hosts that cache only autoloaded options.
498     *
499     * @param string[] $names Changed summary options.
500     */
501    private static function invalidate_summary_cache( $names ) {
502        $cached = wp_cache_get( 'alloptions', 'options' );
503        if ( ( new Host() )->is_wpcom_simple() || array_intersect_key( (array) $cached, array_fill_keys( $names, true ) ) ) {
504            wp_cache_delete( 'alloptions', 'options' );
505        }
506    }
507
508    /** Process a bounded sweep with an expiring worker lock. */
509    public static function work() {
510        if ( ( new Host() )->is_vip_site() || ! Initializer::is_available() || ! apply_filters( 'jetpack_seo_indexnow_can_notify', true ) || Seo_Tools::is_disabled() ) {
511            return;
512        }
513        if ( ! Indexnow_Client::enabled() ) {
514            self::clear();
515            return;
516        }
517        $cooldown = (int) get_option( self::COOLDOWN_OPTION, 0 );
518        if ( $cooldown > time() ) {
519            self::schedule( $cooldown - time() );
520            return;
521        }
522        $lock = self::lock( self::WORKER_LOCK );
523        if ( ! $lock ) {
524            return;
525        }
526        try {
527            $generation = self::generation();
528            if ( null === $generation ) {
529                self::schedule( 60 );
530                return;
531            }
532            $cursor          = (string) get_option( self::CURSOR_OPTION, '' );
533            $claimed         = array();
534            $claimed_bytes   = 0;
535            $deadline        = microtime( true ) + 20;
536            $expired         = 0;
537            $budget          = max( self::SCAN_LIMIT, Indexnow_Client::batch_size() );
538            $started_at_head = '' === $cursor;
539            $complete        = false;
540            $earliest_due    = PHP_INT_MAX;
541            $claimed_count   = 0;
542            while ( $budget > 0 && microtime( true ) < $deadline && $claimed_count < Indexnow_Client::batch_size() ) {
543                $rows = self::rows( min( self::PAGE_SIZE, $budget ), $cursor );
544                if ( ! $rows ) {
545                    $cursor   = '';
546                    $complete = true;
547                    break;
548                }
549                foreach ( $rows as $row ) {
550                    --$budget;
551                    $previous_cursor = $cursor;
552                    $cursor          = $row['option_name'];
553                    $item            = json_decode( $row['option_value'], true );
554                    if ( ! is_array( $item ) || ( $item['created'] ?? 0 ) < time() - 2 * DAY_IN_SECONDS ) {
555                        $expired += self::compare_and_swap( $row, null ) ? 1 : 0;
556                        continue;
557                    }
558                    if ( ( $item['scope'] ?? '' ) !== Indexnow_Client::scope() || ( isset( $item['url'] ) && ! Indexnow_Client::in_scope( $item['url'] ) ) ) {
559                        self::compare_and_swap( $row, null );
560                        continue;
561                    }
562                    $earliest_due = min( $earliest_due, $item['due'] );
563                    if ( $item['due'] > time() ) {
564                        continue;
565                    }
566                    $resolved = self::resolve( $item );
567                    if ( ( $item['generation'] ?? '0' ) !== $generation || ! $resolved ) {
568                        self::compare_and_swap( $row, null );
569                        continue;
570                    }
571                    $bytes = self::notification_bytes( $row['option_value'], $item, $resolved );
572                    if ( $claimed_bytes + $bytes > self::BATCH_BYTES ) {
573                        $cursor = $previous_cursor;
574                        break 2;
575                    }
576                    $claimed_bytes += $bytes;
577                    $claimed[]      = $row;
578                    ++$claimed_count;
579                    if ( count( $claimed ) >= Indexnow_Client::batch_size() ) {
580                        break;
581                    }
582                }
583            }
584            update_option( self::CURSOR_OPTION, $cursor, false );
585            if ( $claimed ) {
586                global $wpdb;
587                $names        = array_column( $claimed, 'option_name' );
588                $placeholders = implode( ', ', array_fill( 0, count( $names ), '%s' ) );
589                // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Only placeholders are interpolated; names are bound below.
590                $fresh    = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name IN ($placeholders)", $names ), ARRAY_A );
591                $versions = array_column( is_array( $fresh ) ? $fresh : array(), 'option_value', 'option_name' );
592                $valid    = array();
593                $bytes    = 0;
594                foreach ( $claimed as $row ) {
595                    $item = json_decode( $row['option_value'], true );
596                    if ( ( $versions[ $row['option_name'] ] ?? null ) === $row['option_value'] && ( $item['generation'] ?? '0' ) === $generation ) {
597                        $url = self::resolve( $item );
598                        if ( $url ) {
599                            $size = self::notification_bytes( $row['option_value'], $item, $url );
600                            if ( $bytes + $size > self::BATCH_BYTES ) {
601                                break;
602                            }
603                            $bytes              += $size;
604                            $row['resolved_url'] = $url;
605                            $valid[]             = $row;
606                        }
607                    }
608                }
609                $claimed = $valid;
610            }
611            if ( $claimed && Indexnow_Client::enabled() && self::row( self::WORKER_LOCK ) === $lock && self::generation() === $generation ) {
612                $urls          = array_values(
613                    array_unique(
614                        array_map(
615                            static function ( $row ) {
616                                return $row['resolved_url'];
617                            },
618                            $claimed
619                        )
620                    )
621                );
622                $enqueue_error = self::row( 'jetpack_seo_indexnow_enqueue_error' );
623                $result        = Indexnow_Client::submit( $urls );
624                if ( self::generation() !== $generation || ! Indexnow_Client::enabled() ) {
625                    return;
626                }
627                $exhausted = 0;
628                $retrying  = 0;
629                $dropped   = 0;
630                if ( $enqueue_error && in_array( $result['state'], array( 'accepted', 'verification_pending' ), true ) ) {
631                    self::delete_rows( array( $enqueue_error ), $generation );
632                    self::invalidate_summary_cache( array( 'jetpack_seo_indexnow_enqueue_error' ) );
633                }
634                if ( 'http_429' === $result['state'] ) {
635                    self::store_status_option( self::COOLDOWN_OPTION, time() + max( 600, $result['retry_after'] ?? 0 ), $generation );
636                }
637                foreach ( $claimed as $row ) {
638                    $item = (array) json_decode( $row['option_value'], true );
639                    if ( $result['retry'] && $item['attempt'] < 5 ) {
640                        ++$item['attempt'];
641                        $item['due']  = time() + max( $result['retry_after'] ?? 0, min( 43200, 60 * pow( 4, $item['attempt'] ) ), 'http_429' === $result['state'] ? 600 : 0 );
642                        $earliest_due = min( $earliest_due, $item['due'] );
643                        $retrying    += self::compare_and_swap( $row, $item, $generation ) ? 1 : 0;
644                    } elseif ( self::compare_and_swap( $row, null ) ) {
645                            $exhausted += $result['retry'] ? 1 : 0;
646                            $dropped   += ! $result['retry'] && ! in_array( $result['state'], array( 'accepted', 'verification_pending' ), true ) ? 1 : 0;
647                    }
648                }
649                self::record_status(
650                    array(
651                        'state'     => $result['state'],
652                        'time'      => time(),
653                        'count'     => count( $urls ),
654                        'expired'   => $expired,
655                        'exhausted' => $exhausted,
656                        'retrying'  => $retrying,
657                        'dropped'   => $dropped,
658                    ),
659                    $generation
660                );
661            } elseif ( $expired ) {
662                self::record_status(
663                    array(
664                        'state'   => 'expired',
665                        'time'    => time(),
666                        'count'   => 0,
667                        'expired' => $expired,
668                    ),
669                    $generation
670                );
671            }
672            if ( self::rows( 1 ) ) {
673                $delay = $started_at_head && $complete && ! $claimed && PHP_INT_MAX !== $earliest_due ? max( 30, $earliest_due - time() ) : 30;
674                self::schedule( $delay );
675            }
676        } finally {
677            self::compare_and_swap( $lock, null );
678        }
679    }
680
681    /**
682     * Include a resolved URL in the worker's retained-payload budget.
683     *
684     * @param string $value Encoded notification.
685     * @param array  $item Decoded notification.
686     * @param string $url Resolved public URL.
687     * @return int
688     */
689    private static function notification_bytes( $value, $item, $url ) {
690        return strlen( $value ) + ( isset( $item['url'] ) ? 0 : strlen( wp_json_encode( $url, JSON_UNESCAPED_SLASHES ) ) + 7 );
691    }
692
693    /**
694     * Resolve a currently eligible discovery or removal URL.
695     *
696     * @param array $item Stored notification.
697     * @return string
698     */
699    private static function resolve( $item ) {
700        $post_id = (int) ( $item['post'] ?? 0 );
701        if ( $post_id < 1 ) {
702            return '';
703        }
704        $post = get_post( $post_id );
705        if ( ! empty( $item['deleted'] ) ) {
706            return Indexnow_Events::removal_allowed( $post ) ? ( $item['url'] ?? '' ) : '';
707        }
708        if ( ! Indexnow_Events::eligible( $post, $item['url'] ?? '' ) ) {
709            return '';
710        }
711        $url = $item['url'] ?? get_permalink( $post );
712        return Indexnow_Client::in_scope( $url ) ? $url : '';
713    }
714}