5 * MINUTE_IN_SECONDS, 'display' => __('Every 5 Minutes', 'valuespace'), ]; return $schedules; } /** Keep one recurring reconciliation trigger; it never owns feature logic. */ function vasp_scheduler_ensure_reconciliation(): bool { return vasp_scheduler_ensure_recurring( 'vasp_reconcile_sync_jobs', 'vasp_every_5_minutes', time() + 5 * MINUTE_IN_SECONDS, [] ); } /** Reconcile durable scopes, then dispatch each feed in its own request. */ function vasp_scheduler_reconcile_and_execute(): bool { update_option(VASP_OPTION_SYNC_RECONCILIATION_LAST_STARTED, time(), false); $vasp_ready = vasp_scheduler_reconcile_services(); vasp_scheduler_dispatch_pending(); update_option(VASP_OPTION_SYNC_RECONCILIATION_LAST_COMPLETED, time(), false); return $vasp_ready; } /** Send one nonblocking local request after the originating request finishes. */ function vasp_scheduler_dispatch_pending(): void { static $vasp_dispatched = []; foreach (array_keys($GLOBALS['vasp_scheduler_services'] ?? []) as $vasp_feed) { if (isset($vasp_dispatched[$vasp_feed]) || !vasp_scheduler_service_is_due($vasp_feed)) { continue; } $vasp_dispatch_option = vasp_scheduler_dispatch_option($vasp_feed); $vasp_dispatch_token = vasp_scheduler_acquire_claim($vasp_dispatch_option, 30); if ($vasp_dispatch_token === '') { continue; } $vasp_dispatched[$vasp_feed] = true; $vasp_timestamp = time(); $vasp_signature = hash_hmac( 'sha256', $vasp_feed . ':' . $vasp_timestamp . ':' . $vasp_dispatch_token, wp_salt('nonce') ); $vasp_wait_for_ack = function_exists('fastcgi_finish_request'); $vasp_dispatch_result = vasp_http_dispatch_local(admin_url('admin-ajax.php'), [ 'wait_for_ack' => $vasp_wait_for_ack, 'body' => [ 'action' => 'vasp_sync_background', 'feed' => $vasp_feed, 'timestamp' => $vasp_timestamp, 'dispatch_token' => $vasp_dispatch_token, 'signature' => $vasp_signature, ], ]); $vasp_dispatch_accepted = !$vasp_wait_for_ack || (!is_wp_error($vasp_dispatch_result) && wp_remote_retrieve_response_code($vasp_dispatch_result) === 202); if (is_wp_error($vasp_dispatch_result) || !$vasp_dispatch_accepted) { vasp_scheduler_release_claim($vasp_dispatch_option, $vasp_dispatch_token); vasp_scheduler_report_error( $vasp_feed, 'loopback_dispatch_failed', false, vasp_scheduler_error_details($vasp_dispatch_result) ); } } } /** Keep one durable WP-Cron wake for a service while loopback remains the fast path. */ function vasp_scheduler_schedule_service_wake(string $name, int $timestamp): bool { $name = sanitize_key($name); return $name !== '' && vasp_scheduler_schedule_single( 'vasp_run_sync_service', $timestamp, [$name], 'keep_earliest', [$name] ); } /** Remove a service's fallback wake after completion or explicit cancellation. */ function vasp_scheduler_clear_service_wake(string $name): int { return vasp_scheduler_clear('vasp_run_sync_service', [sanitize_key($name)]); } /** Make the fallback wake match current durable pending state without losing a concurrent producer. */ function vasp_scheduler_reconcile_service_wake(string $name): bool { $name = sanitize_key($name); if ($name === '') { return false; } wp_cache_delete(vasp_scheduler_pending_option($name), 'options'); $pending = get_option(vasp_scheduler_pending_option($name), false); if (is_array($pending)) { $scheduled = vasp_scheduler_schedule_service_wake( $name, max(time(), (int) ($pending['run_at'] ?? time())) ); if (!$scheduled) { vasp_log('Synchronization fallback could not be scheduled', 'warning', [ 'feed' => $name, ]); } return $scheduled; } vasp_scheduler_clear_service_wake($name); // A producer can insert pending work and its wake while cleanup runs. Read // once more so removing that newer wake cannot strand its durable marker. wp_cache_delete(vasp_scheduler_pending_option($name), 'options'); $pending = get_option(vasp_scheduler_pending_option($name), false); if (!is_array($pending)) { return true; } $scheduled = vasp_scheduler_schedule_service_wake( $name, max(time(), (int) ($pending['run_at'] ?? time())) ); if (!$scheduled) { vasp_log('Synchronization fallback could not be scheduled', 'warning', [ 'feed' => $name, ]); } return $scheduled; } /** Execute one due unit from the durable fallback without creating a second runner. */ function vasp_scheduler_run_scheduled_service($name): void { $name = sanitize_key((string) $name); if ($name === '' || vasp_scheduler_get_service($name) === null) { return; } $pending = get_option(vasp_scheduler_pending_option($name), false); if (!is_array($pending)) { vasp_scheduler_reconcile_service_wake($name); return; } $run_at = (int) ($pending['run_at'] ?? 0); if ($run_at > time() || vasp_scheduler_service_is_running($name)) { vasp_scheduler_reconcile_service_wake($name); return; } vasp_scheduler_execute_service($name); // Another worker can win the claim after the precheck and before execute. // Reconcile the consumed cron event from whatever pending state now owns. vasp_scheduler_reconcile_service_wake($name); } /** Authenticate the private loopback and run the shared bounded executor. */ function vasp_scheduler_handle_background_request(): void { if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { status_header(405); wp_die(); return; } $vasp_feed = isset($_POST['feed']) && is_string($_POST['feed']) ? sanitize_key(wp_unslash($_POST['feed'])) : ''; $timestamp = isset($_POST['timestamp']) && is_scalar($_POST['timestamp']) ? (int) wp_unslash((string) $_POST['timestamp']) : 0; $vasp_dispatch_token = isset($_POST['dispatch_token']) && is_string($_POST['dispatch_token']) ? sanitize_text_field(wp_unslash($_POST['dispatch_token'])) : ''; $signature = isset($_POST['signature']) && is_string($_POST['signature']) ? sanitize_text_field(wp_unslash($_POST['signature'])) : ''; $expected = hash_hmac( 'sha256', $vasp_feed . ':' . $timestamp . ':' . $vasp_dispatch_token, wp_salt('nonce') ); $vasp_dispatch_option = vasp_scheduler_dispatch_option($vasp_feed); $vasp_dispatch_claim = get_option($vasp_dispatch_option, false); if (vasp_scheduler_get_service($vasp_feed) === null || $timestamp <= 0 || $vasp_dispatch_token === '' || abs(time() - $timestamp) > 60 || !hash_equals($expected, $signature) || !is_array($vasp_dispatch_claim) || (int) ($vasp_dispatch_claim['expires_at'] ?? 0) <= time() || !hash_equals((string) ($vasp_dispatch_claim['token'] ?? ''), $vasp_dispatch_token) ) { status_header(403); wp_die(); } $vasp_response_finished = false; if (function_exists('fastcgi_finish_request')) { ignore_user_abort(true); status_header(202); header('Content-Length: 0'); fastcgi_finish_request(); $vasp_response_finished = true; } try { vasp_scheduler_execute_service($vasp_feed); } finally { vasp_scheduler_release_claim($vasp_dispatch_option, $vasp_dispatch_token); } vasp_scheduler_dispatch_pending(); if (!$vasp_response_finished) { status_header(202); wp_die(); } } /** Register one synchronization service. */ function vasp_scheduler_register_service( string $name, string $reconcile_callback, string $cancel_callback, string $execute_callback, string $available_callback = '' ): void { if (!isset($GLOBALS['vasp_scheduler_services']) || !is_array($GLOBALS['vasp_scheduler_services'])) { $GLOBALS['vasp_scheduler_services'] = []; } $GLOBALS['vasp_scheduler_services'][sanitize_key($name)] = [ 'reconcile' => $reconcile_callback, 'cancel' => $cancel_callback, 'execute' => $execute_callback, 'available' => $available_callback, ]; } /** Return the private option used to debounce one synchronization service. */ function vasp_scheduler_pending_option(string $name): string { return 'vasp_sync_pending_' . sanitize_key($name); } /** Return the private claim option for one synchronization service. */ function vasp_scheduler_running_option(string $name): string { return 'vasp_sync_running_' . sanitize_key($name); } /** Return the private cross-request lease used while one loopback is in flight. */ function vasp_scheduler_dispatch_option(string $name): string { return 'vasp_sync_dispatching_' . sanitize_key($name); } /** Insert private scheduler state without overwriting a concurrent owner. */ function vasp_scheduler_insert_option(string $vasp_option, array $vasp_value): bool { global $wpdb; // WordPress add_option() updates duplicate rows after a cached absence. // The unique option name must enforce ownership at the database boundary. $vasp_serialized = maybe_serialize($vasp_value); $vasp_inserted = $wpdb->query($wpdb->prepare( "INSERT INTO %i (option_name, option_value, autoload) VALUES (%s, %s, 'no') ON DUPLICATE KEY UPDATE option_name = VALUES(option_name)", $wpdb->options, $vasp_option, $vasp_serialized )); wp_cache_delete($vasp_option, 'options'); wp_cache_delete('notoptions', 'options'); // A connection using CLIENT_FOUND_ROWS may report one for a no-op clash. // Claims/watchdogs carry unique tokens; verify the stored value as well. return $vasp_inserted === 1 && $wpdb->get_var($wpdb->prepare( 'SELECT option_value FROM %i WHERE option_name = %s', $wpdb->options, $vasp_option )) === $vasp_serialized; } /** Return whether the central executor currently owns this service. */ function vasp_scheduler_service_is_running(string $name): bool { return vasp_scheduler_claim_is_active(vasp_scheduler_running_option($name)); } /** Queue at most one unit for a service and optionally dispatch it off-request. */ function vasp_scheduler_request_service(string $name, bool $dispatch = true, int $delay = 0): bool { if (vasp_scheduler_get_service($name) === null) { return false; } $option = vasp_scheduler_pending_option($name); $run_at = time() + max(0, $delay); $queued = vasp_scheduler_insert_option($option, [ 'run_at' => $run_at, ]); if (!$queued) { vasp_scheduler_note_followup($name, $run_at); } $vasp_requested = $queued || get_option($option, false) !== false; if ($vasp_requested) { vasp_scheduler_reconcile_service_wake($name); } if ($vasp_requested && $dispatch) { // A prior request may already own the due marker. Every immediate // producer arms dispatch after ownership is released. The dispatcher // checks due times, dependencies and ownership at shutdown. add_action('shutdown', 'vasp_scheduler_dispatch_pending', PHP_INT_MAX); } return $vasp_requested; } /** Retain the earliest follow-up requested while an active worker owns the marker. */ function vasp_scheduler_note_followup(string $name, int $run_at): bool { global $wpdb; $option = vasp_scheduler_pending_option($name); for ($attempt = 0; $attempt < 3; $attempt++) { $stored = get_option($option, false); if (!is_array($stored) || empty($stored['watchdog'])) { return false; } $updated = $stored; $vasp_requested_at = max(time(), $run_at); $vasp_existing_at = (int) ($stored['followup_run_at'] ?? 0); $updated['followup_run_at'] = $vasp_existing_at > 0 ? min($vasp_existing_at, $vasp_requested_at) : $vasp_requested_at; $changed = $wpdb->update($wpdb->options, [ 'option_value' => maybe_serialize($updated), ], [ 'option_name' => $option, 'option_value' => maybe_serialize($stored), ], ['%s'], ['%s', '%s']); wp_cache_delete($option, 'options'); if ($changed === 1 || get_option($option, false) === $updated) { return true; } } return false; } /** Make one queued retry due for an explicit administrator run-now action. */ function vasp_scheduler_make_service_due(string $name): bool { global $wpdb; $option = vasp_scheduler_pending_option($name); for ($attempt = 0; $attempt < 3; $attempt++) { wp_cache_delete(vasp_scheduler_running_option($name), 'options'); $stored = get_option($option, false); if (!is_array($stored) || vasp_scheduler_service_is_running($name)) { return false; } $updated = $stored; $updated['run_at'] = time(); if (isset($updated['followup_run_at'])) { $updated['followup_run_at'] = $updated['run_at']; } $changed = $wpdb->update($wpdb->options, [ 'option_value' => maybe_serialize($updated), ], [ 'option_name' => $option, 'option_value' => maybe_serialize($stored), ], ['%s'], ['%s', '%s']); wp_cache_delete($option, 'options'); if ($changed === 1 || get_option($option, false) === $updated) { return true; } } return false; } /** Return whether a service has a queued marker, including a delayed retry. */ function vasp_scheduler_service_is_pending(string $name): bool { return get_option(vasp_scheduler_pending_option($name), false) !== false; } /** Return whether one queued marker may execute now. */ function vasp_scheduler_service_is_due(string $name): bool { $pending = get_option(vasp_scheduler_pending_option($name), false); return is_array($pending) && (int) ($pending['run_at'] ?? 0) <= time() && vasp_scheduler_dependencies_ready($name) && !vasp_scheduler_service_is_running($name); } /** Feed executors are independent; domain prerequisites belong to each worker. */ function vasp_scheduler_dependencies_ready(string $name): bool { return true; } /** Atomically consume and return only the current executor's interruption marker. */ function vasp_scheduler_take_owned_watchdog(string $name, string $token): ?array { global $wpdb; $option = vasp_scheduler_pending_option($name); for ($attempt = 0; $attempt < 3; $attempt++) { $stored = get_option($option, false); if (!is_array($stored) || !hash_equals((string) ($stored['watchdog'] ?? ''), $token)) { return null; } $deleted = $wpdb->delete($wpdb->options, [ 'option_name' => $option, 'option_value' => maybe_serialize($stored), ], ['%s', '%s']); wp_cache_delete($option, 'options'); if ($deleted === 1) { return $stored; } } return null; } /** Execute exactly one queued unit; durable continuation uses a fresh request. */ function vasp_scheduler_execute_service(string $name) { $vasp_started = microtime(true); try { $pending_option = vasp_scheduler_pending_option($name); $pending = get_option($pending_option, false); if (!is_array($pending)) { return false; } if ((int) ($pending['run_at'] ?? 0) > time()) { return true; } $claim_option = vasp_scheduler_running_option($name); $claim = vasp_scheduler_acquire_claim($claim_option, 15 * MINUTE_IN_SECONDS); if ($claim === '') { return true; } try { vasp_scheduler_refresh_service_options($name); if (!vasp_scheduler_dependencies_ready($name)) { return false; } $pending = get_option($pending_option, false); if (!is_array($pending)) { return false; } if ((int) ($pending['run_at'] ?? 0) > time()) { return true; } if (!vasp_scheduler_service_is_available($name)) { vasp_scheduler_cancel_service($name); return false; } // Consume before execution. A request arriving while this unit runs can // never run in parallel. The owned delayed marker is the only fatal-exit // recovery mechanism; normal completion replaces it only when more durable // work remains. delete_option($pending_option); vasp_scheduler_insert_option($pending_option, [ 'run_at' => time() + 5 * MINUTE_IN_SECONDS, 'watchdog' => $claim, ] + array_intersect_key($pending, ['error' => true, 'error_at' => true, 'error_details' => true])); // WP-Cron removes a one-off event before invoking it. Re-arm from // the watchdog before feature code so a fatal exit remains recoverable. vasp_scheduler_reconcile_service_wake($name); unset($GLOBALS['vasp_sync_errors'][$name]); $result = vasp_scheduler_invoke_service($name, 'execute'); $vasp_result_data = is_wp_error($result) ? $result->get_error_data() : []; $vasp_manual_retry = is_array($vasp_result_data) && !empty($vasp_result_data['manual_retry_required']); if (is_wp_error($result)) { // WP_Error creation owns the log entry; the scheduler only retains it. vasp_scheduler_report_error($name, $result, true); } if (!empty($GLOBALS['vasp_sync_errors'][$name])) { if ($vasp_manual_retry) { vasp_scheduler_take_owned_watchdog($name, $claim); vasp_scheduler_reconcile_service_wake($name); return $result; } // A handled failure keeps its chosen retry deadline, not // the generic interruption deadline installed above. global $wpdb; for ($vasp_attempt = 0; $vasp_attempt < 3; $vasp_attempt++) { $vasp_failed = get_option($pending_option, []); if (!is_array($vasp_failed) || ($vasp_failed['watchdog'] ?? '') !== $claim) { break; } $vasp_retry_at = max((int) ($vasp_failed['followup_run_at'] ?? 0), is_array($result) && isset($result['delay']) ? time() + max(1, (int) $result['delay']) : 0); $vasp_retry = $vasp_failed; $vasp_retry['run_at'] = $vasp_retry_at > 0 ? $vasp_retry_at : (int) $vasp_failed['run_at']; // This worker returned normally. Retain its error and // deadline, not an interruption marker for a dead worker. unset($vasp_retry['watchdog'], $vasp_retry['followup_run_at']); $vasp_saved = $wpdb->update($wpdb->options, ['option_value' => maybe_serialize($vasp_retry)], ['option_name' => $pending_option, 'option_value' => maybe_serialize($vasp_failed)], ['%s'], ['%s', '%s']); wp_cache_delete($pending_option, 'options'); if ($vasp_saved === 1) { vasp_scheduler_reconcile_service_wake($name); break; } } return is_wp_error($result) ? $result : new WP_Error('vasp_sync_job_failed'); } $more = is_array($result) ? !empty($result['pending']) : $result === true; $has_result_delay = is_array($result) && array_key_exists('delay', $result); $has_minimum_delay = $has_result_delay && !empty($result['minimum_delay']); $delay = is_array($result) ? max(0, (int) ($result['delay'] ?? 0)) : 0; $watchdog = vasp_scheduler_take_owned_watchdog($name, $claim); if ($watchdog === null) { // Cancellation or another owner removed this attempt. // Its previously computed result cannot schedule new work. return $result; } $followup_run_at = (int) ($watchdog['followup_run_at'] ?? 0); if ($followup_run_at > 0) { $more = true; $vasp_followup_delay = max(0, $followup_run_at - time()); $delay = $has_result_delay ? ($has_minimum_delay ? max($delay, $vasp_followup_delay) : min($delay, $vasp_followup_delay)) : $vasp_followup_delay; } if ($more) { vasp_scheduler_request_service($name, false, $delay); } else { vasp_scheduler_reconcile_service_wake($name); } return $result; } catch (Throwable $error) { // A failure while handling another failure must not erase the // original operation's safe diagnostics. The watchdog still // owns recovery because this worker did not return normally. if (empty($GLOBALS['vasp_sync_errors'][$name])) { vasp_scheduler_report_error($name, 'unexpected_exception', true); } vasp_scheduler_reconcile_service_wake($name); vasp_log('Synchronization worker failed; pending updates retained', 'error', [ 'feed' => $name, 'error_code' => $GLOBALS['vasp_sync_errors'][$name] ?? 'unexpected_exception', 'exception_class' => strpos(get_class($error), '@anonymous') === false ? get_class($error) : 'anonymous_throwable', 'exception_file' => basename($error->getFile()), 'exception_line' => $error->getLine(), ]); return new WP_Error('vasp_sync_job_failed'); } finally { vasp_scheduler_release_claim($claim_option, $claim); } } finally { // Pace fast or skipped AJAX uploads, never cron or status reads. if (wp_doing_ajax() && !wp_doing_cron()) { $vasp_remaining = 1 - (microtime(true) - $vasp_started); if ($vasp_remaining > 0) { usleep((int) ceil($vasp_remaining * 1000000)); } } } } /** Keep only bounded failure facts, never upstream text or request contents. */ function vasp_scheduler_error_details($vasp_error): array { return vasp_error_safe_details($vasp_error); } /** Keep the last failure on the existing pending job until a retry succeeds. */ function vasp_scheduler_report_error(string $vasp_feed, $vasp_error, bool $vasp_origin_logged = false, array $vasp_details = []): void { global $wpdb; $vasp_is_error = is_wp_error($vasp_error); $vasp_code = $vasp_is_error && function_exists('vasp_error_technical_code') ? vasp_error_technical_code($vasp_error) : ($vasp_is_error ? $vasp_error->get_error_code() : (string) $vasp_error); $vasp_code = substr(sanitize_key($vasp_code), 0, 80); $vasp_details = vasp_scheduler_error_details($vasp_is_error ? $vasp_error : $vasp_details); // A feature's summary must not erase the detailed failure already reported // by that same worker. A new attempt may replace it, including with unknown. $vasp_summary_only = !$vasp_is_error && empty($vasp_details) && ($GLOBALS['vasp_sync_errors'][$vasp_feed] ?? '') === $vasp_code; $GLOBALS['vasp_sync_errors'][$vasp_feed] = $vasp_code; $vasp_option = vasp_scheduler_pending_option($vasp_feed); $vasp_pending = get_option($vasp_option, false); if (!is_array($vasp_pending) || $vasp_summary_only || (($vasp_pending['error'] ?? '') === $vasp_code && ($vasp_pending['error_details'] ?? []) === $vasp_details)) { return; } $vasp_updated = $vasp_pending; $vasp_updated['error'] = $vasp_code; $vasp_updated['error_at'] = time(); unset($vasp_updated['error_details']); if ($vasp_details) { $vasp_updated['error_details'] = $vasp_details; } $vasp_saved = $wpdb->update($wpdb->options, ['option_value' => maybe_serialize($vasp_updated)], ['option_name' => $vasp_option, 'option_value' => maybe_serialize($vasp_pending)], ['%s'], ['%s', '%s']); wp_cache_delete($vasp_option, 'options'); if ($vasp_saved === 1 && !$vasp_origin_logged) { vasp_log('Synchronization interrupted; pending updates retained', 'error', [ 'feed' => $vasp_feed, 'error_code' => $vasp_code, ]); } } /** Return one registered synchronization service. */ function vasp_scheduler_get_service(string $name): ?array { $services = is_array($GLOBALS['vasp_scheduler_services'] ?? null) ? $GLOBALS['vasp_scheduler_services'] : []; $service = $services[sanitize_key($name)] ?? null; return is_array($service) ? $service : null; } /** Return whether a service's source and prerequisites are present. */ function vasp_scheduler_service_is_available(string $name): bool { $service = vasp_scheduler_get_service($name); if ($service === null) { return false; } $callback = (string) ($service['available'] ?? ''); return $callback === '' || (is_callable($callback) && (bool) call_user_func($callback)); } /** Invoke one operation owned by a registered service. */ function vasp_scheduler_invoke_service(string $name, string $operation) { $service = vasp_scheduler_get_service($name); $callback = is_array($service) ? (string) ($service[$operation] ?? '') : ''; if ($callback === '' || !is_callable($callback)) { return new WP_Error('vasp_scheduler_service_unavailable'); } return call_user_func($callback); } /** Repair one service from durable local state, or cancel it when unavailable. */ function vasp_scheduler_reconcile_service(string $name) { $vasp_claim_option = vasp_scheduler_running_option($name); $vasp_claim = vasp_scheduler_acquire_claim($vasp_claim_option, 15 * MINUTE_IN_SECONDS); if ($vasp_claim === '') { return true; } try { vasp_scheduler_refresh_service_options($name); if (!vasp_scheduler_service_is_available($name)) { return vasp_scheduler_cancel_service($name); } return vasp_scheduler_invoke_service($name, 'reconcile'); } catch (Throwable $vasp_error) { vasp_log('Synchronization recovery check failed', 'error', [ 'service' => sanitize_key($name), 'exception_class' => get_class($vasp_error), ]); return new WP_Error('vasp_sync_recovery_failed'); } finally { vasp_scheduler_release_claim($vasp_claim_option, $vasp_claim); } } /** Read current feed options after winning its lock, not a pre-lock snapshot. */ function vasp_scheduler_refresh_service_options(string $name): void { $vasp_prefixes = $name === 'events' ? ['VASP_EVENT_'] : ['VASP_WC_CATALOG_', 'VASP_WC_IMAGE_SYNC_']; foreach (get_defined_constants() as $vasp_constant => $vasp_value) { foreach ($vasp_prefixes as $vasp_prefix) { if (strpos($vasp_constant, $vasp_prefix) === 0 && is_string($vasp_value)) { wp_cache_delete($vasp_value, 'options'); } } } wp_cache_delete(vasp_scheduler_pending_option($name), 'options'); wp_cache_delete(vasp_scheduler_dispatch_option($name), 'options'); wp_cache_delete('notoptions', 'options'); } /** Cancel all future work owned by one service. */ function vasp_scheduler_cancel_service(string $name) { delete_option(vasp_scheduler_pending_option($name)); delete_option(vasp_scheduler_dispatch_option($name)); vasp_scheduler_clear_service_wake($name); return vasp_scheduler_invoke_service($name, 'cancel'); } /** Execute one bounded packet immediately and retain required continuation work. */ function vasp_scheduler_run_service_now(string $name) { if (!vasp_scheduler_service_is_available($name)) { return new WP_Error('vasp_scheduler_service_not_applicable'); } vasp_scheduler_request_service($name, false); vasp_scheduler_make_service_due($name); return vasp_scheduler_execute_service($name); } /** Reconcile registered services at an explicit administrator/status boundary. */ function vasp_scheduler_reconcile_services(): bool { $services = is_array($GLOBALS['vasp_scheduler_services'] ?? null) ? $GLOBALS['vasp_scheduler_services'] : []; $ready = true; foreach (array_keys($services) as $name) { $result = vasp_scheduler_reconcile_service($name); if ($result === false || is_wp_error($result)) { $ready = false; } } return $ready; } /** Return scheduled events for a hook and optional exact arguments. */ function vasp_scheduler_get_events(string $hook, ?array $args = []): array { $cron = _get_cron_array(); if (!is_array($cron)) { return []; } $events = []; foreach ($cron as $timestamp => $hooks) { foreach ((array) ($hooks[$hook] ?? []) as $event) { $event_args = is_array($event['args'] ?? null) ? $event['args'] : []; if ($args !== null && $event_args !== $args) { continue; } $events[] = [ 'timestamp' => (int) $timestamp, 'hook' => $hook, 'args' => $event_args, 'schedule' => (string) ($event['schedule'] ?? ''), 'interval' => isset($event['interval']) ? (int) $event['interval'] : null, ]; } } usort($events, static function (array $left, array $right): int { return $left['timestamp'] <=> $right['timestamp']; }); return $events; } /** Return the next matching WP-Cron event. */ function vasp_scheduler_get_next_event(string $hook, ?array $args = []): ?array { $events = vasp_scheduler_get_events($hook, $args); return $events[0] ?? null; } /** Return whether a matching WP-Cron event exists. */ function vasp_scheduler_has_event(string $hook, ?array $args = []): bool { return vasp_scheduler_get_next_event($hook, $args) !== null; } /** Remove exact or all scheduled instances of one hook. */ function vasp_scheduler_clear(string $hook, ?array $args = []): int { $removed = 0; foreach (vasp_scheduler_get_events($hook, $args) as $event) { if (wp_unschedule_event((int) $event['timestamp'], $hook, $event['args'])) { $removed++; } } return $removed; } /** Ensure one one-off event. Durable feature state remains the recovery source. */ function vasp_scheduler_schedule_single( string $hook, int $timestamp, array $args = [], string $policy = 'keep_earliest', ?array $match_args = [] ): bool { $timestamp = max(time(), $timestamp); $match_args = func_num_args() < 5 ? $args : $match_args; $events = vasp_scheduler_get_events($hook, $match_args); $existing = $events[0] ?? null; if ($existing !== null && $policy !== 'replace' && ($policy === 'keep' || (int) $existing['timestamp'] <= $timestamp) ) { foreach (array_slice($events, 1) as $duplicate) { wp_unschedule_event((int) $duplicate['timestamp'], $hook, $duplicate['args']); } return count(vasp_scheduler_get_events($hook, $match_args)) === 1; } if ($existing !== null) { vasp_scheduler_clear($hook, $match_args); if (!empty(vasp_scheduler_get_events($hook, $match_args))) { return false; } } return wp_schedule_single_event($timestamp, $hook, $args) === true; } /** Ensure one recurring event with the requested interval. */ function vasp_scheduler_ensure_recurring(string $hook, string $recurrence, int $first_run, array $args = []): bool { $events = vasp_scheduler_get_events($hook, $args); $existing = $events[0] ?? null; if ($existing !== null && (string) $existing['schedule'] === $recurrence) { foreach (array_slice($events, 1) as $duplicate) { wp_unschedule_event((int) $duplicate['timestamp'], $hook, $duplicate['args']); } return count(vasp_scheduler_get_events($hook, $args)) === 1; } if ($existing !== null) { vasp_scheduler_clear($hook, $args); if (!empty(vasp_scheduler_get_events($hook, $args))) { return false; } } return wp_schedule_event(max(time(), $first_run), $recurrence, $hook, $args) === true; } /** Atomically claim one bounded worker. Durable feature state remains separate. */ function vasp_scheduler_acquire_claim(string $option, int $ttl): string { global $wpdb; $now = time(); $existing = get_option($option, null); if (is_array($existing) && (int) ($existing['expires_at'] ?? 0) <= $now) { $deleted = $wpdb->delete($wpdb->options, [ 'option_name' => $option, 'option_value' => maybe_serialize($existing), ], ['%s', '%s']); if ($deleted === 1) { wp_cache_delete($option, 'options'); } } $token = wp_generate_uuid4(); return vasp_scheduler_insert_option($option, [ 'token' => $token, 'expires_at' => $now + max(1, $ttl), ]) ? $token : ''; } /** Extend a claim only while the caller still owns it. */ function vasp_scheduler_renew_claim(string $option, string $token, int $ttl): bool { global $wpdb; wp_cache_delete($option, 'options'); $existing = get_option($option, null); if (!is_array($existing) || !hash_equals((string) ($existing['token'] ?? ''), $token) || (int) ($existing['expires_at'] ?? 0) <= time()) { return false; } $renewed = $existing; $renewed['expires_at'] = time() + max(1, $ttl); $updated = $wpdb->update($wpdb->options, [ 'option_value' => maybe_serialize($renewed), ], [ 'option_name' => $option, 'option_value' => maybe_serialize($existing), ], ['%s'], ['%s', '%s']); wp_cache_delete($option, 'options'); if ($updated === 1) { return true; } if ($updated !== 0) { return false; } // MySQL reports zero affected rows when a fast worker renews within the // same second and the serialized expiry is therefore unchanged. The claim // is still valid as long as this owner and deadline remain stored. $current = get_option($option, null); return is_array($current) && $current === $renewed; } /** Release a claim without deleting a successor's ownership. */ function vasp_scheduler_release_claim(string $option, string $token): bool { global $wpdb; $existing = get_option($option, null); if (!is_array($existing) || !hash_equals((string) ($existing['token'] ?? ''), $token)) { return false; } $deleted = $wpdb->delete($wpdb->options, [ 'option_name' => $option, 'option_value' => maybe_serialize($existing), ], ['%s', '%s']); if ($deleted === 1) { wp_cache_delete($option, 'options'); return true; } return false; } /** Return whether an unexpired worker claim currently owns the option. */ function vasp_scheduler_claim_is_active(string $option): bool { $claim = get_option($option, false); return is_array($claim) && (int) ($claim['expires_at'] ?? 0) > time(); } /** Return every ValueSpace-owned task for administrator diagnostics. */ function vasp_scheduler_get_plugin_events(): array { $cron = _get_cron_array(); if (!is_array($cron)) { return []; } $events = []; foreach ($cron as $timestamp => $hooks) { foreach ((array) $hooks as $hook => $instances) { if (strpos((string) $hook, 'vasp_') !== 0) { continue; } foreach ((array) $instances as $event) { $events[] = [ 'timestamp' => (int) $timestamp, 'hook' => (string) $hook, 'schedule' => (string) ($event['schedule'] ?? ''), ]; } } } usort($events, static function (array $left, array $right): int { return $left['timestamp'] <=> $right['timestamp']; }); return $events; } /** Return scheduler status for a feature health display. */ function vasp_scheduler_get_status(string $hook, ?array $args = [], int $overdue_tolerance = 60): array { $event = vasp_scheduler_get_next_event($hook, $args); $next_run = is_array($event) ? (int) $event['timestamp'] : null; return [ 'source' => $event === null ? 'none' : 'wp_cron', 'scheduled' => $event !== null, 'next_run' => $next_run, 'overdue' => $next_run !== null && $next_run + max(0, $overdue_tolerance) < time(), 'schedule' => is_array($event) ? (string) $event['schedule'] : '', ]; }