diff --git a/README.md b/README.md index 5b06afd..3a696e9 100644 --- a/README.md +++ b/README.md @@ -203,11 +203,13 @@ WordPress Request Worker Process (Workerman) | Timer triggers at scheduled time | - Claim job (INSERT IGNORE lock) - | - Batch by site_id - | - +------------------------------+ + Claim job (INSERT IGNORE lock) + | + Batch by site_id + | + Acquire per-site WP-Cron execution lease + | + +------------------------------+ | Subprocess: execute-job.php | | Bootstrap WP for site | | For each job in batch: | @@ -222,9 +224,9 @@ WordPress Request Worker Process (Workerman) 2. The plugin intercepts the schedule call and sends a JSON payload to the worker via Unix socket. 3. The worker sets a Workerman timer for the job's exact timestamp. 4. When the timer triggers, the worker atomically claims the job via `INSERT IGNORE` into a lock table (prevents duplicate execution across workers). -5. Claimed jobs are batched by `site_id` and flushed to a subprocess every second. +5. Claimed jobs are batched by `site_id` and flushed to a subprocess every second. WP-Cron batches acquire a shared per-site lease so separate worker processes cannot update one site's cron option concurrently. 6. The subprocess (`execute-job.php`) bootstraps WordPress for the target site's domain, executes each job with a per-job SIGALRM timeout, logs results to the `qw_job_log` table, and exits. -7. The worker polls subprocesses for completion and logs batch results. +7. The worker polls subprocesses for completion, refreshes active site leases, and logs batch results. 8. A periodic database rescan catches any jobs that arrived before the worker started or bypassed socket notification. ## Troubleshooting diff --git a/src/class-job-payload.php b/src/class-job-payload.php index e02efe4..87adef7 100644 --- a/src/class-job-payload.php +++ b/src/class-job-payload.php @@ -108,11 +108,18 @@ public static function from_as_action(int $action_id): ?self public function tracking_key(): string { + if ($this->is_action_scheduler() && $this->action_id > 0) { + return sprintf( + 'action_scheduler:%d:%d', + $this->site_id, + $this->action_id + ); + } + return sprintf( - '%s:%d:%s:%s:%s:%s:%d', + '%s:%d:%s:%s:%s:%d', $this->source, $this->site_id, - md5($this->site_url), $this->hook, $this->group, md5(serialize($this->args)), diff --git a/src/class-worker-process.php b/src/class-worker-process.php index 75c33bb..d293389 100644 --- a/src/class-worker-process.php +++ b/src/class-worker-process.php @@ -13,6 +13,9 @@ */ class Worker_Process { + private const QW_CRON_SITE_LOCK_TTL_SECONDS = 360; + private const QW_CRON_SITE_LOCK_REFRESH_SECONDS = 60; + /** @var string Absolute path to wp-load.php */ private string $wp_load; @@ -49,7 +52,7 @@ class Worker_Process /** @var array tracking_key => payload */ private array $pending_timer_payloads = []; - /** @var list, started: int, stdout: string, stderr: string, lane: string}> */ + /** @var list, started: int, stdout: string, stderr: string, lane: string, cron_site_lock_owner: string, cron_site_lock_refreshed: int}> */ private array $running_processes = []; /** @var array>> lane => site_id => [payload, ...] */ @@ -333,7 +336,12 @@ private function execute_action_scheduler_job(Job_Payload $payload): void /** * Spawn a subprocess to execute a batch of jobs (all same site). */ - private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp_cron'): void + private function spawn_batch( + array $payloads, + int $worker_id, + string $lane = 'wp_cron', + string $cron_site_lock_owner = '' + ): bool { $json_array = array_map( fn($p) => array_merge(json_decode($p->to_json(), true), ['lane' => $lane]), @@ -355,7 +363,10 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp count($payloads), $payloads[0]->site_id )); - return; + if ($cron_site_lock_owner !== '') { + $this->release_cron_site_lock($payloads[0]->site_id, $cron_site_lock_owner); + } + return false; } // Write JSON payload to stdin, then close @@ -366,13 +377,15 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp $this->running_jobs++; $this->running_processes[] = [ - 'process' => $process, - 'pipes' => $pipes, - 'payloads' => $payloads, - 'started' => time(), - 'stdout' => '', - 'stderr' => '', - 'lane' => $lane, + 'process' => $process, + 'pipes' => $pipes, + 'payloads' => $payloads, + 'started' => time(), + 'stdout' => '', + 'stderr' => '', + 'lane' => $lane, + 'cron_site_lock_owner' => $cron_site_lock_owner, + 'cron_site_lock_refreshed' => time(), ]; $hooks = array_map(fn($p) => $p->hook, $payloads); @@ -388,6 +401,8 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp $priority_summary, implode(', ', array_unique($hooks)) )); + + return true; } /** @@ -407,10 +422,17 @@ private function flush_batches(): void if ($this->running_process_count($lane) >= $this->cron_lane_max_concurrent($lane)) { break; } + $site_lock_owner = $this->claim_cron_site_lock((int) $site_id); + if ($site_lock_owner === null) { + continue; + } $this->sort_payloads_by_priority($this->pending_batch[$lane][$site_id]); $batch = array_splice($this->pending_batch[$lane][$site_id], 0, $this->cron_lane_max_batch_size($lane)); // Worker ID isn't critical for batch flush logging; use 0 - $this->spawn_batch($batch, 0, $lane); + if (!$this->spawn_batch($batch, 0, $lane, $site_lock_owner)) { + array_splice($this->pending_batch[$lane][$site_id], 0, 0, $batch); + continue; + } if (empty($this->pending_batch[$lane][$site_id])) { unset($this->pending_batch[$lane][$site_id]); } @@ -479,7 +501,10 @@ private function flush_action_scheduler_batches(): void } $this->sort_payloads_by_priority($this->pending_as_batch[$lane][$site_id]); $batch = array_splice($this->pending_as_batch[$lane][$site_id], 0, $this->lane_max_batch_size($lane)); - $this->spawn_batch($batch, 0, $lane); + if (!$this->spawn_batch($batch, 0, $lane)) { + array_splice($this->pending_as_batch[$lane][$site_id], 0, 0, $batch); + continue; + } if (empty($this->pending_as_batch[$lane][$site_id])) { unset($this->pending_as_batch[$lane][$site_id]); } @@ -708,6 +733,26 @@ private function running_process_count(string $lane): int private function poll_processes(int $worker_id): void { foreach ($this->running_processes as $i => $proc) { + $cron_site_lock_owner = $proc['cron_site_lock_owner']; + $lock_refreshed = $proc['cron_site_lock_refreshed']; + if ($cron_site_lock_owner !== '' && time() - $lock_refreshed >= self::QW_CRON_SITE_LOCK_REFRESH_SECONDS) { + if ($this->refresh_cron_site_lock($proc['payloads'][0]->site_id, $cron_site_lock_owner)) { + $this->running_processes[$i]['cron_site_lock_refreshed'] = time(); + } else { + $this->terminate_and_reap_process($proc); + Worker::log(sprintf( + '[W%d][LOCK][LOST] Batch: %d jobs on site %d lost its cron site lease', + $worker_id, + count($proc['payloads']), + $proc['payloads'][0]->site_id + )); + $this->release_running_cron_site_lock($proc); + unset($this->running_processes[$i]); + $this->running_jobs--; + continue; + } + } + // Read available output $out = stream_get_contents($proc['pipes'][1]); if ($out !== false && $out !== '') { @@ -765,6 +810,7 @@ private function poll_processes(int $worker_id): void )); } + $this->release_running_cron_site_lock($proc); unset($this->running_processes[$i]); $this->running_jobs--; continue; @@ -774,10 +820,7 @@ private function poll_processes(int $worker_id): void if (time() - $proc['started'] > $this->batch_timeout) { $payloads = $proc['payloads']; $pid = $status['pid']; - proc_terminate($proc['process'], 9); - fclose($proc['pipes'][1]); - fclose($proc['pipes'][2]); - proc_close($proc['process']); + $this->terminate_and_reap_process($proc); Worker::log(sprintf( '[W%d][TIMEOUT] Batch: %d jobs on site %d exceeded %ds limit (pid %d)', @@ -788,6 +831,7 @@ private function poll_processes(int $worker_id): void $pid )); + $this->release_running_cron_site_lock($proc); unset($this->running_processes[$i]); $this->running_jobs--; } @@ -796,6 +840,17 @@ private function poll_processes(int $worker_id): void $this->running_processes = array_values($this->running_processes); } + /** + * Stop an active child process and reap its resources. + */ + private function terminate_and_reap_process(array $proc): void + { + proc_terminate($proc['process'], 9); + fclose($proc['pipes'][1]); + fclose($proc['pipes'][2]); + proc_close($proc['process']); + } + /** * Scan all multisite blogs for pending WP Cron events and AS actions. */ @@ -1120,6 +1175,102 @@ private function claim_job(string $job_key): bool return $result === 1; } + /** + * Claim the network-wide WP-Cron execution lease for a site. + */ + private function claim_cron_site_lock(int $site_id): ?string + { + global $wpdb; + + if ($site_id < 1) { + return null; + } + + try { + $owner_token = bin2hex(random_bytes(16)); + } catch (\Throwable $e) { + Worker::log(sprintf('[LOCK][ERROR] Failed to create a cron site-lock token for site %d: %s', $site_id, $e->getMessage())); + return null; + } + + $table = $wpdb->base_prefix . 'qw_cron_site_locks'; + $ttl = self::QW_CRON_SITE_LOCK_TTL_SECONDS; + $result = $wpdb->query($wpdb->prepare( + "INSERT INTO `$table` (site_id, owner_token, expires_at) " + . "VALUES (%d, %s, DATE_ADD(NOW(), INTERVAL $ttl SECOND)) " + . 'ON DUPLICATE KEY UPDATE ' + . 'owner_token = IF(expires_at < NOW(), VALUES(owner_token), owner_token), ' + . 'expires_at = IF(expires_at < NOW(), VALUES(expires_at), expires_at)', + $site_id, + $owner_token + )); + + if ($result === false) { + return null; + } + + // Do not rely on affected-row semantics: clients using FOUND_ROWS can + // report a no-op duplicate-key update as successful. + $current_owner = $wpdb->get_var($wpdb->prepare( + "SELECT owner_token FROM `$table` WHERE site_id = %d", + $site_id + )); + + return is_string($current_owner) && hash_equals($owner_token, $current_owner) ? $owner_token : null; + } + + /** + * Extend a site lease while its subprocess is still running. + */ + private function refresh_cron_site_lock(int $site_id, string $owner_token): bool + { + global $wpdb; + + $table = $wpdb->base_prefix . 'qw_cron_site_locks'; + $ttl = self::QW_CRON_SITE_LOCK_TTL_SECONDS; + $result = $wpdb->query($wpdb->prepare( + "UPDATE `$table` SET expires_at = DATE_ADD(NOW(), INTERVAL $ttl SECOND) " + . 'WHERE site_id = %d AND owner_token = %s', + $site_id, + $owner_token + )); + + return $result === 1; + } + + /** + * Release a site lease only when this worker still owns it. + */ + private function release_cron_site_lock(int $site_id, string $owner_token): void + { + global $wpdb; + + if ($site_id < 1 || $owner_token === '') { + return; + } + + $table = $wpdb->base_prefix . 'qw_cron_site_locks'; + $wpdb->query($wpdb->prepare( + "DELETE FROM `$table` WHERE site_id = %d AND owner_token = %s", + $site_id, + $owner_token + )); + } + + /** + * Release the optional WP-Cron lease attached to a subprocess record. + */ + private function release_running_cron_site_lock(array $process): void + { + $owner_token = (string) ($process['cron_site_lock_owner'] ?? ''); + $payloads = $process['payloads'] ?? []; + if ($owner_token === '' || empty($payloads)) { + return; + } + + $this->release_cron_site_lock($payloads[0]->site_id, $owner_token); + } + /** * Handle incoming socket commands (status, restart). */ @@ -1423,5 +1574,14 @@ public static function ensure_lock_table(): void claimed_at DATETIME NOT NULL ) ENGINE=InnoDB" ); + + $cron_site_locks = $wpdb->base_prefix . 'qw_cron_site_locks'; + $wpdb->query("CREATE TABLE IF NOT EXISTS `$cron_site_locks` ( + site_id BIGINT UNSIGNED NOT NULL PRIMARY KEY, + owner_token VARCHAR(64) NOT NULL, + expires_at DATETIME NOT NULL, + KEY expires_at (expires_at) + ) ENGINE=InnoDB" + ); } } diff --git a/tests/regression.php b/tests/regression.php index 3a35f16..bef35a4 100644 --- a/tests/regression.php +++ b/tests/regression.php @@ -167,6 +167,8 @@ class Test_WPDB public string $base_prefix = 'wp_'; public array $queries = []; public array $query_results = []; + public array $cron_site_locks = []; + public array $expired_cron_site_locks = []; public function prepare(string $query, ...$args): string { @@ -180,6 +182,9 @@ public function esc_like(string $text): string public function get_var(string $query): ?string { + if (preg_match('/SELECT owner_token FROM `wp_qw_cron_site_locks` WHERE site_id = ([0-9]+)/', $query, $matches)) { + return $this->cron_site_locks[(int) $matches[1]] ?? null; + } if (str_contains($query, 'SHOW TABLES LIKE') && str_contains($query, 'wu_domain_mappings')) { return $GLOBALS['test_mapping_table_exists'] ? 'wp_wu_domain_mappings' : null; } @@ -199,6 +204,35 @@ public function query(string $query) { $this->queries[] = $query; + if (str_contains($query, 'qw_cron_site_locks')) { + if (str_starts_with($query, 'CREATE TABLE')) { + return 1; + } + if (preg_match("/INSERT INTO `wp_qw_cron_site_locks` .*VALUES \\(([0-9]+), '([a-f0-9]+)'/", $query, $matches)) { + $site_id = (int) $matches[1]; + if (isset($this->cron_site_locks[$site_id]) && empty($this->expired_cron_site_locks[$site_id])) { + // Emulate a client using CLIENT_FOUND_ROWS, where a + // no-op duplicate-key update can report one row. + return 1; + } + $this->cron_site_locks[$site_id] = $matches[2]; + unset($this->expired_cron_site_locks[$site_id]); + return 1; + } + if (preg_match("/UPDATE `wp_qw_cron_site_locks` .*WHERE site_id = ([0-9]+) AND owner_token = '([a-f0-9]+)'/", $query, $matches)) { + $site_id = (int) $matches[1]; + return ($this->cron_site_locks[$site_id] ?? '') === $matches[2] ? 1 : 0; + } + if (preg_match("/DELETE FROM `wp_qw_cron_site_locks` WHERE site_id = ([0-9]+) AND owner_token = '([a-f0-9]+)'/", $query, $matches)) { + $site_id = (int) $matches[1]; + if (($this->cron_site_locks[$site_id] ?? '') !== $matches[2]) { + return 0; + } + unset($this->cron_site_locks[$site_id]); + return 1; + } + } + return $this->query_results === [] ? 1 : array_shift($this->query_results); } } @@ -373,6 +407,13 @@ function private_property(object $object, string $property) return $reflection->getValue($object); } + function set_private_property(object $object, string $property, mixed $value): void + { + $reflection = new ReflectionProperty($object, $property); + $reflection->setAccessible(true); + $reflection->setValue($object, $value); + } + function invoke_private(object $object, string $method, array $args = []) { $reflection = new ReflectionMethod($object, $method); @@ -402,7 +443,49 @@ function invoke_private(object $object, string $method, array $args = []) ]); $decoded = json_decode($payload->to_json(), true); assert_same('checkout', $decoded['group'], 'Action Scheduler group must be serialized'); - assert_true(str_contains($payload->tracking_key(), ':checkout:'), 'Action Scheduler group must be part of the tracking key'); + assert_same('action_scheduler:7:44', $payload->tracking_key(), 'Action Scheduler identity must use its durable action ID'); + $same_action_different_route = new Job_Payload([ + 'site_id' => 7, + 'site_url' => 'https://alternate.example.test', + 'hook' => 'changed_transport_hook', + 'args' => ['changed' => true], + 'timestamp' => 1710000100, + 'source' => 'action_scheduler', + 'action_id' => 44, + 'group' => 'alternate', + ]); + assert_same($payload->tracking_key(), $same_action_different_route->tracking_key(), 'Action Scheduler identity must not depend on routing metadata'); + $different_action = new Job_Payload([ + 'site_id' => 7, + 'site_url' => 'https://tenant.example.test', + 'hook' => 'as_hook', + 'args' => ['order_id' => 123], + 'timestamp' => 1710000000, + 'source' => 'action_scheduler', + 'action_id' => 45, + 'group' => 'checkout', + ]); + assert_true($payload->tracking_key() !== $different_action->tracking_key(), 'Distinct Action Scheduler actions must not collapse'); + + $cron_route_a = new Job_Payload([ + 'site_id' => 7, + 'site_url' => 'https://tenant.example.test', + 'hook' => 'route_independent_hook', + 'args' => ['batch' => 1], + 'timestamp' => 2147483647, + 'schedule' => 'hourly', + 'source' => 'wp_cron', + ]); + $cron_route_b = new Job_Payload([ + 'site_id' => 7, + 'site_url' => 'https://mapped.example.test', + 'hook' => 'route_independent_hook', + 'args' => ['batch' => 1], + 'timestamp' => 2147483647, + 'schedule' => 'hourly', + 'source' => 'wp_cron', + ]); + assert_same($cron_route_a->tracking_key(), $cron_route_b->tracking_key(), 'WP-Cron identity must not depend on its bootstrap URL'); $failed_bootstrap_file = tempnam(sys_get_temp_dir(), 'qw-bootstrap-failure-'); assert_true(false !== $failed_bootstrap_file, 'Bootstrap failure fixture must be created'); @@ -438,6 +521,65 @@ function invoke_private(object $object, string $method, array $args = []) ], ])); $worker = new Worker_Process(__FILE__, 'example.test', __FILE__); + $identity_worker = new Worker_Process(__FILE__, 'example.test', __FILE__); + invoke_private($identity_worker, 'schedule_timer', [$cron_route_a]); + invoke_private($identity_worker, 'schedule_timer', [$cron_route_b]); + assert_same(1, count(private_property($identity_worker, 'pending_timers')), 'Route variants of one WP-Cron event must collapse to one timer'); + + Worker_Process::ensure_lock_table(); + assert_true( + str_contains(implode("\n", $GLOBALS['wpdb']->queries), 'CREATE TABLE IF NOT EXISTS `wp_qw_cron_site_locks`'), + 'Worker startup must provision the shared per-site cron lock table' + ); + $site_7_owner = invoke_private($worker, 'claim_cron_site_lock', [7]); + assert_true(is_string($site_7_owner) && $site_7_owner !== '', 'The first worker must claim a site cron lease'); + $second_worker = new Worker_Process(__FILE__, 'example.test', __FILE__); + assert_same(null, invoke_private($second_worker, 'claim_cron_site_lock', [7]), 'A second worker must not claim an active lease for the same site'); + $site_8_owner = invoke_private($second_worker, 'claim_cron_site_lock', [8]); + assert_true(is_string($site_8_owner) && $site_8_owner !== '', 'Different sites must retain parallel cron execution'); + assert_same(true, invoke_private($worker, 'refresh_cron_site_lock', [7, $site_7_owner]), 'The owning worker must refresh its cron site lease'); + $GLOBALS['wpdb']->expired_cron_site_locks[7] = true; + $replacement_site_7_owner = invoke_private($second_worker, 'claim_cron_site_lock', [7]); + assert_true( + is_string($replacement_site_7_owner) && $replacement_site_7_owner !== $site_7_owner, + 'Another worker must be able to replace an expired site lease' + ); + assert_same(false, invoke_private($worker, 'refresh_cron_site_lock', [7, $site_7_owner]), 'A stale owner must not refresh a replaced site lease'); + invoke_private($worker, 'release_cron_site_lock', [7, $site_7_owner]); + assert_same(null, invoke_private($worker, 'claim_cron_site_lock', [7]), 'A stale owner must not release another worker\'s site lease'); + + $lease_process = proc_open(PHP_BINARY . ' -r ' . escapeshellarg('sleep(5);'), [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ], $lease_pipes); + assert_true(is_resource($lease_process), 'Lease-renewal failure fixture must start a subprocess'); + fclose($lease_pipes[0]); + stream_set_blocking($lease_pipes[1], false); + stream_set_blocking($lease_pipes[2], false); + set_private_property($worker, 'running_processes', [[ + 'process' => $lease_process, + 'pipes' => $lease_pipes, + 'payloads' => [$payload], + 'started' => time(), + 'stdout' => '', + 'stderr' => '', + 'lane' => 'wp_cron', + 'cron_site_lock_owner' => $site_7_owner, + 'cron_site_lock_refreshed' => time() - 61, + ]]); + set_private_property($worker, 'running_jobs', 1); + invoke_private($worker, 'poll_processes', [0]); + assert_same([], private_property($worker, 'running_processes'), 'A batch must be reaped when its cron site lease cannot be renewed'); + assert_same(0, private_property($worker, 'running_jobs'), 'A reaped batch must no longer count as running'); + assert_same($replacement_site_7_owner, $GLOBALS['wpdb']->cron_site_locks[7] ?? null, 'A stale worker must not delete the replacement site lease'); + + invoke_private($second_worker, 'release_cron_site_lock', [7, $replacement_site_7_owner]); + $reclaimed_site_7_owner = invoke_private($worker, 'claim_cron_site_lock', [7]); + assert_true(is_string($reclaimed_site_7_owner) && $reclaimed_site_7_owner !== '', 'A completed batch must release the site for the next worker'); + invoke_private($worker, 'release_cron_site_lock', [7, $reclaimed_site_7_owner]); + invoke_private($second_worker, 'release_cron_site_lock', [8, $site_8_owner]); + assert_same('checkout_lane', invoke_private($worker, 'action_scheduler_lane_for', [$payload]), 'AS lane must match by site, group, and hook'); assert_same('action_scheduler', invoke_private($worker, 'action_scheduler_lane_for', [new Job_Payload([ 'site_id' => 7,