job_manager = $job_manager; $this->logger = $logger; } /** * Schedule a job for execution * * @param AutomationJob $job Job to schedule * @return bool Success status * @throws \Exception On scheduling failure */ public function scheduleJob(AutomationJob $job) { try { $next_run = $this->calculateNextRun($job); if (!$next_run && in_array(strtolower((string) ($job->schedule_config['type'] ?? '')), ['daily', 'weekly', 'monthly'], true)) { $this->logger->warning($job->id, 'Recurring cadence is not schedulable on this plan; job will not re-arm', [ 'schedule_type' => $job->schedule_config['type'] ?? 'unknown', ]); } if ($next_run) { $job->next_run = $next_run; if (!$this->job_manager->setJobNextRun((int) $job->id, $next_run)) { throw new \Exception('Failed to save the next run'); } $timestamp = strtotime($next_run); JobRunHook::clear((int) $job->id); $scheduled = JobRunHook::schedule((int) $job->id, (int) $timestamp, true); if ($scheduled === false || is_wp_error($scheduled)) { $error_detail = is_wp_error($scheduled) ? $scheduled->get_error_message() : 'unknown'; throw new \Exception('Failed to schedule WordPress cron event: ' . $error_detail); } $this->logger->info($job->id, 'Job scheduled for execution', [ 'next_run' => $next_run, 'schedule_type' => $job->schedule_config['type'] ?? 'unknown' ]); if (false !== $timestamp && $timestamp <= time()) { self::spawnDueCron(); } return true; } return false; } catch (\Exception $e) { $this->logger->error($job->id, 'Failed to schedule job', [ 'error' => $e->getMessage() ]); throw $e; } } /** * Ask WordPress to run due cron events now instead of on the next page hit. * * Skipped when WP-Cron is disabled in favour of a system cron, which owns * the schedule then. spawn_cron() only runs events that are already due and * takes its own 60 second lock, so calling it is cheap and safe. * * @return void */ public static function spawnDueCron(): void { if (!\defined('DISABLE_WP_CRON') || !\DISABLE_WP_CRON) { if (\function_exists('spawn_cron')) { \spawn_cron(); } } } /** * Whether a recurring job's next cycle is due. * * For a recurring job next_run is the start of the next cycle that has not * started yet: JobExecutor moves it to the following cycle when a cycle * starts. It is UTC, like the recurring schedule math and the execution * event timestamp. * * @param AutomationJob $job Job. * @return bool */ public static function isRecurringCycleDue(AutomationJob $job) { if (empty($job->next_run) || !JobEntitlementGuard::isRecurring($job->schedule_config)) { return false; } $next_ts = strtotime((string) $job->next_run); return false !== $next_ts && $next_ts <= time(); } /** * Whether a recurring job only waits for its next cycle. * * Its cycle is not due and it has nothing to drain: it has not started its * first cycle yet (that cycle rebuilds whatever pool was built at * creation, so draining it early would generate those products twice), or * no pool row is pending. Waking such a job does nothing, so the executor, * the browser runner and the job list do not treat it as work. * * @param AutomationJob $job Job. * @param AutomationJobManager $job_manager Job manager, to count pending pool rows. * @return bool */ public static function isWaitingForRecurringCycle(AutomationJob $job, AutomationJobManager $job_manager) { if (!in_array($job->status, ['ready', 'completed'], true) || !JobEntitlementGuard::isRecurring($job->schedule_config) || self::isRecurringCycleDue($job)) { return false; } return 'completed' === $job->status || empty($job->started_at) || 0 === $job_manager->countOpenJobProducts((int) $job->id); } /** * Whether a one-time job still waits for its scheduled run time. * * The cron poller only runs a ready job once next_run (stored in UTC) has * passed; the browser runner has to honor the same schedule. * * @param AutomationJob $job Job. * @return bool */ public static function isWaitingForScheduledRun(AutomationJob $job) { if ('ready' !== $job->status || empty($job->next_run) || JobEntitlementGuard::isRecurring($job->schedule_config)) { return false; } $next_ts = strtotime((string) $job->next_run . ' UTC'); return false !== $next_ts && $next_ts > time(); } /** * Re-arm a recurring job after a run completed. * * Without recurring entitlement the job is not re-armed, its pending cycle * event is cleared and the stored job says why: a definitive denial leaves * it completed, an unverifiable license pauses it so resuming can re-arm * it. An entitled daily/weekly/monthly job is re-armed by the Premium * build (`aipt_automation_rearm_recurring_job`): it returns to 'ready' * with an execution event for its next cycle. * * @param int $job_id Job ID. * @return bool True when the job was re-armed. */ public function rearmRecurringJob($job_id) { $job_id = (int) $job_id; $job = $this->job_manager->getJob($job_id); if (!$job || 'completed' !== $job->status || !JobEntitlementGuard::isRecurring($job->schedule_config)) { return false; } $block = JobEntitlementGuard::recurringBlock(JobEntitlementGuard::CONTEXT_REARM); if (null !== $block) { $this->logger->warning($job_id, 'Recurring job was not re-armed', [ 'reason' => $block['reason'], 'feature' => $block['feature'], ]); $this->job_manager->updateJobStatus( $job_id, PlanDenial::isVerificationUnavailable($block['reason']) ? 'paused' : 'completed', $block['message'] ); JobRunHook::clear((int) $job_id); return false; } /** * Re-arm a completed recurring job the plan can run for its next cycle. * * The Premium RecurringCycleService is the sole registrant; without it * a recurring job is never re-armed. * * @since 2.8.0 * * @param bool $rearmed Whether the job was re-armed. Default false. * @param AutomationJob $job The completed job. * @param AutomationJobManager $job_manager Job manager. * @param JobLoggerInterface $logger Job logger. */ return (bool) apply_filters('aipt_automation_rearm_recurring_job', false, $job, $this->job_manager, $this->logger); } /** * Unschedule a job * * @param int $job_id Job ID to unschedule * @return bool Success status * @throws \Exception On unscheduling failure */ public function unscheduleJob($job_id) { try { JobRunHook::clear((int) $job_id); $this->logger->info($job_id, 'Job unscheduled'); return true; } catch (\Exception $e) { $this->logger->error($job_id, 'Failed to unschedule job', [ 'error' => $e->getMessage() ]); throw $e; } } /** * Reschedule a job with new configuration * * @param AutomationJob $job Job to reschedule * @return bool Success status * @throws \Exception On rescheduling failure */ public function rescheduleJob(AutomationJob $job) { $this->unscheduleJob($job->id); return $this->scheduleJob($job); } /** * Process pending jobs * * @return int Number of jobs processed */ public function processPendingJobs() { $processed_count = 0; try { $this->buildPoolsForPreparingJobs(AutomationConstants::MAX_PREPARING_JOBS_TO_BUILD, AutomationConstants::MAX_POOL_BUILD_CHUNKS); $running_jobs = $this->getRunningJobsCount(); if ($running_jobs >= AutomationConstants::MAX_CONCURRENT_JOBS) { return 0; } $available_slots = AutomationConstants::MAX_CONCURRENT_JOBS - $running_jobs; $jobs = $this->getJobsReadyForExecution($available_slots); foreach ($jobs as $job) { try { if (JobEntitlementGuard::isRecurring($job->schedule_config) && !empty($job->next_run) && !self::isRecurringCycleDue($job)) { continue; } $hook = JobRunHook::HOOK; $existing_schedule = JobRunHook::next_run((int) $job->id); if ( false !== $existing_schedule ) { $this->logger->info($job->id, 'Job already scheduled - skipping duplicate enqueue', [ 'hook' => $hook, 'existing_run_at' => gmdate('Y-m-d H:i:s', (int) $existing_schedule), ]); $processed_count++; continue; } $scheduled = JobRunHook::schedule((int) $job->id, time() + AutomationConstants::IMMEDIATE_EXECUTION_DELAY, true); if ($scheduled === false || is_wp_error($scheduled)) { $error_detail = is_wp_error($scheduled) ? $scheduled->get_error_message() : 'unknown'; $this->logger->error($job->id, 'Failed to queue job for immediate execution', [ 'hook' => $hook, 'wp_error' => $error_detail, ]); Logger::error('automation', 'Job could not be scheduled', ['job_id' => (int) $job->id, 'hook' => $hook, 'error' => $error_detail]); } else { $this->logger->info($job->id, 'Job queued for immediate execution', [ 'hook' => $hook, 'scheduled_time' => gmdate('Y-m-d H:i:s', time() + AutomationConstants::IMMEDIATE_EXECUTION_DELAY) ]); } $processed_count++; } catch (\Exception $e) { $this->logger->error($job->id, 'Failed to queue job for execution', [ 'error' => $e->getMessage() ]); } } } catch (\Exception $e) { Logger::error('automation', 'Job processing run failed', ['error' => $e->getMessage()]); } return $processed_count; } /** * Monitor running jobs for timeouts and issues * * @return int Number of jobs monitored */ public function monitorRunningJobs() { $monitored_count = 0; try { $reclaimed = $this->releaseStaleClaimsOfUnlockedJobs(); if ($reclaimed > 0) { Logger::warn('automation', 'Stale queue claims released', ['count' => (int) $reclaimed]); } } catch (\Throwable $t) { Logger::error('automation', 'Stale queue claim release failed', ['error' => $t->getMessage()]); } try { $running_jobs = $this->job_manager->getJobs(['status' => 'running']); foreach ($running_jobs as $job) { $monitored_count++; if ($this->isJobTimedOut($job)) { $this->handleJobTimeout($job->id); continue; } $this->updateJobProgressIfNeeded($job); $snapshot = $this->getJobProductSnapshot((int) $job->id); $this->ensureJobExecutionScheduled($job, $snapshot); } } catch (\Exception $e) { Logger::error('automation', 'Job monitor run failed', ['error' => $e->getMessage()]); } return $monitored_count; } /** * Calculate next run time for a job * * @param AutomationJob $job Job to calculate next run for * @return string|null Next run datetime or null if one-time job */ public function calculateNextRun(AutomationJob $job) { $schedule_config = $job->schedule_config; if (empty($schedule_config['type'])) { return null; } $base_time = time(); if ($schedule_config['type'] === 'once') { if (isset($schedule_config['runDate'])) { $runDate = trim((string) $schedule_config['runDate']); if (strpos($runDate, 'T') !== false) { $runDate = str_replace('T', ' ', $runDate); if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $runDate)) { $runDate .= ':00'; } } try { $parsed = (new \DateTimeImmutable($runDate, wp_timezone()))->getTimestamp(); } catch (\Exception $e) { return gmdate('Y-m-d H:i:s', $base_time + 60); } if ($parsed <= 0) { return gmdate('Y-m-d H:i:s', $base_time + 60); } return gmdate('Y-m-d H:i:s', $parsed); } return gmdate('Y-m-d H:i:s', $base_time + 60); } return apply_filters('aipt_calculate_next_run', null, $job); } /** * Check if job should run now * * @param AutomationJob $job Job to check * @return bool Whether job should run */ public function shouldJobRun(AutomationJob $job) { if ($job->status !== 'ready') { return false; } if (empty($job->next_run)) { return false; } return strtotime($job->next_run) <= time(); } /** * Get jobs ready for execution * * @param int $limit Maximum number of jobs to return * @return array Jobs ready for execution */ public function getJobsReadyForExecution($limit = 10) { global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$jobs_table} WHERE status = 'ready' AND (next_run IS NULL OR next_run <= %s) ORDER BY created_at ASC LIMIT %d", JobTime::now(), $limit ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $jobs = []; foreach ($results as $result) { $jobs[] = new AutomationJob($result); } return $jobs; } /** * Build pools for jobs in 'preparing' status. * * @param int $max_jobs Max number of preparing jobs to advance * @param int $max_chunks Max chunks per job to build in this tick */ private function buildPoolsForPreparingJobs($max_jobs = AutomationConstants::MAX_PREPARING_JOBS_TO_BUILD, $max_chunks = AutomationConstants::MAX_POOL_BUILD_CHUNKS) { try { $preparing_jobs = $this->job_manager->getJobs(['status' => 'preparing'], $max_jobs, 0, 'created_at', 'ASC'); if (empty($preparing_jobs)) { return; } global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; $job_products_table = $wpdb->prefix . 'aipt_job_products'; foreach ($preparing_jobs as $job) { try { $pool_builder = new \AIPT\Api\AutomationJobs\PoolBuilder(); $pool_options = AutomationJob::getPoolBuildOptions( (string) $job->tool_type, is_array($job->settings) ? $job->settings : [] ); $result = $pool_builder->buildPool( (int)$job->id, $job->product_filter ?? [], AutomationConstants::POOL_BUILD_CHUNK_SIZE, $max_chunks, $pool_options['skip_processed'], $pool_options['targeted_types'] ); if (!empty($result['blocked'])) { if (!$this->job_manager->pauseForEntitlement((int) $job->id, (string) $result['blocked']['message'], true, ['preparing'])) { $this->logger->info($job->id, 'Pool build stopped: the job changed meanwhile, its status was left as it is'); continue; } $this->logger->warning($job->id, 'Pool build paused: saved product filter cannot be honored', [ 'reason' => $result['blocked']['reason'], 'feature' => $result['blocked']['feature'], 'filters' => $result['blocked']['keys'], ]); continue; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $current_total = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$job_products_table} WHERE job_id = %d", $job->id) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $target_total = isset($result['total']) ? (int)$result['total'] : $current_total; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table update $wpdb->update( $jobs_table, [ 'total_products' => max($current_total, $target_total), 'updated_at' => JobTime::now(), ], ['id' => $job->id], ['%d','%s'], ['%d'] ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ($current_total >= $target_total) { if ($current_total === 0) { if (AutomationJobManager::TRANSITION_APPLIED === $this->job_manager->transitionJobStatus((int) $job->id, 'completed', ['preparing'])) { $this->logger->info($job->id, 'Job completed immediately (no matching products)'); $this->rearmRecurringJob((int) $job->id); } } elseif (AutomationJobManager::TRANSITION_APPLIED === $this->job_manager->transitionJobStatus((int) $job->id, 'ready', ['preparing'])) { $this->logger->info($job->id, 'Job pool prepared and marked as ready', [ 'total_products' => $current_total, ]); } } else { $this->logger->info($job->id, 'Pool building in progress', [ 'built_so_far' => $current_total, 'target_total' => $target_total, ]); } } catch (\Exception $e) { $this->logger->error($job->id, 'Pool building error', ['error' => $e->getMessage()]); } } } catch (\Exception $e) { Logger::error('automation', 'Pool building run failed', ['error' => $e->getMessage()]); } } /** * Give a running job that had no tick and no finished product for * JOB_TIMEOUT a new tick. The job is never failed or paused for it: the * usual cause is a WP-Cron that did not run. Nothing is done while a tick * holds the job's lock, and its claimed rows are left to the next tick, * which releases them under the lock. * * @param int $job_id Job ID. * @return bool Whether a tick is running or one is now due. */ public function handleJobTimeout($job_id) { $job_id = (int) $job_id; if ($this->hasLiveLock($job_id)) { return true; } $job = $this->job_manager->getJob($job_id); if (!$job || 'running' !== (string) $job->status) { return false; } $snapshot = $this->getJobProductSnapshot($job_id); if (!SpendLimit::isReached() && $this->shouldLogSnapshot($job_id, 'stalled', $snapshot, AutomationConstants::JOB_TIMEOUT)) { $this->logger->warning($job_id, 'No tick ran and no product finished for a while; a new tick was scheduled', array_merge($snapshot, [ 'timeout_seconds' => AutomationConstants::JOB_TIMEOUT, ])); } return $this->ensureJobExecutionScheduled($job, $snapshot, true); } /** * Get count of running jobs * * @return int Number of running jobs */ private function getRunningJobsCount() { return $this->job_manager->getJobCount(['status' => 'running']); } /** * Check if job is timed out * * @param AutomationJob $job Job to check * @return bool Whether job is timed out */ private function isJobTimedOut(AutomationJob $job) { $lastActivity = $this->getLastActivityTimestamp($job); if ($lastActivity === null) { return false; } return (time() - $lastActivity) > AutomationConstants::JOB_TIMEOUT; } /** * Update job progress if needed (throttled via last_progress_logged_at) * * @param AutomationJob $job Job to update */ private function updateJobProgressIfNeeded(AutomationJob $job) { global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; $started_ts = JobTime::toTimestamp($job->started_at); if (false === $started_ts) { return; } $now_ts = time(); $elapsed_time = max(0, $now_ts - $started_ts); $logThrottleKey = 'aipt_job_monitor_log_' . (int) $job->id; $lastLoggedTs = null; if (function_exists('get_transient')) { $cached = get_transient($logThrottleKey); if (is_numeric($cached)) { $lastLoggedTs = (int) $cached; } } $should_log = false; if ($lastLoggedTs === null) { $should_log = true; } elseif (($now_ts - $lastLoggedTs) >= AutomationConstants::LOG_THROTTLE_CADENCE_SECONDS) { $should_log = true; } if ($should_log) { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $last_progress = $wpdb->get_var( $wpdb->prepare("SELECT last_progress_logged_at FROM {$jobs_table} WHERE id = %d", $job->id) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $snapshot = $this->getJobProductSnapshot((int) $job->id); $lastActivity = $this->getLastActivityTimestamp($job); $sinceLastProgress = null; if (!empty($last_progress)) { $last_ts = JobTime::toTimestamp($last_progress); if (false !== $last_ts) { $sinceLastProgress = max(0, $now_ts - $last_ts); } } else { $sinceLastProgress = max(0, $now_ts - $started_ts); } $logContext = array_merge([ 'elapsed_time' => $elapsed_time, 'progress' => $job->progress, 'seconds_since_last_progress' => $sinceLastProgress, 'last_activity_at' => $lastActivity ? \wp_date('c', $lastActivity) : null, ], $snapshot); if ($this->shouldLogSnapshot((int) $job->id, 'job_still_running', $logContext, AutomationConstants::SNAPSHOT_LOG_TTL)) { $this->logger->info($job->id, 'Job still running', $logContext); } if (function_exists('set_transient')) { set_transient($logThrottleKey, $now_ts, AutomationConstants::LOG_THROTTLE_CADENCE_SECONDS); } } } /** * Snapshot queue state for diagnostics/logging. * * @param int $job_id * @return array */ private function getJobProductSnapshot(int $job_id): array { global $wpdb; $table = $wpdb->prefix . 'aipt_job_products'; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $row = $wpdb->get_row( $wpdb->prepare( "SELECT SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending, SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) AS processing, SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed, SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed, MIN(CASE WHEN status = 'processing' THEN processing_started_at END) AS oldest_processing_started_at FROM {$table} WHERE job_id = %d", $job_id ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $snapshot = [ 'pending' => 0, 'processing' => 0, 'completed' => 0, 'failed' => 0, ]; if (is_array($row)) { $snapshot['pending'] = (int) ($row['pending'] ?? 0); $snapshot['processing'] = (int) ($row['processing'] ?? 0); $snapshot['completed'] = (int) ($row['completed'] ?? 0); $snapshot['failed'] = (int) ($row['failed'] ?? 0); $snapshot['total_rows'] = array_sum($snapshot); if (!empty($row['oldest_processing_started_at'])) { $ts = JobTime::toTimestamp($row['oldest_processing_started_at']); if ($ts !== false) { $snapshot['oldest_processing_started_at'] = UtcTimestamp::fromStored($row['oldest_processing_started_at'], false); $snapshot['oldest_processing_age_sec'] = max(0, time() - $ts); } } } else { $snapshot['total_rows'] = 0; } return $snapshot; } /** * Prevent duplicate log noise by caching snapshot hashes. */ private function shouldLogSnapshot(int $job_id, string $slug, array $context, int $ttl = AutomationConstants::SNAPSHOT_LOG_TTL): bool { if (!function_exists('get_transient') || !function_exists('set_transient')) { return true; } try { ksort($context); } catch (\Throwable $t) { } $hash = md5(wp_json_encode($context)); $key = 'aipt_joblog_' . $slug . '_' . $job_id; $stored = get_transient($key); if ($stored === $hash) { return false; } set_transient($key, $hash, $ttl); return true; } /** * Ensure there is an upcoming execution event for a running job. * * Acts as a safety net when WP-Cron misses/loses the scheduled single event, * avoiding "stuck" jobs that never schedule the next tick. * * @param AutomationJob $job * @param array $snapshot * @param bool $stalled The job had no tick for JOB_TIMEOUT: a tick is due even * with no product left, so the executor can complete it. * @return bool Whether a tick is running or due. */ private function ensureJobExecutionScheduled(AutomationJob $job, array $snapshot, bool $stalled = false): bool { if (!function_exists('wp_next_scheduled') || !function_exists('wp_schedule_single_event')) { return false; } $remaining = (int) ($snapshot['pending'] ?? 0) + (int) ($snapshot['processing'] ?? 0); if ($remaining <= 0 && !$stalled) { return false; } $job_id = (int) $job->id; if ($this->hasLiveLock($job_id)) { return true; } $now = time(); $next = JobRunHook::next_run($job_id); $reason = null; if ($next === false) { $reason = 'missing_event'; } elseif ($next <= ($now - self::EXECUTION_EVENT_GRACE)) { $reason = 'event_overdue'; } if ($reason === null) { return true; } if ($next !== false) { JobRunHook::unschedule($job_id, (int) $next); } $scheduled_time = $now + AutomationConstants::rescheduleDelay(); $scheduled = JobRunHook::schedule($job_id, $scheduled_time, true); $schedule_failed = ($scheduled === false) || is_wp_error($scheduled); $wp_error_msg = is_wp_error($scheduled) ? $scheduled->get_error_message() : null; $logContext = array_merge($snapshot, [ 'reason' => $reason, 'previous_event_at' => $next ? gmdate('c', (int) $next) : null, 'rescheduled_for' => gmdate('c', $scheduled_time), 'schedule_result' => $schedule_failed ? 'failed' : 'scheduled', 'wp_error' => $wp_error_msg, 'remaining_items' => $remaining, ]); if ($schedule_failed) { $this->logger->error($job_id, 'Job monitor failed to reschedule execution event', $logContext); } else { $this->logger->warning($job_id, 'Job monitor rescheduled missing execution event', $logContext); } return !$schedule_failed; } /** * Return the claims older than STALE_CLAIM_MINUTES to the queue, for each * job whose lock no tick holds. One product's provider work can outlast * those minutes (an image alt product makes one call per image, with no * cap on its images), and the tick working on it renews the job lock * before each provider attempt: releasing its claim would let the next * tick claim the product again and pay for it a second time. * * @return int Rows returned to the queue. */ private function releaseStaleClaimsOfUnlockedJobs(): int { global $wpdb; $table = $wpdb->prefix . 'aipt_job_products'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix; no input. $job_ids = $wpdb->get_col("SELECT DISTINCT job_id FROM {$table} WHERE status = 'processing'"); $queue = new ClaimBasedQueue(); $released = 0; foreach (array_map('intval', is_array($job_ids) ? $job_ids : []) as $job_id) { if ($job_id > 0 && !$this->hasLiveLock($job_id)) { $released += $queue->releaseStaleClaims(AutomationConstants::STALE_CLAIM_MINUTES, $job_id); } } return $released; } /** * Whether a tick holds the job's execution lock right now. * * JobExecutor::acquireLock() stores the lock via add_option() as JSON * {token, expires}, NOT a transient, so reading it with get_transient() * always returned false, leaving this guard dead and letting the monitor * reschedule an execution event on top of a live worker. Read the same * option and honor the expiry: an expired lock means the previous worker * died, so it must NOT be treated as held. * * @param int $job_id Job ID. * @return bool */ private function hasLiveLock(int $job_id): bool { $lockKey = 'aipt_job_lock_' . $job_id; $lock_raw = get_option($lockKey); if (!$lock_raw) { return false; } $lock_data = is_string($lock_raw) ? json_decode($lock_raw, true) : $lock_raw; return is_array($lock_data) && isset($lock_data['expires']) && time() <= (int) $lock_data['expires']; } /** * Determine the most recent activity timestamp for a running job. * * @param AutomationJob $job * @return int|null */ private function getLastActivityTimestamp(AutomationJob $job): ?int { $candidates = []; $started = JobTime::toTimestamp($job->started_at); if (false !== $started) { $candidates[] = $started; } if (!empty($job->updated_at)) { $updated = JobTime::toTimestamp($job->updated_at); if (false !== $updated) { $candidates[] = $updated; } } global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $last_progress = $wpdb->get_var( $wpdb->prepare( "SELECT last_progress_logged_at FROM {$jobs_table} WHERE id = %d", (int) $job->id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if (!empty($last_progress)) { $progress_ts = JobTime::toTimestamp($last_progress); if (false !== $progress_ts) { $candidates[] = $progress_ts; } } if (empty($candidates)) { return null; } return max($candidates); } /** * Setup cron schedules * * Called during plugin initialization */ public static function setupCronSchedules() { if (!wp_next_scheduled('aipt_process_automation_jobs')) { $scheduled = wp_schedule_event(time() + 60, 'aipt_five_minutes', 'aipt_process_automation_jobs', [], true); if ($scheduled === false || is_wp_error($scheduled)) { $detail = is_wp_error($scheduled) ? $scheduled->get_error_message() : 'unknown'; Logger::error('automation', 'Main job processor could not be scheduled', ['hook' => 'aipt_process_automation_jobs', 'error' => $detail]); } } } /** * Clear cron schedules * * Called during plugin deactivation */ public static function clearCronSchedules() { wp_clear_scheduled_hook('aipt_process_automation_jobs'); global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix $job_ids = $wpdb->get_col("SELECT id FROM {$jobs_table}"); foreach ($job_ids as $job_id) { JobRunHook::clear_legacy((int) $job_id); } } }