check_automation_rate_limit('process_jobs', AutomationConstants::RATE_LIMIT_PROCESS_JOBS); if (is_wp_error($rl)) { return $rl; } $lock_key = 'aipt_browser_job_processing'; $lock_token = $this->acquireBrowserLock($lock_key); if ($lock_token === null) { return new WP_REST_Response([ 'success' => true, 'needs_manual_process' => true, 'processed_job_id' => null, 'processed_job_name' => null, 'execution_result' => null, 'active_jobs' => [], 'active_jobs_count' => 0, 'message' => __('Another process is running', 'ai-product-tools'), ], 200); } try { global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table check, table name is safe prefixed string if (!$wpdb->get_var("SHOW TABLES LIKE '{$jobs_table}'")) { return new WP_REST_Response([ 'success' => false, 'message' => __('Automation jobs table not found', 'ai-product-tools'), 'needs_manual_process' => false, ], 500); } if (SpendLimit::isReached()) { return new WP_REST_Response([ 'success' => true, 'needs_manual_process' => false, 'processed_job_id' => null, 'processed_job_name' => null, 'execution_result' => null, 'execution_error' => null, 'active_jobs' => [], 'active_jobs_count' => 0, 'spend_limit_reached' => true, ], 200); } $active_jobs = $this->getBrowserRunnableJobs($jobs_table); if (null === $active_jobs) { return $this->browserJobsQueryFailedResponse(); } $processed_job_id = null; $processed_job_name = null; $execution_result = null; $execution_error = null; if (!empty($active_jobs)) { $job_to_process = $active_jobs[0]; $processed_job_id = (int) $job_to_process->id; $processed_job_name = $job_to_process->name; try { $execution_result = $this->job_executor->executeJob($processed_job_id); } catch (\Exception $e) { $this->logger->error($processed_job_id, 'Browser-based execution failed', [ 'error' => $e->getMessage() ]); $execution_result = false; $execution_error = __('Job execution failed. Please check the logs for details.', 'ai-product-tools'); } } $remaining_jobs = $this->getBrowserRunnableJobs($jobs_table); if (null === $remaining_jobs) { return $this->browserJobsQueryFailedResponse(); } $needs_manual_process = !empty($remaining_jobs); $jobs_summary = array_map(function($job) { return [ 'id' => (int) $job->id, 'name' => $job->name, 'status' => $job->status, 'progress' => (int) $job->progress, 'total_products' => (int) $job->total_products, 'processed_products' => (int) $job->processed_products, 'failed_products' => (int) $job->failed_products, ]; }, $remaining_jobs); return new WP_REST_Response([ 'success' => true, 'needs_manual_process' => $needs_manual_process, 'processed_job_id' => $processed_job_id, 'processed_job_name' => $processed_job_name, 'execution_result' => $execution_result, 'execution_error' => $execution_error, 'active_jobs' => $jobs_summary, 'active_jobs_count' => count($remaining_jobs), ], 200); } catch (\Exception $e) { Logger::error('automation', 'Browser-based job processing failed', ['exception' => get_class($e), 'error' => $e->getMessage()]); return new WP_REST_Response([ 'success' => false, 'message' => __('The jobs could not be processed. Please check the logs for details.', 'ai-product-tools'), 'needs_manual_process' => false, ], 500); } finally { $this->releaseBrowserLock($lock_key, $lock_token); } } /** * The endpoint's error answer for a failed runnable-jobs query, shaped like * its other failures so the browser stops polling instead of reading * "no job left". * * @return WP_REST_Response */ private function browserJobsQueryFailedResponse(): WP_REST_Response { return new WP_REST_Response([ 'success' => false, 'message' => __('The jobs could not be read. Please check the logs for details.', 'ai-product-tools'), 'needs_manual_process' => false, ], 500); } /** * Active jobs the browser runner has work for, least recently updated first. * * A recurring job that only waits for its next cycle is left out: running * it does nothing and leaves its row untouched, so it would be picked on * every call (starving the other jobs) and keep the browser polling. A * one-time job whose scheduled run time has not come yet is left out too. * * @param string $jobs_table Prefixed jobs table name. * @return array|null Job rows (empty when none is left); null when the query failed, which must not read as "no job left". */ private function getBrowserRunnableJobs(string $jobs_table): ?array { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Direct query needed, table name is safe prefixed string $rows = $wpdb->get_results( "SELECT id, status, name, progress, total_products, processed_products, failed_products, schedule_config, next_run, started_at FROM {$jobs_table} WHERE status IN ('running', 'ready', 'preparing') ORDER BY updated_at ASC" ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if (!is_array($rows) || '' !== (string) $wpdb->last_error) { Logger::error('automation', 'Browser runner could not read the runnable jobs', ['error' => (string) $wpdb->last_error]); return null; } $runnable = []; foreach ($rows as $row) { $job = new AutomationJob((array) $row); if (!JobScheduler::isWaitingForRecurringCycle($job, $this->job_manager) && !JobScheduler::isWaitingForScheduledRun($job)) { $runnable[] = $row; } } return $runnable; } /** * Acquire the browser processing lock. * * An OptionLock row: one INSERT IGNORE decides the winner and an expired * lock is taken over with one conditional UPDATE, so exactly one concurrent * caller wins. add_option() is not atomic enough: two requests can both pass * its existence check. * * @param string $lock_key Option name to use as the lock. * @param int $ttl_seconds Lock TTL in seconds (default 120). * @return string|null Owner token on success; null if the lock is held. */ private function acquireBrowserLock(string $lock_key, int $ttl_seconds = 120): ?string { return OptionLock::acquire($lock_key, $ttl_seconds); } /** * Release a browser processing lock only when its row still holds the token. * * The delete carries the token in its condition, so a late-arriving process * never removes the lock of the request that took over its expired one. * * @param string $lock_key Option name used as the lock. * @param string $token Token returned by acquireBrowserLock(). * @return bool True on successful release; false if the token no longer matches or the key is missing. */ private function releaseBrowserLock(string $lock_key, string $token): bool { return OptionLock::release($lock_key, $token); } }