job_manager->getJobCount([ 'status' => array_values(array_diff(AutomationJob::VALID_STATUSES, ['completed', 'failed'])), ]); if ($max_jobs > 0 && $active_jobs >= $max_jobs) { return PlanDenial::error( 'multipleJobs', PlanDenial::PLAN_BUSINESS, sprintf( /* translators: %d: number of automation jobs the current plan allows. */ _n( 'Your plan includes %d automation job. Business plan adds more jobs.', 'Your plan includes %d automation jobs. Business plan adds more jobs.', $max_jobs, 'ai-product-tools' ), $max_jobs ), 'aipt_job_limit_reached', [ 'applied_free_defaults' => true, 'max_jobs' => $max_jobs, ] ); } return null; } /** * Acquire the job-count-cap lock. Callers must hold this for the whole * count-check + insert critical section and release it in a `finally` * block regardless of outcome — the count-then-create race this closes * (two concurrent requests both reading $active_jobs below the cap * before either inserts) only disappears if the actual `createJob()` * call happens while the lock is held, not just the count read. * * The lock is an OptionLock row: one INSERT IGNORE decides the winner and an * expired row (a holder that crashed) is taken over with one conditional * UPDATE. add_option() is not atomic enough: two requests can both pass its * existence check and both report success. * * @return bool True when the lock was acquired. */ private function acquireJobCountLock(): bool { $this->job_count_lock_handle = OptionLock::acquire(self::JOB_COUNT_LOCK_KEY, self::JOB_COUNT_LOCK_TTL); return null !== $this->job_count_lock_handle; } /** * Whether this request still holds the job-count-cap lock. The lock has a * TTL, so a slow count could outlive it and let another request take it * over: check right before the insert and refuse instead of inserting * beside a successor. * * @return bool */ private function jobCountLockStillHeld(): bool { return null !== $this->job_count_lock_handle && OptionLock::holds(self::JOB_COUNT_LOCK_KEY, $this->job_count_lock_handle); } /** * The retryable refusal for a request that did not get, or no longer holds, * the job-count-cap lock. * * @return WP_Error */ private function jobCountLockBusyError(): WP_Error { return new WP_Error( 'aipt_job_limit_check_busy', __('Another job operation is in progress. Please try again.', 'ai-product-tools'), ['status' => 409] ); } /** * Release the job-count-cap lock when this request still owns it; a lock a * successor took over after expiry is left alone. * * @return void */ private function releaseJobCountLock(): void { if (null !== $this->job_count_lock_handle) { OptionLock::release(self::JOB_COUNT_LOCK_KEY, $this->job_count_lock_handle); $this->job_count_lock_handle = null; } } }