From a3ac7abba63f2dc78877041fdca3b42160471bc8 Mon Sep 17 00:00:00 2001 From: Aleksei Tikhomirov Date: Wed, 11 Nov 2026 16:42:08 +0300 Subject: [PATCH 1/2] fix: atomic database queue, global worker lock (1.3.0) - Database driver keeps jobs in {prefix}queue_jobs; pop() claims a row with a conditional UPDATE, so parallel workers can neither lose nor repeat jobs (the wp_options array was rewritten without locking and read through the persistent object cache). - 1.2.x jobs stored in wp_options are migrated on first use. - One DB-row worker lock for all queues ({prefix}queue_locks), used by wp_queue_process, REST process, wp queue work and the daemon. - wp queue work --all --max-time for system cron. - Daemon mode removes stale wp_queue_process events; dispatch() does not spawn_cron() when DISABLE_WP_CRON is set. - Payloads base64-encoded (PostgreSQL text rejects NUL bytes). - Tests on a real SQL engine (SQLite): race between two workers, stale reclaim, legacy migration, 4 parallel worker processes x 120 jobs. --- readme.txt | 14 +- src/Admin/AdminPage.php | 15 +- src/Admin/RestApi.php | 81 ++---- src/CLI/QueueCommand.php | 90 +++++-- src/Contracts/InspectableQueue.php | 29 +++ src/Jobs/PendingDispatch.php | 20 +- src/Queue/DatabaseQueue.php | 270 ++++++++++++-------- src/QueueManager.php | 35 ++- src/Support/Lock.php | 123 +++++++++ src/Support/Schema.php | 160 ++++++++++++ src/WPQueue.php | 117 ++++++--- src/Worker.php | 8 + tests/Fixtures/ConcurrencyJob.php | 27 ++ tests/Pest.php | 3 + tests/Support/SqliteWpdb.php | 187 ++++++++++++++ tests/Support/concurrent-worker.php | 30 +++ tests/Unit/DatabaseQueueConcurrencyTest.php | 189 ++++++++++++++ tests/Unit/QueueManagerTest.php | 12 +- tests/bootstrap.php | 4 + wp-queue.php | 4 +- 20 files changed, 1139 insertions(+), 279 deletions(-) create mode 100644 src/Contracts/InspectableQueue.php create mode 100644 src/Support/Lock.php create mode 100644 src/Support/Schema.php create mode 100644 tests/Fixtures/ConcurrencyJob.php create mode 100644 tests/Support/SqliteWpdb.php create mode 100644 tests/Support/concurrent-worker.php create mode 100644 tests/Unit/DatabaseQueueConcurrencyTest.php diff --git a/readme.txt b/readme.txt index a5f9575..2c29833 100644 --- a/readme.txt +++ b/readme.txt @@ -5,7 +5,7 @@ Tags: queue, cron, background-processing, jobs, scheduler Requires at least: 6.2 Tested up to: 7.0 Requires PHP: 8.3 -Stable tag: 1.2.1 +Stable tag: 1.3.0 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -147,6 +147,15 @@ Yes, WP Queue works with WordPress multisite installations. == Changelog == += 1.3.0 = +* Database driver stores jobs in its own table (`{prefix}queue_jobs`) instead of one wp_options array: a job is claimed with an atomic conditional UPDATE, so parallel workers no longer lose or repeat jobs (also with a persistent object cache such as Redis) +* Jobs left in wp_options by 1.2.x are migrated automatically +* One worker lock for all queues (`{prefix}queue_locks`), shared by WP-Cron, loopback, REST "process" and `wp queue work` +* `wp queue work --all --max-time=` for system cron / external workers +* Daemon mode no longer schedules WP-Cron events and removes stale `wp_queue_process` events +* dispatch() no longer calls spawn_cron() when DISABLE_WP_CRON is set (it executed every due WP-Cron hook) +* Payloads are base64-encoded (PostgreSQL text columns reject the NUL bytes of serialized objects) + = 1.2.1 = * Added ABSPATH guards to all PHP files * Fixed WordPress Plugin Check errors: escaping, i18n placeholders, input sanitization @@ -181,6 +190,9 @@ Yes, WP Queue works with WordPress multisite installations. == Upgrade Notice == += 1.3.0 = +Database driver moves jobs to its own table with atomic claiming (no lost or duplicated jobs under parallel workers). Pending 1.2.x jobs are migrated automatically. + = 1.2.1 = Maintenance release with WordPress Plugin Check fixes and plugin rename to Queue Manager. diff --git a/src/Admin/AdminPage.php b/src/Admin/AdminPage.php index 61bbd52..3a4d172 100644 --- a/src/Admin/AdminPage.php +++ b/src/Admin/AdminPage.php @@ -1217,18 +1217,11 @@ protected function renderRecentLogs(int $limit): void */ protected function getQueuesStatus(): array { - global $wpdb; - $queues = ['default' => ['size' => 0, 'status' => 'idle']]; + $manager = WPQueue::manager(); - // Find all queue options - $results = $wpdb->get_col( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'wp_queue_jobs_%'", - ); - - foreach ($results as $optionName) { - $queueName = str_replace('wp_queue_jobs_', '', $optionName); - $jobs = get_site_option($optionName, []); + foreach ($manager->discoverQueues() as $queueName) { + $jobs = $manager->queuedJobs($queueName); $status = 'idle'; if (WPQueue::isPaused($queueName)) { @@ -1277,7 +1270,7 @@ protected function getRunningCount(): int */ protected function getQueueJobs(string $queueName): array { - $rawJobs = get_site_option('wp_queue_jobs_'.$queueName, []); + $rawJobs = WPQueue::manager()->queuedJobs($queueName); $jobs = []; foreach ($rawJobs as $id => $data) { diff --git a/src/Admin/RestApi.php b/src/Admin/RestApi.php index 4267c54..9905cca 100644 --- a/src/Admin/RestApi.php +++ b/src/Admin/RestApi.php @@ -171,19 +171,11 @@ public function checkPermission(): bool public function getQueues(): WP_REST_Response { - global $wpdb; - $queues = []; - $results = $wpdb->get_col( - $wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", - 'wp_queue_jobs_%', - ), - ); + $manager = WPQueue::manager(); - foreach ($results as $optionName) { - $queueName = str_replace('wp_queue_jobs_', '', $optionName); - $jobs = get_site_option($optionName, []); + foreach ($manager->discoverQueues() as $queueName) { + $jobs = $manager->queuedJobs($queueName); $queues[$queueName] = [ 'size' => count($jobs), @@ -205,18 +197,15 @@ public function getQueues(): WP_REST_Response public function getQueue(WP_REST_Request $request): WP_REST_Response|WP_Error { - $queueName = $request->get_param('queue'); - $optionName = 'wp_queue_jobs_'.$queueName; - - // Проверяем существование очереди - $jobs = get_site_option($optionName, null); + $queueName = (string) $request->get_param('queue'); + $manager = WPQueue::manager(); // Очередь существует если есть задачи или это очередь default - if ($jobs === null && $queueName !== 'default') { + if ($queueName !== 'default' && ! in_array($queueName, $manager->discoverQueues(), true)) { return new WP_Error('queue_not_found', 'Queue not found', ['status' => 404]); } - $jobs = $jobs ?? []; + $jobs = $manager->queuedJobs($queueName); return new WP_REST_Response([ 'name' => $queueName, @@ -228,8 +217,8 @@ public function getQueue(WP_REST_Request $request): WP_REST_Response|WP_Error public function getQueueJobs(WP_REST_Request $request): WP_REST_Response { - $queueName = $request->get_param('queue'); - $jobs = get_site_option('wp_queue_jobs_'.$queueName, []); + $queueName = (string) $request->get_param('queue'); + $jobs = WPQueue::manager()->queuedJobs($queueName); $result = []; foreach ($jobs as $index => $job) { @@ -259,37 +248,23 @@ public function processQueue(WP_REST_Request $request): WP_REST_Response $queueName = $request->get_param('queue'); $maxJobs = (int) ($request->get_param('max_jobs') ?? 10); - $worker = WPQueue::worker(); - $worker->setMaxJobs($maxJobs); - - $processed = 0; - while ($processed < $maxJobs && $worker->runNextJob($queueName)) { - $processed++; - } + $processed = WPQueue::processQueues((string) $queueName, max(1, $maxJobs), 50); return new WP_REST_Response([ - 'success' => true, - 'processed' => $processed, + 'success' => $processed !== null, + 'processed' => (int) $processed, + 'message' => $processed === null ? 'Another worker is already processing the queue' : '', ]); } public function getStats(): WP_REST_Response { - global $wpdb; - - $queues = []; $totalJobs = 0; + $manager = WPQueue::manager(); + $results = $manager->discoverQueues(); - $results = $wpdb->get_col( - $wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", - 'wp_queue_jobs_%', - ), - ); - - foreach ($results as $optionName) { - $jobs = get_site_option($optionName, []); - $totalJobs += count($jobs); + foreach ($results as $queueName) { + $totalJobs += count($manager->queuedJobs($queueName)); } // Получаем статистику из логов @@ -352,7 +327,7 @@ public function getJob(WP_REST_Request $request): WP_REST_Response|WP_Error $jobId = urldecode($request->get_param('job')); $queueName = $request->get_param('queue') ?? 'default'; - $jobs = get_site_option('wp_queue_jobs_'.$queueName, []); + $jobs = WPQueue::manager()->queuedJobs((string) $queueName); if (! isset($jobs[$jobId])) { return new WP_Error('job_not_found', 'Job not found', ['status' => 404]); @@ -392,19 +367,13 @@ public function deleteJob(WP_REST_Request $request): WP_REST_Response|WP_Error $jobId = urldecode($request->get_param('job')); $queueName = $request->get_param('queue') ?? 'default'; - $jobs = get_site_option('wp_queue_jobs_'.$queueName, []); + $jobs = WPQueue::manager()->queuedJobs((string) $queueName); if (! isset($jobs[$jobId])) { return new WP_Error('job_not_found', 'Job not found', ['status' => 404]); } - unset($jobs[$jobId]); - - if (empty($jobs)) { - delete_site_option('wp_queue_jobs_'.$queueName); - } else { - update_site_option('wp_queue_jobs_'.$queueName, $jobs); - } + WPQueue::manager()->connection()->delete($jobId); return new WP_REST_Response(['success' => true, 'message' => 'Job deleted']); } @@ -439,16 +408,8 @@ public function clearLogs(WP_REST_Request $request): WP_REST_Response public function clearAllQueues(): WP_REST_Response { - global $wpdb; - - // Находим все опции с джобами - $results = $wpdb->get_col( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'wp_queue_jobs_%'", - ); - $cleared = 0; - foreach ($results as $optionName) { - $queueName = str_replace('wp_queue_jobs_', '', $optionName); + foreach (WPQueue::manager()->discoverQueues() as $queueName) { WPQueue::clear($queueName); $cleared++; } diff --git a/src/CLI/QueueCommand.php b/src/CLI/QueueCommand.php index 0500383..98a3f2e 100644 --- a/src/CLI/QueueCommand.php +++ b/src/CLI/QueueCommand.php @@ -7,6 +7,7 @@ use WP_CLI; use WP_CLI\Utils; use WPQueue\Admin\SystemStatus; +use WPQueue\Support\Lock; use WPQueue\WPQueue; if (! defined('ABSPATH')) { @@ -54,19 +55,11 @@ class QueueCommand */ public function status(array $args, array $assocArgs): void { - global $wpdb; - $queues = []; - $results = $wpdb->get_col( - $wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", - 'wp_queue_jobs_%', - ), - ); + $manager = WPQueue::manager(); - foreach ($results as $optionName) { - $queueName = str_replace('wp_queue_jobs_', '', $optionName); - $jobs = get_site_option($optionName, []); + foreach ($manager->discoverQueues() as $queueName) { + $jobs = $manager->queuedJobs($queueName); $queues[] = [ 'queue' => $queueName, @@ -110,6 +103,15 @@ public function status(array $args, array $assocArgs): void * default: 256 * --- * + * [--all] + * : Process every queue that has jobs (the queue argument is processed first). + * + * [--max-time=] + * : Stop after this many seconds (0 = no limit). + * --- + * default: 0 + * --- + * * [--daemon] * : Run as a daemon worker that continuously polls the queue. * In daemon mode loopback requests and WP-Cron scheduling are skipped @@ -120,6 +122,7 @@ public function status(array $args, array $assocArgs): void * wp queue work * wp queue work emails --limit=50 * wp queue work imports --memory=512 + * wp queue work --all --limit=50 --max-time=50 * wp queue work --daemon * wp queue work imports --daemon --memory=512 * @@ -135,28 +138,46 @@ public function work(array $args, array $assocArgs): void return; } - $limit = (int) ($assocArgs['limit'] ?? 100); + $limit = max(1, (int) ($assocArgs['limit'] ?? 100)); + $maxTime = max(0, (int) ($assocArgs['max-time'] ?? 0)); // Get default memory limit from WordPress $defaultMemory = $this->getDefaultMemoryLimit(); $memory = (int) ($assocArgs['memory'] ?? $defaultMemory); - WP_CLI::log("Processing jobs from queue: {$queue} (memory limit: {$memory}MB, WordPress default: {$defaultMemory}MB)"); + $lockTtl = ($maxTime > 0 ? $maxTime : 3600) + 60; + $token = Lock::acquire(Lock::WORKER, $lockTtl); - $worker = WPQueue::worker(); - $worker->setMemoryLimit($memory); + if ($token === null) { + WP_CLI::log('Another worker is processing the queues, skipping.'); + + return; + } + + try { + WP_CLI::log("Processing jobs from queue: {$queue} (memory limit: {$memory}MB, WordPress default: {$defaultMemory}MB)"); - $processed = 0; + $worker = WPQueue::worker(); + $worker->setMemoryLimit($memory); + $worker->setMaxJobs($limit); + $worker->setMaxTime($maxTime); + $worker->resetJobsProcessed(); - while ($processed < $limit) { - if (! $worker->runNextJob($queue)) { - break; + $queues = [$queue]; + if (! empty($assocArgs['all'])) { + $queues = array_values(array_unique(array_merge($queues, WPQueue::manager()->discoverQueues()))); } - $processed++; - WP_CLI::log("Processed job #{$processed}"); - } - WP_CLI::success("Processed {$processed} jobs from queue: {$queue}"); + foreach ($queues as $queueName) { + while (! $worker->shouldStop() && $worker->runNextJob($queueName)) { + WP_CLI::log("Processed job #{$worker->getJobsProcessed()} ({$queueName})"); + } + } + + WP_CLI::success("Processed {$worker->getJobsProcessed()} jobs from: ".implode(', ', $queues)); + } finally { + Lock::release(Lock::WORKER, $token); + } } /** @@ -174,9 +195,30 @@ protected function runDaemon(string $queue, array $assocArgs): void WP_CLI::log("Starting daemon worker for queue: {$queue} (memory limit: {$memory}MB)"); + $token = Lock::acquire(Lock::WORKER, 120); + + if ($token === null) { + WP_CLI::error('Another worker is processing the queues.'); + } + $worker = WPQueue::worker(); $worker->setMemoryLimit($memory); - $worker->daemon($queue); + + try { + while (! $worker->shouldStop()) { + if (! Lock::refresh(Lock::WORKER, $token, 120)) { + WP_CLI::warning('Worker lock lost, stopping.'); + + break; + } + + if (! $worker->runNextJob($queue)) { + sleep(3); + } + } + } finally { + Lock::release(Lock::WORKER, $token); + } } /** diff --git a/src/Contracts/InspectableQueue.php b/src/Contracts/InspectableQueue.php new file mode 100644 index 0000000..b05c119 --- /dev/null +++ b/src/Contracts/InspectableQueue.php @@ -0,0 +1,29 @@ + + */ + public function jobs(string $queue): array; +} diff --git a/src/Jobs/PendingDispatch.php b/src/Jobs/PendingDispatch.php index ad6f828..410b938 100644 --- a/src/Jobs/PendingDispatch.php +++ b/src/Jobs/PendingDispatch.php @@ -7,6 +7,7 @@ use WPQueue\Contracts\JobInterface; use WPQueue\Loopback\LoopbackDispatcher; use WPQueue\QueueManager; +use WPQueue\Runtime\RuntimeMode; if (! defined('ABSPATH')) { exit; @@ -87,6 +88,21 @@ protected static function scheduleImmediateProcessing(string $queue): void return; } + // Daemon mode: an external worker polls the queue, WP-Cron is not used. + if (! RuntimeMode::useCron()) { + return; + } + + if (wp_next_scheduled('wp_queue_process', [$queue]) === false) { + wp_schedule_single_event(time(), 'wp_queue_process', [$queue]); + } + + // With DISABLE_WP_CRON the site runs cron from the system scheduler: + // spawning wp-cron.php here would execute every due hook, not only ours. + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { + return; + } + if (! self::$spawnRegistered) { self::$spawnRegistered = true; @@ -105,10 +121,6 @@ protected static function scheduleImmediateProcessing(string $queue): void }); } - if (wp_next_scheduled('wp_queue_process', [$queue]) === false) { - wp_schedule_single_event(time(), 'wp_queue_process', [$queue]); - } - self::$spawnQueued = true; } } diff --git a/src/Queue/DatabaseQueue.php b/src/Queue/DatabaseQueue.php index b2a9e44..8619f28 100644 --- a/src/Queue/DatabaseQueue.php +++ b/src/Queue/DatabaseQueue.php @@ -4,23 +4,55 @@ namespace WPQueue\Queue; +use WPQueue\Contracts\InspectableQueue; use WPQueue\Contracts\JobInterface; use WPQueue\Contracts\QueueInterface; +use WPQueue\Support\Schema; if (! defined('ABSPATH')) { exit; } -class DatabaseQueue implements QueueInterface +/** + * Database driver: one row per job in {prefix}queue_jobs. + * + * A job is claimed with a conditional UPDATE (`... WHERE id = ? AND reserved_at IS NULL`), + * which is atomic in every SQL engine, so concurrent workers can neither take the + * same job twice nor lose jobs. The object cache (Redis etc.) is not involved. + */ +class DatabaseQueue implements InspectableQueue, QueueInterface { - protected const PREFIX = 'wp_queue_'; + /** + * Seconds after which a reserved job is considered abandoned (worker crashed). + */ + public const STALE_THRESHOLD = 300; + + /** + * Candidates fetched per pop() attempt. + */ + protected const CLAIM_BATCH = 10; + + protected string $workerId; + + public function __construct() + { + $this->workerId = bin2hex(random_bytes(8)); + } public function push(JobInterface $job): string { - $queue = $job->getQueue(); - $availableAt = time() + $job->getDelay(); + global $wpdb; + + Schema::ensure(); - $this->store($queue, $job, $availableAt); + $wpdb->insert(Schema::jobsTable(), [ + 'job_id' => $job->getId(), + 'queue' => $job->getQueue() ?: 'default', + 'payload' => $this->encode($job), + 'attempts' => $job->getAttempts(), + 'available_at' => time() + $job->getDelay(), + 'created_at' => time(), + ], ['%s', '%s', '%s', '%d', '%d', '%d']); return $job->getId(); } @@ -34,93 +66,109 @@ public function later(int $delay, JobInterface $job): string public function pop(string $queue = 'default'): ?JobInterface { - $jobs = $this->getQueue($queue); + global $wpdb; - if (empty($jobs)) { - return null; - } + Schema::ensure(); + $table = Schema::jobsTable(); $now = time(); - $staleThreshold = 300; - - foreach ($jobs as $id => $data) { - $isStale = $data['reserved_at'] !== null && ($now - $data['reserved_at']) > $staleThreshold; - - if ($data['available_at'] <= $now && ($data['reserved_at'] === null || $isStale)) { - if ($isStale) { - error_log(sprintf( - 'WP Queue: Releasing stale job %s (reserved for %d seconds)', - $id, - $now - $data['reserved_at'], - )); - } - - $jobs[$id]['reserved_at'] = $now; - $this->saveQueue($queue, $jobs); - - try { - $job = unserialize($data['payload']); - if ($job instanceof JobInterface) { - return $job; - } - } catch (\Throwable $e) { - error_log(sprintf( - 'WP Queue: Failed to unserialize job %s: %s', - $id, - $e->getMessage(), - )); - // Release the job back to the queue for retry - $jobs[$id]['reserved_at'] = null; - $this->saveQueue($queue, $jobs); - } + $staleBefore = $now - self::STALE_THRESHOLD; + + $candidates = $wpdb->get_results($wpdb->prepare( + "SELECT id, job_id, payload, reserved_at FROM {$table} WHERE queue = %s AND available_at <= %d AND (reserved_at IS NULL OR reserved_at < %d) ORDER BY available_at ASC, id ASC LIMIT %d", + $queue, + $now, + $staleBefore, + self::CLAIM_BATCH, + ), ARRAY_A); + + foreach ((array) $candidates as $row) { + if (! $this->claim((int) $row['id'], $staleBefore)) { + // Another worker was faster. + continue; + } + + if ($row['reserved_at'] !== null) { + error_log(sprintf('WP Queue: Releasing stale job %s', $row['job_id'])); } + + $job = $this->decode((string) $row['payload']); + + if ($job instanceof JobInterface) { + return $job; + } + + error_log(sprintf('WP Queue: Failed to unserialize job %s, removing it', $row['job_id'])); + $wpdb->delete($table, ['id' => (int) $row['id']], ['%d']); } return null; } - public function delete(string $jobId): bool + /** + * Atomically reserve one row for this worker. + */ + protected function claim(int $rowId, int $staleBefore): bool { - foreach ($this->getAllQueues() as $queue) { - $jobs = $this->getQueue($queue); + global $wpdb; - if (isset($jobs[$jobId])) { - unset($jobs[$jobId]); - $this->saveQueue($queue, $jobs); + $table = Schema::jobsTable(); - return true; - } - } + $updated = $wpdb->query($wpdb->prepare( + "UPDATE {$table} SET reserved_at = %d, reserved_by = %s WHERE id = %d AND (reserved_at IS NULL OR reserved_at < %d)", + time(), + $this->workerId, + $rowId, + $staleBefore, + )); - // Job not found - this is normal if it was already deleted or never existed - return false; + return (int) $updated === 1; + } + + public function delete(string $jobId): bool + { + global $wpdb; + + Schema::ensure(); + + return (bool) $wpdb->delete(Schema::jobsTable(), ['job_id' => $jobId], ['%s']); } public function release(JobInterface $job, int $delay = 0): void { - $queue = $job->getQueue(); - $jobs = $this->getQueue($queue); - - if (isset($jobs[$job->getId()])) { - $jobs[$job->getId()]['reserved_at'] = null; - $jobs[$job->getId()]['available_at'] = time() + $delay; - $jobs[$job->getId()]['payload'] = serialize($job); - $jobs[$job->getId()]['attempts'] = $job->getAttempts(); - $this->saveQueue($queue, $jobs); - } + global $wpdb; + + Schema::ensure(); + + $table = Schema::jobsTable(); + + $wpdb->query($wpdb->prepare( + "UPDATE {$table} SET reserved_at = NULL, reserved_by = NULL, available_at = %d, payload = %s, attempts = %d WHERE job_id = %s", + time() + $delay, + $this->encode($job), + $job->getAttempts(), + $job->getId(), + )); } public function size(string $queue = 'default'): int { - return count($this->getQueue($queue)); + global $wpdb; + + Schema::ensure(); + + $table = Schema::jobsTable(); + + return (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE queue = %s", $queue)); } public function clear(string $queue = 'default'): int { - $count = $this->size($queue); - delete_site_option($this->queueKey($queue)); + global $wpdb; - return $count; + Schema::ensure(); + + return (int) $wpdb->delete(Schema::jobsTable(), ['queue' => $queue], ['%s']); } public function isEmpty(string $queue = 'default'): bool @@ -128,69 +176,67 @@ public function isEmpty(string $queue = 'default'): bool return $this->size($queue) === 0; } - /** - * @return array - */ - protected function getQueue(string $queue): array + public function queues(): array { - // Clear cache to ensure we get fresh data from DB - if (function_exists('wp_cache_delete')) { - wp_cache_delete($this->queueKey($queue), 'site-options'); + global $wpdb; + + if (! isset($wpdb)) { + return []; } - return get_site_option($this->queueKey($queue), []); - } + Schema::ensure(); - /** - * @param array $jobs - */ - protected function saveQueue(string $queue, array $jobs): void - { - if (empty($jobs)) { - delete_site_option($this->queueKey($queue)); - } else { - update_site_option($this->queueKey($queue), $jobs); - } + $table = Schema::jobsTable(); + + return array_values(array_map('strval', (array) $wpdb->get_col("SELECT DISTINCT queue FROM {$table}"))); } - protected function store(string $queue, JobInterface $job, int $availableAt): void + public function jobs(string $queue): array { - $jobs = $this->getQueue($queue); + global $wpdb; - $jobs[$job->getId()] = [ - 'payload' => serialize($job), - 'available_at' => $availableAt, - 'reserved_at' => null, - 'attempts' => $job->getAttempts(), - ]; + Schema::ensure(); + + $table = Schema::jobsTable(); + $rows = $wpdb->get_results($wpdb->prepare( + "SELECT job_id, payload, available_at, reserved_at, attempts FROM {$table} WHERE queue = %s ORDER BY available_at ASC, id ASC", + $queue, + ), ARRAY_A); + + $jobs = []; + foreach ((array) $rows as $row) { + $jobs[(string) $row['job_id']] = [ + 'payload' => (string) base64_decode((string) $row['payload'], true), + 'available_at' => (int) $row['available_at'], + 'reserved_at' => $row['reserved_at'] === null ? null : (int) $row['reserved_at'], + 'attempts' => (int) $row['attempts'], + ]; + } - update_site_option($this->queueKey($queue), $jobs); + return $jobs; } - protected function queueKey(string $queue): string + /** + * Serialized PHP objects contain NUL bytes (private/protected properties), + * which PostgreSQL text columns reject, so payloads are stored base64-encoded. + */ + protected function encode(JobInterface $job): string { - return self::PREFIX.'jobs_'.$queue; + return base64_encode(serialize($job)); } - /** - * @return string[] - */ - protected function getAllQueues(): array + protected function decode(string $payload): mixed { - global $wpdb; + $raw = base64_decode($payload, true); - if (! isset($wpdb)) { - return ['default']; + if ($raw === false) { + return null; } - $prefix = self::PREFIX.'jobs_'; - $results = $wpdb->get_col( - $wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", - $prefix.'%', - ), - ); - - return array_map(fn ($key) => str_replace($prefix, '', $key), $results); + try { + return unserialize($raw); + } catch (\Throwable) { + return null; + } } } diff --git a/src/QueueManager.php b/src/QueueManager.php index 830e622..94cade4 100644 --- a/src/QueueManager.php +++ b/src/QueueManager.php @@ -5,6 +5,7 @@ namespace WPQueue; use InvalidArgumentException; +use WPQueue\Contracts\InspectableQueue; use WPQueue\Contracts\QueueInterface; use WPQueue\Queue\DatabaseQueue; use WPQueue\Queue\MemcachedQueue; @@ -619,32 +620,38 @@ protected function discoverRedisQueues(): array } /** - * Discover queues from database (wp_options). + * Discover queues from the database driver table. * * @return string[] */ protected function discoverDatabaseQueues(): array { - global $wpdb; - - $results = $wpdb->get_col( - $wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", - 'wp_queue_jobs_%', - ), - ); - + $connection = $this->connection('database'); $queues = ['default']; - foreach ($results as $optionName) { - $name = str_replace('wp_queue_jobs_', '', $optionName); - if ($name && ! in_array($name, $queues, true)) { - $queues[] = $name; + + if ($connection instanceof InspectableQueue) { + foreach ($connection->queues() as $name) { + if ($name !== '' && ! in_array($name, $queues, true)) { + $queues[] = $name; + } } } return $queues; } + /** + * Pending jobs of a queue for the admin UI / REST / CLI (empty for drivers that cannot list jobs). + * + * @return array + */ + public function queuedJobs(string $queue): array + { + $connection = $this->connection(); + + return $connection instanceof InspectableQueue ? $connection->jobs($queue) : []; + } + /** * Get known queues from scheduled jobs. * diff --git a/src/Support/Lock.php b/src/Support/Lock.php new file mode 100644 index 0000000..885e54c --- /dev/null +++ b/src/Support/Lock.php @@ -0,0 +1,123 @@ +query($wpdb->prepare( + "UPDATE {$table} SET owner = %s, expires_at = %d WHERE name = %s AND (owner IS NULL OR expires_at < %d)", + $token, + $now + $ttl, + $name, + $now, + )); + + if ((int) $updated === 1) { + return $token; + } + + $exists = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE name = %s", $name)); + + if ($exists > 0) { + return null; + } + + // First use of this lock name: the primary key makes concurrent inserts fail for all but one. + $suppress = $wpdb->suppress_errors(true); + $inserted = $wpdb->insert($table, [ + 'name' => $name, + 'owner' => $token, + 'expires_at' => $now + $ttl, + ], ['%s', '%s', '%d']); + $wpdb->suppress_errors($suppress); + + return $inserted ? $token : null; + } + + /** + * Extend a held lock. Returns false when the lock was lost. + */ + public static function refresh(string $name, string $token, int $ttl): bool + { + global $wpdb; + + $table = Schema::locksTable(); + + $updated = $wpdb->query($wpdb->prepare( + "UPDATE {$table} SET expires_at = %d WHERE name = %s AND owner = %s", + time() + $ttl, + $name, + $token, + )); + + return (int) $updated === 1; + } + + public static function release(string $name, string $token): void + { + global $wpdb; + + $table = Schema::locksTable(); + + $wpdb->query($wpdb->prepare( + "UPDATE {$table} SET owner = NULL, expires_at = 0 WHERE name = %s AND owner = %s", + $name, + $token, + )); + } + + public static function isHeld(string $name): bool + { + global $wpdb; + + if (! isset($wpdb)) { + return false; + } + + Schema::ensure(); + + $table = Schema::locksTable(); + $suppress = $wpdb->suppress_errors(true); + $held = (int) $wpdb->get_var($wpdb->prepare( + "SELECT COUNT(*) FROM {$table} WHERE name = %s AND owner IS NOT NULL AND expires_at >= %d", + $name, + time(), + )); + $wpdb->suppress_errors($suppress); + + return $held > 0; + } + + private static function token(): string + { + return bin2hex(random_bytes(16)); + } +} diff --git a/src/Support/Schema.php b/src/Support/Schema.php new file mode 100644 index 0000000..b8432f6 --- /dev/null +++ b/src/Support/Schema.php @@ -0,0 +1,160 @@ +prefix.'queue_jobs'; + } + + public static function locksTable(): string + { + global $wpdb; + + return $wpdb->prefix.'queue_locks'; + } + + /** + * Create tables once per request when the stored schema version is outdated. + */ + public static function ensure(): void + { + if (self::$ready) { + return; + } + + $version = function_exists('get_option') ? (int) get_option(self::OPTION, 0) : 0; + + if ($version < self::VERSION) { + self::install(); + } + + self::$ready = true; + } + + public static function install(): void + { + global $wpdb; + + if (! isset($wpdb)) { + return; + } + + $jobs = self::jobsTable(); + $locks = self::locksTable(); + $charsetCollate = method_exists($wpdb, 'get_charset_collate') ? $wpdb->get_charset_collate() : ''; + + // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange + $wpdb->query("CREATE TABLE IF NOT EXISTS {$jobs} ( + id bigint(20) unsigned NOT NULL AUTO_INCREMENT, + job_id varchar(64) NOT NULL, + queue varchar(64) NOT NULL, + payload longtext NOT NULL, + attempts int(11) NOT NULL DEFAULT 0, + available_at bigint(20) NOT NULL DEFAULT 0, + reserved_at bigint(20) NULL DEFAULT NULL, + reserved_by varchar(64) NULL DEFAULT NULL, + created_at bigint(20) NOT NULL DEFAULT 0, + PRIMARY KEY (id), + UNIQUE KEY job_id (job_id), + KEY queue_available (queue, available_at) + ) {$charsetCollate};"); + + $wpdb->query("CREATE TABLE IF NOT EXISTS {$locks} ( + name varchar(64) NOT NULL, + owner varchar(64) NULL DEFAULT NULL, + expires_at bigint(20) NOT NULL DEFAULT 0, + PRIMARY KEY (name) + ) {$charsetCollate};"); + // phpcs:enable + + self::migrateLegacyOptions(); + + if (function_exists('update_option')) { + update_option(self::OPTION, self::VERSION, false); + } + + self::$ready = true; + } + + /** + * Move jobs stored by 1.2.x in wp_options (wp_queue_jobs_) into the table. + */ + public static function migrateLegacyOptions(): void + { + global $wpdb; + + if (! function_exists('get_option') || ! function_exists('delete_option')) { + return; + } + + $options = $wpdb->get_col( + $wpdb->prepare( + "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", + 'wp_queue_jobs_%', + ), + ); + + foreach ((array) $options as $optionName) { + $queue = substr((string) $optionName, strlen('wp_queue_jobs_')); + $jobs = get_option($optionName, []); + + if (is_array($jobs)) { + foreach ($jobs as $jobId => $data) { + if (! is_array($data) || ! isset($data['payload'])) { + continue; + } + + $wpdb->insert(self::jobsTable(), [ + 'job_id' => (string) $jobId, + 'queue' => $queue, + 'payload' => base64_encode((string) $data['payload']), + 'attempts' => (int) ($data['attempts'] ?? 0), + 'available_at' => (int) ($data['available_at'] ?? time()), + 'created_at' => time(), + ], ['%s', '%s', '%s', '%d', '%d', '%d']); + } + } + + delete_option($optionName); + } + } + + /** + * Reset the per-request cache (tests). + */ + public static function reset(): void + { + self::$ready = false; + } + + /** + * Treat the schema as installed (tests with a pre-built database). + */ + public static function markReady(): void + { + self::$ready = true; + } +} diff --git a/src/WPQueue.php b/src/WPQueue.php index 7715777..df2c67d 100644 --- a/src/WPQueue.php +++ b/src/WPQueue.php @@ -11,6 +11,8 @@ use WPQueue\Loopback\LoopbackHandler; use WPQueue\Runtime\RuntimeMode; use WPQueue\Storage\LogStorage; +use WPQueue\Support\Lock; +use WPQueue\Support\Schema; if (! defined('ABSPATH')) { exit; @@ -77,50 +79,16 @@ public static function boot(): void // Register cron handler for processing queues add_action('wp_queue_process', static function (string $queue = 'default'): void { - error_log('WP Queue: Processing started for queue: '.$queue); - - if (self::isProcessing($queue)) { - error_log('WP Queue: Processing already running for queue: '.$queue); - - return; - } - - $lockKey = 'wp_queue_lock_'.$queue; - $lockTtl = 120; - - set_site_transient($lockKey, 1, $lockTtl); - - $instance = self::getInstance(); - $instance->worker->setMaxJobs(50); - $instance->worker->setMaxTime(50); - - // Discover all queues from the current driver - $queues = $instance->manager->discoverQueues(); - - // Ensure default queue is always processed - if (! in_array($queue, $queues, true)) { - array_unshift($queues, $queue); - } - - // Process each discovered queue until worker reaches its limits - foreach ($queues as $queueName) { - while (! $instance->worker->shouldStop()) { - if (! $instance->worker->runNextJob($queueName)) { - break; - } - } - } - - try { - error_log('WP Queue: Processing completed. Jobs processed: '.$instance->worker->getJobsProcessed()); - } finally { - delete_site_transient($lockKey); - } + self::processQueues($queue, 50, 50); }); - // Schedule queue processing + // Schedule queue processing (cron / loopback mode). In daemon mode an + // external worker (`wp queue work`) polls the queue, so stale WP-Cron + // events of the plugin are removed instead. add_action('init', static function (): void { if (! RuntimeMode::useCron()) { + self::unscheduleProcessing(); + return; } @@ -182,6 +150,7 @@ public static function install(): void self::createLogsTable(); self::migrateLogsOption(); + Schema::install(); } public static function uninstall(): void @@ -345,7 +314,73 @@ public static function worker(): Worker */ public static function isProcessing(string $queue = 'default'): bool { - return (bool) get_site_transient('wp_queue_lock_'.$queue); + // One worker lock for all queues: a worker drains every queue. + return Lock::isHeld(Lock::WORKER); + } + + /** + * Process all known queues under the global worker lock. + * + * @return int|null Jobs processed, or null when another worker holds the lock. + */ + public static function processQueues(string $queue = 'default', int $maxJobs = 50, int $maxTime = 50): ?int + { + $token = Lock::acquire(Lock::WORKER, $maxTime + 60); + + if ($token === null) { + error_log('WP Queue: Processing already running, skipped for queue: '.$queue); + + return null; + } + + try { + $instance = self::getInstance(); + $instance->worker->setMaxJobs($maxJobs); + $instance->worker->setMaxTime($maxTime); + $instance->worker->resetJobsProcessed(); + + $queues = $instance->manager->discoverQueues(); + + if (! in_array($queue, $queues, true)) { + array_unshift($queues, $queue); + } + + foreach ($queues as $queueName) { + while (! $instance->worker->shouldStop()) { + if (! $instance->worker->runNextJob($queueName)) { + break; + } + } + } + + $processed = $instance->worker->getJobsProcessed(); + + if ($processed > 0) { + error_log('WP Queue: Processing completed. Jobs processed: '.$processed); + } + + return $processed; + } finally { + Lock::release(Lock::WORKER, $token); + } + } + + /** + * Remove every scheduled wp_queue_process event (with or without args). + */ + public static function unscheduleProcessing(): void + { + if (! function_exists('_get_cron_array') || ! function_exists('wp_unschedule_hook')) { + return; + } + + foreach ((array) _get_cron_array() as $hooks) { + if (isset($hooks['wp_queue_process'])) { + wp_unschedule_hook('wp_queue_process'); + + return; + } + } } /** diff --git a/src/Worker.php b/src/Worker.php index 0d79e1a..5221e6a 100644 --- a/src/Worker.php +++ b/src/Worker.php @@ -331,6 +331,14 @@ public function getMemoryLimit(): int return $this->memoryLimit; } + /** + * Reset the processed-jobs counter (the shared worker instance is reused per request). + */ + public function resetJobsProcessed(): void + { + $this->jobsProcessed = 0; + } + public function getJobsProcessed(): int { return $this->jobsProcessed; diff --git a/tests/Fixtures/ConcurrencyJob.php b/tests/Fixtures/ConcurrencyJob.php new file mode 100644 index 0000000..379e622 --- /dev/null +++ b/tests/Fixtures/ConcurrencyJob.php @@ -0,0 +1,27 @@ +onQueue('parallel'); + } + + public function handle(): void + { + // Widen the race window between claiming and deleting. + usleep(random_int(0, 2000)); + } + + public function number(): int + { + return $this->number; + } +} diff --git a/tests/Pest.php b/tests/Pest.php index 276fdca..48006c9 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -11,6 +11,9 @@ uses() ->beforeEach(function (): void { \Brain\Monkey\setUp(); + // Fresh real-SQL database per test (queue table, worker lock). + $GLOBALS['wpdb'] = new \WPQueue\Tests\Support\SqliteWpdb(); + \WPQueue\Support\Schema::markReady(); }) ->afterEach(function (): void { \Brain\Monkey\tearDown(); diff --git a/tests/Support/SqliteWpdb.php b/tests/Support/SqliteWpdb.php new file mode 100644 index 0000000..47bf6ac --- /dev/null +++ b/tests/Support/SqliteWpdb.php @@ -0,0 +1,187 @@ +pdo = new PDO('sqlite:'.$path, null, null, [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_TIMEOUT => 30, + ]); + $this->pdo->exec('PRAGMA busy_timeout = 30000'); + + if ($path !== ':memory:') { + $this->pdo->exec('PRAGMA journal_mode = WAL'); + } + + $this->pdo->exec('CREATE TABLE IF NOT EXISTS wp_queue_jobs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + job_id TEXT NOT NULL UNIQUE, + queue TEXT NOT NULL, + payload TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + available_at INTEGER NOT NULL DEFAULT 0, + reserved_at INTEGER NULL, + reserved_by TEXT NULL, + created_at INTEGER NOT NULL DEFAULT 0 + )'); + $this->pdo->exec('CREATE TABLE IF NOT EXISTS wp_queue_locks ( + name TEXT PRIMARY KEY, + owner TEXT NULL, + expires_at INTEGER NOT NULL DEFAULT 0 + )'); + $this->pdo->exec('CREATE TABLE IF NOT EXISTS wp_options ( + option_name TEXT PRIMARY KEY, + option_value TEXT + )'); + } + + public function get_charset_collate(): string + { + return ''; + } + + public function suppress_errors(bool $suppress = true): bool + { + $previous = $this->suppress; + $this->suppress = $suppress; + + return $previous; + } + + public function prepare(string $query, mixed ...$args): string + { + if (count($args) === 1 && is_array($args[0])) { + $args = $args[0]; + } + + $index = 0; + + return (string) preg_replace_callback('/%([sdif])/', function (array $m) use (&$index, $args): string { + $value = $args[$index++] ?? null; + + return match ($m[1]) { + 'd' => (string) (int) $value, + 'f' => (string) (float) $value, + 'i' => '"'.str_replace('"', '', (string) $value).'"', + default => $this->pdo->quote((string) $value), + }; + }, $query); + } + + public function query(string $sql): int|bool + { + if (preg_match('/^\s*CREATE TABLE/i', $sql)) { + return true; + } + + try { + $this->rows_affected = (int) $this->pdo->exec($sql); + + return $this->rows_affected; + } catch (PDOException $e) { + return $this->fail($e); + } + } + + public function insert(string $table, array $data, array $format = []): int|false + { + $columns = implode(', ', array_keys($data)); + $placeholders = implode(', ', array_fill(0, count($data), '?')); + + try { + $statement = $this->pdo->prepare("INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})"); + $statement->execute(array_values($data)); + $this->insert_id = (int) $this->pdo->lastInsertId(); + + return $this->rows_affected = $statement->rowCount(); + } catch (PDOException $e) { + return $this->fail($e); + } + } + + public function delete(string $table, array $where, array $format = []): int|false + { + $conditions = implode(' AND ', array_map(static fn ($c) => "{$c} = ?", array_keys($where))); + + try { + $statement = $this->pdo->prepare("DELETE FROM {$table} WHERE {$conditions}"); + $statement->execute(array_values($where)); + + return $this->rows_affected = $statement->rowCount(); + } catch (PDOException $e) { + return $this->fail($e); + } + } + + public function get_results(string $query, string $output = 'OBJECT'): array + { + try { + $rows = $this->pdo->query($query)->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + $this->fail($e); + + return []; + } + + return $output === 'ARRAY_A' ? $rows : array_map(static fn ($r) => (object) $r, $rows); + } + + public function get_col(string $query): array + { + try { + return $this->pdo->query($query)->fetchAll(PDO::FETCH_COLUMN); + } catch (PDOException $e) { + $this->fail($e); + + return []; + } + } + + public function get_var(string $query): mixed + { + try { + $value = $this->pdo->query($query)->fetchColumn(); + + return $value === false ? null : $value; + } catch (PDOException $e) { + $this->fail($e); + + return null; + } + } + + private function fail(PDOException $e): false + { + $this->last_error = $e->getMessage(); + + return false; + } +} diff --git a/tests/Support/concurrent-worker.php b/tests/Support/concurrent-worker.php new file mode 100644 index 0000000..387d320 --- /dev/null +++ b/tests/Support/concurrent-worker.php @@ -0,0 +1,30 @@ + + */ +if (PHP_SAPI !== 'cli') { + exit; +} + +define('ABSPATH', sys_get_temp_dir().'/'); +define('ARRAY_A', 'ARRAY_A'); + +require dirname(__DIR__, 2).'/vendor/autoload.php'; + +$GLOBALS['wpdb'] = new WPQueue\Tests\Support\SqliteWpdb($argv[1]); + +WPQueue\Support\Schema::markReady(); + +$queue = new WPQueue\Queue\DatabaseQueue(); + +while (($job = $queue->pop('parallel')) !== null) { + $job->handle(); + echo $job->getId(), "\n"; + $queue->delete($job->getId()); +} diff --git a/tests/Unit/DatabaseQueueConcurrencyTest.php b/tests/Unit/DatabaseQueueConcurrencyTest.php new file mode 100644 index 0000000..554000e --- /dev/null +++ b/tests/Unit/DatabaseQueueConcurrencyTest.php @@ -0,0 +1,189 @@ +competitor !== null) { + $this->competitorJob = $this->competitor->pop('parallel'); + $this->competitor = null; + } + + return parent::claim($rowId, $staleBefore); + } +} + +describe('DatabaseQueue storage', function (): void { + it('pops each job once and removes it on delete', function (): void { + $queue = new DatabaseQueue(); + $job = new ConcurrencyJob(1); + $queue->push($job); + + $popped = $queue->pop('parallel'); + + expect($popped)->toBeInstanceOf(ConcurrencyJob::class) + ->and($popped->getId())->toBe($job->getId()) + ->and($queue->pop('parallel'))->toBeNull() + ->and($queue->size('parallel'))->toBe(1); + + $queue->delete($popped->getId()); + + expect($queue->size('parallel'))->toBe(0); + }); + + it('does not hand the same job to a worker that lost the race', function (): void { + $first = new ConcurrencyJob(1); + $second = new ConcurrencyJob(2); + + $slow = new RacingDatabaseQueue(); + $slow->push($first); + $slow->push($second); + $slow->competitor = new DatabaseQueue(); + + $slowJob = $slow->pop('parallel'); + + expect($slow->competitorJob)->not->toBeNull() + ->and($slowJob)->not->toBeNull() + ->and($slowJob->getId())->not->toBe($slow->competitorJob->getId()) + ->and([$slowJob->getId(), $slow->competitorJob->getId()]) + ->toEqualCanonicalizing([$first->getId(), $second->getId()]); + }); + + it('re-claims a job abandoned by a crashed worker', function (): void { + global $wpdb; + + $queue = new DatabaseQueue(); + $job = new ConcurrencyJob(1); + $queue->push($job); + $queue->pop('parallel'); + + $wpdb->query($wpdb->prepare( + 'UPDATE wp_queue_jobs SET reserved_at = %d WHERE job_id = %s', + time() - DatabaseQueue::STALE_THRESHOLD - 1, + $job->getId(), + )); + + expect($queue->pop('parallel')?->getId())->toBe($job->getId()); + }); + + it('release makes a job available again after the delay', function (): void { + $queue = new DatabaseQueue(); + $queue->push(new ConcurrencyJob(1)); + $job = $queue->pop('parallel'); + + $queue->release($job, 3600); + expect($queue->pop('parallel'))->toBeNull(); + + $queue->release($job, 0); + expect($queue->pop('parallel')?->getId())->toBe($job->getId()); + }); + + it('lists queues and jobs for the admin UI', function (): void { + $queue = new DatabaseQueue(); + $job = new ConcurrencyJob(7); + $queue->push($job); + + $jobs = $queue->jobs('parallel'); + + expect($queue->queues())->toBe(['parallel']) + ->and(array_keys($jobs))->toBe([$job->getId()]) + ->and(unserialize($jobs[$job->getId()]['payload'])->number())->toBe(7); + }); + + it('moves 1.2.x jobs from wp_options into the table', function (): void { + global $wpdb; + + $legacy = new ConcurrencyJob(3); + $stored = [$legacy->getId() => ['payload' => serialize($legacy), 'available_at' => time(), 'reserved_at' => null, 'attempts' => 0]]; + $wpdb->insert('wp_options', ['option_name' => 'wp_queue_jobs_parallel', 'option_value' => 'x']); + + Brain\Monkey\Functions\when('get_option')->alias(fn ($name, $default = false) => $name === 'wp_queue_jobs_parallel' ? $stored : 0); + Brain\Monkey\Functions\when('update_option')->justReturn(true); + Brain\Monkey\Functions\expect('delete_option')->once()->with('wp_queue_jobs_parallel')->andReturn(true); + + Schema::install(); + + expect((new DatabaseQueue())->pop('parallel')?->getId())->toBe($legacy->getId()); + }); + + it('never processes a job twice with parallel worker processes', function (): void { + $file = tempnam(sys_get_temp_dir(), 'wpq'); + $GLOBALS['wpdb'] = new SqliteWpdb($file); + + $queue = new DatabaseQueue(); + $ids = []; + for ($i = 0; $i < 120; $i++) { + $job = new ConcurrencyJob($i); + $queue->push($job); + $ids[] = $job->getId(); + } + + $script = dirname(__DIR__).'/Support/concurrent-worker.php'; + $processes = []; + for ($w = 0; $w < 4; $w++) { + $processes[] = proc_open([PHP_BINARY, $script, $file], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes[$w]); + } + + $handled = []; + foreach ($processes as $w => $process) { + $out = stream_get_contents($pipes[$w][1]); + $err = stream_get_contents($pipes[$w][2]); + proc_close($process); + expect($err)->toBe(''); + $handled = array_merge($handled, array_filter(explode("\n", $out))); + } + + @unlink($file); + @unlink($file.'-wal'); + @unlink($file.'-shm'); + + expect(count($handled))->toBe(120) + ->and(count(array_unique($handled)))->toBe(120) + ->and($handled)->toEqualCanonicalizing($ids); + }); +}); + +describe('Worker lock', function (): void { + it('is exclusive until released', function (): void { + $token = Lock::acquire(Lock::WORKER, 60); + + expect($token)->toBeString() + ->and(Lock::acquire(Lock::WORKER, 60))->toBeNull() + ->and(Lock::isHeld(Lock::WORKER))->toBeTrue(); + + Lock::release(Lock::WORKER, $token); + + expect(Lock::isHeld(Lock::WORKER))->toBeFalse() + ->and(Lock::acquire(Lock::WORKER, 60))->toBeString(); + }); + + it('can be taken over after it expires', function (): void { + $stale = Lock::acquire(Lock::WORKER, -1); + + expect($stale)->toBeString() + ->and(Lock::refresh(Lock::WORKER, $stale, 60))->toBeTrue(); + + global $wpdb; + $wpdb->query("UPDATE wp_queue_locks SET expires_at = 0 WHERE name = 'worker'"); + + $fresh = Lock::acquire(Lock::WORKER, 60); + + expect($fresh)->toBeString() + ->and(Lock::refresh(Lock::WORKER, $stale, 60))->toBeFalse(); + }); +}); diff --git a/tests/Unit/QueueManagerTest.php b/tests/Unit/QueueManagerTest.php index bfedab6..41333b8 100644 --- a/tests/Unit/QueueManagerTest.php +++ b/tests/Unit/QueueManagerTest.php @@ -84,17 +84,9 @@ public function handle(): void {} }); it('can get queue size', function (): void { - $job1 = new SimpleJob(); - $job2 = new SimpleJob(); - - Brain\Monkey\Functions\stubs([ - 'get_site_option' => fn () => [ - $job1->getId() => ['payload' => serialize($job1), 'available_at' => time(), 'reserved_at' => null, 'attempts' => 0], - $job2->getId() => ['payload' => serialize($job2), 'available_at' => time(), 'reserved_at' => null, 'attempts' => 0], - ], - ]); - $queue = new DatabaseQueue(); + $queue->push(new SimpleJob()); + $queue->push(new SimpleJob()); expect($queue->size('default'))->toBe(2); }); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index f9cf4b3..df43f05 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -10,6 +10,10 @@ // Load Composer autoloader require_once dirname(__DIR__).'/vendor/autoload.php'; +if (! defined('ARRAY_A')) { + define('ARRAY_A', 'ARRAY_A'); +} + // Load Brain Monkey \Brain\Monkey\setUp(); diff --git a/wp-queue.php b/wp-queue.php index 2db6490..0c46811 100644 --- a/wp-queue.php +++ b/wp-queue.php @@ -6,7 +6,7 @@ * Plugin Name: Queue Manager * Plugin URI: https://github.com/rwsite/wp-queue * Description: Background job processing and WP-Cron management for WordPress. Schedule tasks, manage queues, and monitor cron events. - * Version: 1.2.1 + * Version: 1.3.0 * Author: Aleksei Tikhomirov * Author URI: https://rwsite.ru * License: GPL-2.0-or-later @@ -26,7 +26,7 @@ return; } -define('WP_QUEUE_VERSION', '1.2.1'); +define('WP_QUEUE_VERSION', '1.3.0'); define('WP_QUEUE_FILE', __FILE__); define('WP_QUEUE_PATH', plugin_dir_path(__FILE__)); define('WP_QUEUE_URL', plugin_dir_url(__FILE__)); From e3c1fa24a71841ff78ec79676a4e798f99caa2f7 Mon Sep 17 00:00:00 2001 From: Aleksei Tikhomirov Date: Wed, 11 Nov 2026 16:44:07 +0300 Subject: [PATCH 2/2] test: SQLite wpdb only for unit tests; e2e cleanup of queue tables --- tests/Feature/CliIntegrationTest.php | 3 +++ tests/Feature/QueueIntegrationTest.php | 3 +++ tests/Feature/RestApiIntegrationTest.php | 3 +++ tests/Pest.php | 11 ++++++++--- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/tests/Feature/CliIntegrationTest.php b/tests/Feature/CliIntegrationTest.php index 9cbc708..717a180 100644 --- a/tests/Feature/CliIntegrationTest.php +++ b/tests/Feature/CliIntegrationTest.php @@ -22,6 +22,9 @@ global $wpdb; $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name IN ('wp_queue_jobs_default', 'wp_queue_jobs_emails')"); $wpdb->query("DELETE FROM {$wpdb->prefix}queue_logs"); + \WPQueue\Support\Schema::install(); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_jobs"); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_locks"); // Очистка счётчиков и статусов $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wp_queue_%' AND option_name NOT LIKE 'wp_queue_jobs_%'"); diff --git a/tests/Feature/QueueIntegrationTest.php b/tests/Feature/QueueIntegrationTest.php index 44497e7..7fd2f16 100644 --- a/tests/Feature/QueueIntegrationTest.php +++ b/tests/Feature/QueueIntegrationTest.php @@ -21,6 +21,9 @@ global $wpdb; $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name IN ('wp_queue_jobs_default', 'wp_queue_jobs_emails')"); $wpdb->query("DELETE FROM {$wpdb->prefix}queue_logs"); + \WPQueue\Support\Schema::install(); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_jobs"); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_locks"); // Очистка счётчиков и статусов $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wp_queue_%' AND option_name NOT LIKE 'wp_queue_jobs_%'"); diff --git a/tests/Feature/RestApiIntegrationTest.php b/tests/Feature/RestApiIntegrationTest.php index 26ad151..1e37164 100644 --- a/tests/Feature/RestApiIntegrationTest.php +++ b/tests/Feature/RestApiIntegrationTest.php @@ -16,6 +16,9 @@ global $wpdb; $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name IN ('wp_queue_jobs_default', 'wp_queue_jobs_emails')"); $wpdb->query("DELETE FROM {$wpdb->prefix}queue_logs"); + \WPQueue\Support\Schema::install(); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_jobs"); + $wpdb->query("DELETE FROM {$wpdb->prefix}queue_locks"); // Очистка счётчиков и статусов $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wp_queue_%' AND option_name NOT LIKE 'wp_queue_jobs_%'"); diff --git a/tests/Pest.php b/tests/Pest.php index 48006c9..23a6a13 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -11,15 +11,20 @@ uses() ->beforeEach(function (): void { \Brain\Monkey\setUp(); - // Fresh real-SQL database per test (queue table, worker lock). - $GLOBALS['wpdb'] = new \WPQueue\Tests\Support\SqliteWpdb(); - \WPQueue\Support\Schema::markReady(); }) ->afterEach(function (): void { \Brain\Monkey\tearDown(); }) ->in('Unit', 'Feature'); +// Unit tests: fresh real-SQL database (SQLite) per test for the queue table and worker lock. +uses() + ->beforeEach(function (): void { + $GLOBALS['wpdb'] = new \WPQueue\Tests\Support\SqliteWpdb(); + \WPQueue\Support\Schema::markReady(); + }) + ->in('Unit'); + /* |-------------------------------------------------------------------------- | Functions