*/ private static array $handlers = array(); /** * Boots the cron and loopback endpoints. */ public static function init(): void { add_action( self::CRON_HOOK, array( __CLASS__, 'process' ), 10, 1 ); add_action( 'wp_ajax_ai_seo_queue_tick', array( __CLASS__, 'handle_loopback' ) ); add_action( 'wp_ajax_nopriv_ai_seo_queue_tick', array( __CLASS__, 'handle_loopback' ) ); } /** * Registers a worker. * * @param string $slug Queue slug. * @param callable $handler Receives ( int $id, array $meta ) and returns true|WP_Error. */ public static function register( string $slug, callable $handler ): void { self::$handlers[ $slug ] = $handler; } public static function registered(): array { return array_keys( self::$handlers ); } private static function state_key( string $slug ): string { return 'ai_seo_queue_' . $slug; } private static function pending_key( string $slug ): string { return 'ai_seo_queue_pending_' . $slug; } /** * Default, empty state. */ public static function empty_state(): array { return array( 'status' => 'idle', 'total' => 0, 'processed' => 0, 'failed' => 0, 'skipped' => 0, 'errors' => array(), 'recent' => array(), 'current' => 0, 'started' => 0, 'last_run' => 0, 'label' => '', 'meta' => array(), ); } /** * Current state of a queue. */ public static function status( string $slug ): array { $state = get_option( self::state_key( $slug ), array() ); $state = wp_parse_args( is_array( $state ) ? $state : array(), self::empty_state() ); $pending = get_option( self::pending_key( $slug ), array() ); $state['remaining'] = is_array( $pending ) ? count( $pending ) : 0; // A run that has not advanced in ten minutes is almost certainly wedged // (cron disabled, fatal in a handler); surface that instead of spinning. if ( 'running' === $state['status'] && $state['last_run'] && ( time() - $state['last_run'] ) > 600 ) { $state['status'] = 'stalled'; } $state['percent'] = $state['total'] > 0 ? min( 100, (int) round( ( $state['processed'] + $state['failed'] + $state['skipped'] ) / $state['total'] * 100 ) ) : 0; return $state; } /** * Queues a set of object IDs. * * @param string $slug Queue slug. * @param int[] $ids Object IDs to process. * @param array $meta Arbitrary data handed to the handler on every item. * @param string $label Human readable description of the run. */ public static function start( string $slug, array $ids, array $meta = array(), string $label = '' ): array { self::cancel_scheduled( $slug ); $ids = array_values( array_unique( array_map( 'intval', $ids ) ) ); $state = array_merge( self::empty_state(), array( 'status' => $ids ? 'running' : 'complete', 'total' => count( $ids ), 'started' => time(), 'last_run' => time(), 'label' => $label, 'meta' => $meta, ) ); update_option( self::state_key( $slug ), $state, false ); update_option( self::pending_key( $slug ), $ids, false ); if ( $ids ) { self::schedule( $slug, 0 ); } else { delete_option( self::pending_key( $slug ) ); } return self::status( $slug ); } /** * Stops a run and clears its backlog. */ public static function stop( string $slug ): array { self::cancel_scheduled( $slug ); delete_option( self::pending_key( $slug ) ); $state = get_option( self::state_key( $slug ), array() ); $state = wp_parse_args( is_array( $state ) ? $state : array(), self::empty_state() ); if ( in_array( $state['status'], array( 'running', 'stalled' ), true ) ) { $state['status'] = 'stopped'; } update_option( self::state_key( $slug ), $state, false ); return self::status( $slug ); } /** * Clears a finished run so the UI returns to its resting state. */ public static function reset( string $slug ): void { self::cancel_scheduled( $slug ); delete_option( self::state_key( $slug ) ); delete_option( self::pending_key( $slug ) ); } /** * Processes one batch and reschedules itself. */ public static function process( string $slug ): void { if ( ! isset( self::$handlers[ $slug ] ) ) { return; } $lock = 'ai_seo_queue_lock_' . $slug; // Cron and the loopback can both land at once; only one may run. if ( get_transient( $lock ) ) { return; } set_transient( $lock, 1, 5 * MINUTE_IN_SECONDS ); try { self::run_batch( $slug ); } finally { delete_transient( $lock ); } } private static function run_batch( string $slug ): void { $state = get_option( self::state_key( $slug ), array() ); $state = wp_parse_args( is_array( $state ) ? $state : array(), self::empty_state() ); $pending = get_option( self::pending_key( $slug ), array() ); if ( 'running' !== $state['status'] || ! is_array( $pending ) || ! $pending ) { self::finish( $slug, $state, empty( $pending ) ? 'complete' : $state['status'] ); return; } $budget = AI_SEO_Tools_Client::check_budget(); if ( is_wp_error( $budget ) ) { $state['errors'][] = array( 'id' => 0, 'message' => $budget->get_error_message() ); self::finish( $slug, $state, 'paused' ); return; } $options = get_option( AI_SEO_Tools_Client::OPTION, array() ); $batch_size = max( 1, min( 20, (int) ( $options['queue_batch_size'] ?? 3 ) ) ); $delay = max( 0, (int) ( $options['bulk_processing_delay'] ?? 2 ) ); $deadline = time() + (int) apply_filters( 'ai_seo_tools_queue_max_runtime', 20 ); $handler = self::$handlers[ $slug ]; $processed = 0; while ( $pending && $processed < $batch_size && time() < $deadline ) { $id = (int) array_shift( $pending ); $state['current'] = $id; update_option( self::state_key( $slug ), $state, false ); update_option( self::pending_key( $slug ), $pending, false ); $result = call_user_func( $handler, $id, $state['meta'] ); if ( is_wp_error( $result ) ) { $data = $result->get_error_data(); $status = is_array( $data ) ? (int) ( $data['status'] ?? 0 ) : 0; // Rate limits and outages are worth waiting out; put the item back. if ( in_array( $status, array( 429, 500, 502, 503, 504 ), true ) || 'network_error' === $result->get_error_code() ) { array_unshift( $pending, $id ); update_option( self::pending_key( $slug ), $pending, false ); $state['errors'] = self::push_error( $state['errors'], $id, $result->get_error_message() ); $state['current'] = 0; $state['last_run'] = time(); update_option( self::state_key( $slug ), $state, false ); $wait = is_array( $data ) && ! empty( $data['retry_after'] ) ? (int) $data['retry_after'] : 60; self::schedule( $slug, max( 15, min( 300, $wait ) ) ); return; } // Budget exhaustion mid-run: stop cleanly rather than burning the queue. if ( 'budget_exceeded' === $result->get_error_code() ) { array_unshift( $pending, $id ); update_option( self::pending_key( $slug ), $pending, false ); $state['errors'] = self::push_error( $state['errors'], $id, $result->get_error_message() ); self::finish( $slug, $state, 'paused' ); return; } $state['failed']++; $state['errors'] = self::push_error( $state['errors'], $id, $result->get_error_message() ); } elseif ( 'skipped' === $result ) { $state['skipped']++; } else { $state['processed']++; array_unshift( $state['recent'], $id ); $state['recent'] = array_slice( $state['recent'], 0, 8 ); } $processed++; $state['current'] = 0; $state['last_run'] = time(); update_option( self::state_key( $slug ), $state, false ); if ( $pending && $delay && $processed < $batch_size && time() < $deadline ) { sleep( min( 5, $delay ) ); } } if ( ! $pending ) { self::finish( $slug, $state, 'complete' ); return; } update_option( self::state_key( $slug ), $state, false ); self::schedule( $slug, $delay ); } private static function push_error( array $errors, int $id, string $message ): array { $errors[] = array( 'id' => $id, 'message' => $message, 'time' => time(), ); return array_slice( $errors, -25 ); } private static function finish( string $slug, array $state, string $status ): void { $state['status'] = $status; $state['current'] = 0; $state['last_run'] = time(); update_option( self::state_key( $slug ), $state, false ); delete_option( self::pending_key( $slug ) ); self::cancel_scheduled( $slug ); do_action( 'ai_seo_tools_queue_finished', $slug, $state ); } /* --------------------------------------------------------------------- */ /* Scheduling */ /* --------------------------------------------------------------------- */ private static function schedule( string $slug, int $delay ): void { $delay = max( 0, $delay ); if ( function_exists( 'as_schedule_single_action' ) ) { as_schedule_single_action( time() + $delay, self::CRON_HOOK, array( $slug ), 'ai-seo-tools' ); } else { wp_schedule_single_event( time() + $delay, self::CRON_HOOK, array( $slug ) ); } // Cron only fires when somebody visits, so nudge every batch ourselves and // let the scheduled event stand as the fallback. The run lock keeps the two // from processing the same batch twice. self::kick( $slug, $delay ); } private static function cancel_scheduled( string $slug ): void { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( self::CRON_HOOK, array( $slug ), 'ai-seo-tools' ); } wp_clear_scheduled_hook( self::CRON_HOOK, array( $slug ) ); delete_transient( 'ai_seo_queue_lock_' . $slug ); } /** * Shared secret for the loopback endpoint. */ private static function token(): string { $token = get_option( 'ai_seo_tools_queue_token' ); if ( ! $token ) { $token = wp_generate_password( 40, false, false ); update_option( 'ai_seo_tools_queue_token', $token, false ); } return $token; } /** * Fires a non-blocking request back at the site to run the next batch. */ private static function kick( string $slug, int $delay = 0 ): void { if ( ! apply_filters( 'ai_seo_tools_queue_loopback', true, $slug ) ) { return; } wp_remote_post( admin_url( 'admin-ajax.php' ), array( 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), 'body' => array( 'action' => 'ai_seo_queue_tick', 'queue' => $slug, 'token' => self::token(), 'delay' => max( 0, min( 30, $delay ) ), ), ) ); } /** * Loopback endpoint. Authenticated by a rotating shared secret, not a nonce, * because the request carries no user session. */ public static function handle_loopback(): void { $token = isset( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : ''; $slug = isset( $_POST['queue'] ) ? sanitize_key( wp_unslash( $_POST['queue'] ) ) : ''; if ( ! $token || ! hash_equals( self::token(), $token ) ) { wp_die( '', '', array( 'response' => 403 ) ); } if ( ! isset( self::$handlers[ $slug ] ) ) { wp_die( '', '', array( 'response' => 400 ) ); } // Let the caller go; the batch can take a while. if ( function_exists( 'fastcgi_finish_request' ) ) { fastcgi_finish_request(); } ignore_user_abort( true ); // The pause between batches is honoured here rather than by the scheduler, // because the response has already been sent. $delay = isset( $_POST['delay'] ) ? absint( wp_unslash( $_POST['delay'] ) ) : 0; if ( $delay > 0 ) { sleep( min( 30, $delay ) ); } self::process( $slug ); wp_die( '', '', array( 'response' => 200 ) ); } /** * Clears every queue (deactivation / uninstall). */ public static function purge_all(): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $names = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'ai_seo_queue_%'" ); foreach ( (array) $names as $name ) { delete_option( $name ); } // Queue ticks are scheduled with the queue slug as an argument, so only // the hook-wide call reaches them. wp_unschedule_hook( self::CRON_HOOK ); if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( self::CRON_HOOK, null, 'ai-seo-tools' ); } } } }