'', 'consecutive_failures' => 0, 'retry_exhaustion_reported' => false, 'retry_not_before' => 0, ]; } $stored_receipts = is_array($status['gateway_receipts'] ?? null) ? array_values($status['gateway_receipts']) : []; $active_receipts = vasp_event_gateway_receipts($status); $stale_legacy_summary = !$stored_receipts && !$active_receipts && in_array((string) ($status['gateway_status'] ?? ''), ['queued', 'processing'], true); if ($active_receipts !== $stored_receipts || $stale_legacy_summary) { $changes = array_merge($changes, vasp_event_gateway_receipt_summary($active_receipts), [ 'gateway_status_url' => $active_receipts ? (string) ($status['gateway_status_url'] ?? '') : '', 'gateway_receipts' => $active_receipts, ]); } if ($changes) { vasp_event_update_delivery_status($changes); } } $option = vasp_scheduler_pending_option('events'); for ($attempt = 0; $attempt < 3; $attempt++) { $pending = get_option($option, false); if (!is_array($pending) || ($pending['error'] ?? '') !== 'receipt_status_unavailable') { return; } $updated = $pending; unset($updated['error'], $updated['error_at'], $updated['error_details']); $saved = $wpdb->update( $wpdb->options, ['option_value' => maybe_serialize($updated)], ['option_name' => $option, 'option_value' => maybe_serialize($pending)], ['%s'], ['%s', '%s'] ); wp_cache_delete($option, 'options'); if ($saved === 1) { return; } } } /** Route legacy cron work through the same service owner as AJAX and loopback. */ function vasp_event_legacy_delivery_trigger(): void { vasp_scheduler_request_service('events'); } /** Return the current cancellation generation. */ function vasp_event_delivery_generation() { return max(0, (int) get_option(VASP_EVENT_DELIVERY_GENERATION_OPTION, 0)); } /** Invalidate workers created under an earlier enable/connection state. */ function vasp_event_rotate_delivery_generation() { $generation = vasp_event_delivery_generation() + 1; update_option(VASP_EVENT_DELIVERY_GENERATION_OPTION, $generation, false); return $generation; } /** Return whether a worker may still publish and acknowledge its batch. */ function vasp_event_delivery_worker_is_current($generation) { return (int) $generation === vasp_event_delivery_generation() && vasp_is_event_tracking_enabled() && function_exists('vasp_valuespace_is_connected') && vasp_valuespace_is_connected(); } /** Read privacy-safe delivery health metadata. */ function vasp_event_get_delivery_status() { $status = get_option(VASP_EVENT_DELIVERY_STATUS_OPTION, []); $defaults = [ 'last_attempt' => 0, 'last_success' => 0, 'last_error' => '', 'last_batch_size' => 0, 'last_duration_ms' => 0, 'consecutive_failures' => 0, 'accepted_total' => 0, 'duplicate_total' => 0, 'acknowledged_total' => 0, 'discarded_total' => 0, 'gateway_published' => 0, 'gateway_pending' => 0, 'gateway_batch_id' => '', 'gateway_status' => '', 'gateway_status_url' => '', 'gateway_updated_at' => '', 'gateway_quarantined' => 0, 'gateway_rejected' => 0, 'gateway_status_next_at' => 0, 'gateway_receipts' => [], 'isolation_limit' => 0, 'compatibility_required' => false, 'supported_schema_versions' => [], 'discarded' => [], 'pending_hint' => false, 'retry_exhaustion_reported' => false, 'next_attempt_at' => 0, 'retry_not_before' => 0, ]; return is_array($status) ? wp_parse_args($status, $defaults) : $defaults; } /** Persist health data without event payloads or visitor identifiers. */ function vasp_event_update_delivery_status($changes) { global $wpdb; for ($attempt = 0; $attempt < 3; $attempt++) { $stored = get_option(VASP_EVENT_DELIVERY_STATUS_OPTION, null); if ($stored === null || $stored === false) { if (add_option(VASP_EVENT_DELIVERY_STATUS_OPTION, array_merge(vasp_event_get_delivery_status(), (array) $changes), '', 'no')) { return true; } continue; } $stored = is_array($stored) ? $stored : []; $original = $stored; if (!array_key_exists('retry_not_before', $stored) && (int) ($stored['consecutive_failures'] ?? 0) > 0 ) { $stored['retry_not_before'] = max(0, (int) ($stored['next_attempt_at'] ?? 0)); } $updated = array_merge(vasp_event_get_delivery_status(), $stored, (array) $changes); $changed = $wpdb->update($wpdb->options, [ 'option_value' => maybe_serialize($updated), ], [ 'option_name' => VASP_EVENT_DELIVERY_STATUS_OPTION, 'option_value' => maybe_serialize($original), ], ['%s'], ['%s', '%s']); if ($changed === 1) { wp_cache_delete(VASP_EVENT_DELIVERY_STATUS_OPTION, 'options'); return true; } wp_cache_delete(VASP_EVENT_DELIVERY_STATUS_OPTION, 'options'); $current = get_option(VASP_EVENT_DELIVERY_STATUS_OPTION, []); if ($changed === 0 && is_array($current)) { $matches = true; foreach ((array) $changes as $key => $value) { if (!array_key_exists($key, $current) || $current[$key] !== $value) { $matches = false; break; } } if ($matches) { return true; } } } return false; } /** Note a newly accepted outbox row and request prompt background delivery. */ function vasp_event_note_pending_delivery() { vasp_event_update_delivery_status(['pending_hint' => true]); $retry_delay = max(0, vasp_event_delivery_retry_not_before() - time()); vasp_event_schedule_delivery($retry_delay); } /** Return seconds until 06:00 in the WordPress site timezone, or zero outside the quiet period. */ function vasp_event_delivery_quiet_period_delay($now = null) { $now = $now === null ? time() : (int) $now; $local_now = (new DateTimeImmutable('@' . $now))->setTimezone(wp_timezone()); if ((int) $local_now->format('G') >= VASP_EVENT_DELIVERY_RESUME_HOUR) { return 0; } $resume_at = $local_now->setTime(VASP_EVENT_DELIVERY_RESUME_HOUR, 0, 0); return max(1, $resume_at->getTimestamp() - $now); } /** Durable outbox state is the sole authority for whether delivery work exists. */ function vasp_event_delivery_task_is_needed() { return vasp_event_has_pending_delivery() || vasp_event_gateway_status_refresh_needed(); } /** Return the persisted retry deadline, including pre-upgrade failure state. */ function vasp_event_delivery_retry_not_before() { $stored = get_option(VASP_EVENT_DELIVERY_STATUS_OPTION, []); if (!is_array($stored)) { return 0; } if (array_key_exists('retry_not_before', $stored)) { return max(0, (int) $stored['retry_not_before']); } return (int) ($stored['consecutive_failures'] ?? 0) > 0 ? max(0, (int) ($stored['next_attempt_at'] ?? 0)) : 0; } /** Return the current central delivery job and worker state. */ function vasp_event_delivery_scheduled_state() { $event = get_option(vasp_scheduler_pending_option('events'), false); return [ 'source' => is_array($event) ? 'sync_job' : 'none', 'timestamp' => is_array($event) ? (int) ($event['run_at'] ?? 0) : 0, 'running' => vasp_event_delivery_is_running(), ]; } /** Clear current central and legacy delivery work. */ function vasp_event_clear_delivery_schedules() { delete_option(vasp_scheduler_pending_option('events')); vasp_scheduler_clear(VASP_EVENT_DELIVERY_HOOK, null); } /** Return whether a one-off worker is too overdue to remain trustworthy. */ function vasp_event_delivery_schedule_is_stale($timestamp, $now = null) { if ($timestamp === false) { return false; } $now = $now === null ? time() : (int) $now; return (int) $timestamp < $now - (5 * MINUTE_IN_SECONDS); } /** Request one debounced delivery job. */ function vasp_event_schedule_delivery($delay = 20, $now = null) { if (!vasp_event_delivery_task_is_needed()) { vasp_event_clear_delivery_schedules(); vasp_event_update_delivery_status([ 'pending_hint' => false, 'next_attempt_at' => 0, ]); return true; } if (!vasp_is_event_tracking_enabled()) { return false; } $now = $now === null ? time() : (int) $now; $delay = max(0, (int) $delay); if (vasp_event_has_pending_delivery()) { $delay = max($delay, vasp_event_delivery_quiet_period_delay($now)); } $run_at = $now + $delay; $scheduled = vasp_scheduler_request_service('events', true, $delay); if (!$scheduled) { vasp_event_update_delivery_status(['last_error' => 'schedule_failed']); vasp_log('Event delivery retry could not be scheduled', 'warning'); return false; } if ((int) $delay <= 0) { // A prior accepted batch may retain a future receipt-poll marker. New // outbox rows and explicit administrator requests must make that job // due now; transport retry deadlines are passed in as a positive delay. vasp_scheduler_make_service_due('events'); } $state = vasp_event_delivery_scheduled_state(); vasp_event_update_delivery_status([ 'next_attempt_at' => vasp_scheduler_service_is_running('events') ? $run_at : (int) ($state['timestamp'] ?? $run_at), ]); return true; } /** Retain one delayed follow-up selected by the active worker. */ function vasp_event_schedule_delivery_after_worker($delay) { if (!vasp_event_delivery_task_is_needed() || !vasp_is_event_tracking_enabled()) { return false; } $delay = max(1, (int) $delay); if (vasp_event_has_pending_delivery()) { $delay = max($delay, vasp_event_delivery_quiet_period_delay()); } $run_at = time() + $delay; $scheduled = vasp_scheduler_request_service('events', false, $delay); if ($scheduled) { $state = vasp_event_delivery_scheduled_state(); vasp_event_update_delivery_status([ 'next_attempt_at' => vasp_scheduler_service_is_running('events') ? $run_at : (int) ($state['timestamp'] ?? $run_at), ]); } return $scheduled; } /** Restore a missing or stale one-off delivery while work is known to remain. */ function vasp_event_reconcile_delivery_schedule() { $pending = vasp_event_delivery_task_is_needed(); vasp_event_update_delivery_status(['pending_hint' => $pending]); if (!$pending) { vasp_event_clear_delivery_schedules(); return true; } if (!vasp_is_event_tracking_enabled()) { vasp_event_clear_delivery_schedules(); return true; } $status = vasp_event_get_delivery_status(); $scheduled_state = vasp_event_delivery_scheduled_state(); $next = (int) ($scheduled_state['timestamp'] ?? 0); $missing = ($scheduled_state['source'] ?? 'none') === 'none'; $stale = $next > 0 && vasp_event_delivery_schedule_is_stale($next); if (($missing || $stale) && !vasp_event_delivery_is_running() ) { $retry_deadline = max( (int) ($status['next_attempt_at'] ?? 0), vasp_event_delivery_retry_not_before() ); $retry_delay = max(5, $retry_deadline - time()); vasp_event_schedule_delivery($retry_delay); } return true; } /** Cancel future work and invalidate any worker that has not acknowledged yet. */ function vasp_event_deactivate_delivery() { vasp_event_rotate_delivery_generation(); vasp_event_clear_delivery_schedules(); vasp_event_update_delivery_status([ 'next_attempt_at' => 0, 'retry_not_before' => 0, ]); } /** Mark one bounded delivery worker as active. */ function vasp_event_acquire_delivery_lock() { $token = vasp_scheduler_acquire_claim(VASP_EVENT_DELIVERY_LOCK_OPTION, 5 * MINUTE_IN_SECONDS); return $token === '' ? false : $token; } /** Clear the active marker only when this request owns it. */ function vasp_event_release_delivery_lock($token) { return $token !== '' && vasp_scheduler_release_claim(VASP_EVENT_DELIVERY_LOCK_OPTION, (string) $token); } /** Return whether a delivery worker is currently marked active. */ function vasp_event_delivery_is_running() { $claim = get_option(VASP_EVENT_DELIVERY_LOCK_OPTION, false); return is_array($claim) && (int) ($claim['expires_at'] ?? 0) > time(); } /** Return whether at least one vetted outbox row is pending. */ function vasp_event_has_pending_delivery() { global $wpdb; $vasp_index_table = vasp_event_index_table(); if (!vasp_event_storage_schema_ready()) { return false; } return (bool) $wpdb->get_var($wpdb->prepare( "SELECT event_id FROM %i WHERE delivery_status = 'pending' ORDER BY event_id ASC LIMIT 1", $vasp_index_table )); } /** Read one bounded ordered slice from the event-index outbox. */ function vasp_event_delivery_rows($limit = VASP_EVENT_DELIVERY_BATCH_SIZE) { global $wpdb; $vasp_index_table = vasp_event_index_table(); if (!vasp_event_storage_schema_ready()) { return []; } $limit = max(1, min(VASP_EVENT_DELIVERY_BATCH_SIZE, (int) $limit)); return $wpdb->get_results($wpdb->prepare( "SELECT event_id, event_uid, occurred_at, event_type, canonical_url, session_id, wp_user_id, country, language, is_internal, payload FROM %i WHERE delivery_status = 'pending' ORDER BY event_id ASC LIMIT %d", $vasp_index_table, $limit ), ARRAY_A); } /** Mark exact pending outbox rows as acknowledged or discarded. */ function vasp_event_mark_delivery_rows($event_ids, $status) { global $wpdb; $vasp_index_table = vasp_event_index_table(); $event_ids = array_values(array_unique(array_filter(array_map('absint', (array) $event_ids)))); if (!$event_ids || !in_array($status, ['acknowledged', 'discarded'], true)) { return $event_ids === []; } $placeholders = implode(',', array_fill(0, count($event_ids), '%d')); if ($status === 'acknowledged') { $updated = $wpdb->query($wpdb->prepare( "UPDATE %i SET delivery_status = %s, delivered_at = %s WHERE delivery_status = 'pending' AND event_id IN ({$placeholders})", array_merge([$vasp_index_table, $status, current_time('mysql')], $event_ids) )); } else { $updated = $wpdb->query($wpdb->prepare( "UPDATE %i SET delivery_status = %s, delivered_at = NULL WHERE delivery_status = 'pending' AND event_id IN ({$placeholders})", array_merge([$vasp_index_table, $status], $event_ids) )); } return $updated !== false && !$wpdb->last_error; } /** Remove request-identifying fields before legacy-row vetting. */ function vasp_event_delivery_scrub_data($value) { if (!is_array($value)) { return $value; } $clean = []; foreach ($value as $key => $child) { if (is_string($key) && vasp_event_is_private_data_key($key)) { continue; } $clean[$key] = vasp_event_delivery_scrub_data($child); } return $clean; } /** Return the producer owning one activity kind. */ function vasp_event_delivery_source_system($event_type) { return preg_match('/^(?:cart|checkout|order)\./', (string) $event_type) ? 'woocommerce' : 'wordpress'; } /** Return a bounded enum-like label, or null for free text. */ function vasp_event_delivery_safe_label($value, $maximum = 64) { if (!is_scalar($value)) { return null; } $value = strtolower(trim((string) $value)); return $value !== '' && preg_match('/^[a-z0-9._-]+$/', $value) ? substr($value, 0, max(1, (int) $maximum)) : null; } /** Copy one allowlisted finite numeric dimension. */ function vasp_event_delivery_copy_number(&$target, $target_key, $data, $source_key) { if (isset($data[$source_key]) && is_numeric($data[$source_key]) && is_finite((float) $data[$source_key])) { $target[$target_key] = (float) $data[$source_key]; } } /** Return the first finite number from a list of safe source values. */ function vasp_event_delivery_first_number($values) { foreach ((array) $values as $value) { if ($value !== null && is_numeric($value) && is_finite((float) $value)) { return (float) $value; } } return null; } /** Return one finite number inside the activity contract's numeric bounds. */ function vasp_event_delivery_bounded_number($value, $minimum, $maximum) { if (!is_numeric($value) || !is_finite((float) $value)) { return null; } $number = (float) $value; return $number >= (float) $minimum && $number <= (float) $maximum ? $number : null; } /** Return bounded display text without accepting arrays or object coercion. */ function vasp_event_delivery_safe_text($value, $maximum = 256) { if (!is_string($value)) { return null; } $value = trim(sanitize_text_field($value)); if ($value === '') { return null; } $maximum = max(1, (int) $maximum); if (function_exists('mb_substr')) { return mb_substr($value, 0, $maximum, 'UTF-8'); } $characters = []; return preg_match_all('/./us', $value, $characters) !== false ? implode('', array_slice($characters[0], 0, $maximum)) : substr($value, 0, $maximum); } /** Return a same-site product URL without query or fragment data. */ function vasp_event_delivery_product_url($value) { $url = vasp_event_normalize_page_url($value); if ($url === false) { return null; } $parts = wp_parse_url($url); if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return null; } $port = isset($parts['port']) ? ':' . (int) $parts['port'] : ''; $path = isset($parts['path']) && $parts['path'] !== '' ? $parts['path'] : '/'; return substr(strtolower((string) $parts['scheme']) . '://' . $parts['host'] . $port . $path, 0, 2048); } /** Build one strict typed product object for a cart mutation. */ function vasp_event_delivery_product($event_type, $data) { if (!in_array($event_type, ['cart.added', 'cart.removed', 'cart.updated'], true)) { return null; } $product_id = isset($data['product_id']) && vasp_event_is_integer_value($data['product_id'], 1) ? (int) $data['product_id'] : 0; $variation_id = isset($data['variation_id']) && vasp_event_is_integer_value($data['variation_id'], 0) ? (int) $data['variation_id'] : 0; $quantity_source = $event_type === 'cart.updated' ? ($data['new_quantity'] ?? null) : ($data['quantity'] ?? null); $quantity = vasp_event_delivery_bounded_number($quantity_source, 0, 1000000); $name = vasp_event_delivery_safe_text($data['product_title'] ?? null, 200); $url = vasp_event_delivery_product_url($data['product_url'] ?? null); if ($product_id <= 0 || $quantity === null || $name === null || $url === null) { return null; } return [ 'productId' => $product_id, 'variationId' => $variation_id, 'name' => $name, 'url' => $url, ]; } /** Build the bounded post-mutation cart snapshot for a cart activity. */ function vasp_event_delivery_cart($event_type, $data) { if (!in_array($event_type, [ 'cart.added', 'cart.removed', 'cart.updated', 'cart.coupon_applied', 'cart.coupon_removed', ], true) || empty($data['cart_snapshot']) || !is_array($data['cart_snapshot'])) { return null; } $snapshot = $data['cart_snapshot']; $currency = strtoupper((string) ($snapshot['currency'] ?? '')); $subtotal = vasp_event_delivery_bounded_number($snapshot['subtotal'] ?? null, 0, 1000000000000); $total = vasp_event_delivery_bounded_number($snapshot['total'] ?? null, 0, 1000000000000); $total_items = vasp_event_delivery_bounded_number($snapshot['total_items'] ?? null, 0, 1000000); if (!preg_match('/^[A-Z]{3}$/', $currency) || $subtotal === null || $total === null || $total_items === null || !isset($snapshot['items']) || !is_array($snapshot['items']) || count($snapshot['items']) > 100) { return null; } $items = []; foreach ($snapshot['items'] as $item) { if (!is_array($item) || !isset($item['product_id']) || !vasp_event_is_integer_value($item['product_id'], 1)) { return null; } $variation_id = isset($item['variation_id']) && vasp_event_is_integer_value($item['variation_id'], 0) ? (int) $item['variation_id'] : 0; $name = vasp_event_delivery_safe_text($item['product_title'] ?? $item['product_name'] ?? null, 200); $url = vasp_event_delivery_product_url($item['product_url'] ?? null); $quantity = vasp_event_delivery_bounded_number($item['quantity'] ?? null, 0, 1000000); $unit_price = vasp_event_delivery_bounded_number($item['price'] ?? null, 0, 1000000000000); $line_total = vasp_event_delivery_bounded_number($item['line_total'] ?? null, 0, 1000000000000); if ($name === null || $url === null || $quantity === null || $unit_price === null || $line_total === null) { return null; } $items[] = [ 'productId' => (int) $item['product_id'], 'variationId' => $variation_id, 'name' => $name, 'url' => $url, 'quantity' => $quantity, 'unitPrice' => $unit_price, 'lineTotal' => $line_total, ]; } return [ 'currency' => $currency, 'subtotal' => $subtotal, 'total' => $total, 'totalItems' => $total_items, 'items' => $items, ]; } /** Build the documented safe dimensions for one known activity kind. */ function vasp_event_delivery_dimensions($event_type, $data, $row) { $dimensions = [ 'country' => vasp_event_normalize_country($row['country'] ?? 'ZZ'), 'language' => strtolower(substr(sanitize_text_field((string) ($row['language'] ?? 'unknown')), 0, 20)), 'internal' => !empty($row['is_internal']), ]; $label_fields = []; $number_fields = []; $allow_currency = false; $allow_has_product = false; switch ($event_type) { case 'auth.login': $label_fields = ['login_method']; break; case 'auth.logout': $label_fields = ['logout_method']; break; case 'cart.added': case 'cart.removed': $number_fields = ['quantity' => 'quantity', 'cartItemCount' => 'cart_items_count', 'value' => 'order_total']; $allow_currency = true; $allow_has_product = true; break; case 'cart.updated': $number_fields = ['oldQuantity' => 'old_quantity', 'newQuantity' => 'new_quantity', 'cartItemCount' => 'cart_items_count', 'value' => 'order_total']; $allow_currency = true; $allow_has_product = true; break; case 'cart.coupon_applied': case 'cart.coupon_removed': case 'checkout.started': case 'order.completed': $number_fields = ['itemCount' => 'item_count', 'cartItemCount' => 'cart_items_count', 'value' => 'order_total']; $allow_currency = true; $allow_has_product = true; break; } foreach ($label_fields as $field) { $label = vasp_event_delivery_safe_label($data[$field] ?? null); if ($label !== null) { $dimensions[$field] = $label; } } foreach ($number_fields as $target_key => $source_key) { vasp_event_delivery_copy_number($dimensions, $target_key, $data, $source_key); } $cart_snapshot = isset($data['cart_snapshot']) && is_array($data['cart_snapshot']) ? $data['cart_snapshot'] : []; if (isset($number_fields['cartItemCount']) && !isset($dimensions['cartItemCount'])) { $cart_item_count = vasp_event_delivery_first_number([$cart_snapshot['total_items'] ?? null]); if ($cart_item_count !== null) { $dimensions['cartItemCount'] = $cart_item_count; } } if (isset($number_fields['value']) && !isset($dimensions['value'])) { $value = vasp_event_delivery_first_number([$data['cart_total'] ?? null, $cart_snapshot['total'] ?? null]); if ($value !== null) { $dimensions['value'] = $value; } } if ($allow_currency) { $currency = strtoupper((string) ($data['currency'] ?? $cart_snapshot['currency'] ?? '')); if (preg_match('/^[A-Z]{3}$/', $currency)) { $dimensions['currency'] = $currency; } } if ($allow_has_product && (isset($data['has_product']) || isset($data['product_id']))) { $dimensions['hasProduct'] = isset($data['has_product']) ? (bool) $data['has_product'] : (int) $data['product_id'] > 0; } return $dimensions; } /** Return stable allowlisted object and lifecycle correlations. */ function vasp_event_delivery_correlations($event_type, $data) { $correlations = []; if (in_array($event_type, ['cart.added', 'cart.removed', 'cart.updated'], true)) { foreach (['product_id' => 'productId', 'variation_id' => 'variationId'] as $source => $target) { if (isset($data[$source]) && vasp_event_is_integer_value($data[$source], $source === 'variation_id' ? 0 : 1)) { $correlations[$target] = (int) $data[$source]; } } } if (in_array($event_type, ['checkout.started', 'order.completed'], true) && isset($data['order_id']) && vasp_event_is_integer_value($data['order_id'], 1)) { $correlations['orderId'] = (int) $data['order_id']; } return $correlations; } /** Isolated request builder for the generic customer-activity API. */ function vasp_event_delivery_envelope($activities) { $activities = array_values((array) $activities); foreach ($activities as &$activity) { if (!is_array($activity)) { continue; } // PHP encodes an empty array as JSON [], but the Gateway contract // requires these fields to remain JSON objects even when empty. foreach (['correlations', 'dimensions'] as $object_field) { if (isset($activity[$object_field]) && is_array($activity[$object_field]) && !$activity[$object_field] ) { $activity[$object_field] = (object) []; } } } unset($activity); return ['schemaVersion' => 1, 'activities' => $activities]; } /** Build a bounded privacy-safe summary for delivery logs. */ function vasp_event_delivery_batch_log_context($activities) { $source_counts = []; $kind_counts = []; $source_event_ids = []; $activity_count = 0; foreach (array_slice(array_values((array) $activities), 0, 100) as $activity) { if (!is_array($activity)) { continue; } $activity_count++; $source = vasp_event_delivery_safe_label($activity['sourceSystem'] ?? null, 32); $kind = vasp_event_delivery_safe_label($activity['kind'] ?? null, 64); if ($source !== null) { $source_counts[$source] = (int) ($source_counts[$source] ?? 0) + 1; } if ($kind !== null) { $kind_counts[$kind] = (int) ($kind_counts[$kind] ?? 0) + 1; } $source_event_id = strtolower((string) ($activity['sourceEventId'] ?? '')); if (preg_match('/^[a-f0-9]{64}$/', $source_event_id)) { $source_event_ids[] = $source_event_id; } } ksort($source_counts); ksort($kind_counts); return [ 'activity_count' => $activity_count, 'source_counts' => $source_counts, 'kind_counts' => $kind_counts, 'activity_batch_id' => $source_event_ids ? substr(hash('sha256', implode("\n", $source_event_ids)), 0, 16) : '', ]; } /** Return the bounded retry count at which one terminal error is emitted. */ function vasp_event_delivery_retry_exhaustion_threshold() { return max(2, min(10, (int) apply_filters('vasp_event_delivery_retry_exhaustion_threshold', 5))); } /** Select the one permitted log severity for a failed delivery attempt. */ function vasp_event_delivery_failure_log_action($failure_count, $already_reported) { $failure_count = max(1, (int) $failure_count); if ($failure_count >= vasp_event_delivery_retry_exhaustion_threshold() && !$already_reported) { return 'error'; } return $failure_count === 1 ? 'warning' : 'debug'; } /** Return completion log levels: one info, plus warning only when pending. */ function vasp_event_delivery_completion_log_levels($gateway_pending) { return (int) $gateway_pending > 0 ? ['info', 'warning'] : ['info']; } /** Convert one indexed row to the generic authenticated activity contract. */ function vasp_event_delivery_item($row, &$discard_reason = null) { $discard_reason = null; $data = json_decode((string) ($row['payload'] ?? ''), true); $data = is_array($data) ? $data : []; if (strtolower((string) ($data['delivery_scope'] ?? '')) === 'local') { $discard_reason = 'local_only'; return false; } $data = vasp_event_delivery_scrub_data($data); $event_type = (string) ($row['event_type'] ?? ''); $url = (string) ($row['canonical_url'] ?? ''); $session_id = (string) ($row['session_id'] ?? ''); $event_uid = strtolower((string) ($row['event_uid'] ?? '')); $occurred = date_create_immutable_from_format( '!Y-m-d H:i:s', (string) ($row['occurred_at'] ?? ''), wp_timezone() ); $now = time(); if (!vasp_event_validate_payload($event_type, $data, $url)) { $discard_reason = 'invalid_payload'; return false; } if (!wp_is_uuid($session_id, 4)) { $discard_reason = 'invalid_session'; return false; } if (preg_match('/^[a-f0-9]{64}$/', $event_uid) !== 1) { $discard_reason = 'invalid_uid'; return false; } if (!$occurred) { $discard_reason = 'invalid_timestamp'; return false; } if ($occurred->getTimestamp() < $now - (vasp_event_retention_days() * DAY_IN_SECONDS)) { $discard_reason = 'outside_retention'; return false; } if ($occurred->getTimestamp() > $now + (5 * MINUTE_IN_SECONDS)) { $discard_reason = 'future_timestamp'; return false; } $wp_user_id = (int) ($row['wp_user_id'] ?? 0); $activity = [ 'sourceEventId' => $event_uid, 'sourceSystem' => vasp_event_delivery_source_system($event_type), 'channel' => 'web', 'kind' => $event_type, 'occurredAt' => $occurred->setTimezone(new DateTimeZone('UTC'))->format(DATE_ATOM), 'visitorId' => strtolower($session_id), 'sessionId' => strtolower($session_id), 'correlations' => vasp_event_delivery_correlations($event_type, $data), 'dimensions' => vasp_event_delivery_dimensions($event_type, $data, $row), ]; if ($wp_user_id > 0) { $activity['externalSubject'] = [ // The stored identifier is always the local WordPress user ID, // including for WooCommerce hooks. Keep the provider aligned with // WebChat CustomerIdentified instead of creating a second subject. 'provider' => 'wordpress_user', 'id' => (string) $wp_user_id, ]; } $product = vasp_event_delivery_product($event_type, $data); if ($product !== null) { $activity['product'] = $product; } $cart = vasp_event_delivery_cart($event_type, $data); if ($cart !== null) { $activity['cart'] = $cart; } return $activity; } /** Return the bounded exponential retry delay in seconds. */ function vasp_event_delivery_retry_delay($failure_count) { $exponent = max(0, min(4, (int) $failure_count - 1)); return min(15 * MINUTE_IN_SECONDS, MINUTE_IN_SECONDS * (2 ** $exponent)); } /** Return whether the persisted automatic-attempt deadline has arrived. */ function vasp_event_delivery_attempt_is_due($force = false, $now = null) { $now = $now === null ? time() : (int) $now; if (vasp_event_delivery_quiet_period_delay($now) > 0) { return false; } if ($force) { return true; } return vasp_event_delivery_retry_not_before() <= $now; } /** Record a failed attempt and ensure a retry exists. */ function vasp_event_delivery_failed($error_code, $event_count, $batch_context = [], $origin_logged = false) { $vasp_error_details = is_wp_error($error_code) ? vasp_scheduler_error_details($error_code) : []; $error_code = is_wp_error($error_code) ? vasp_event_delivery_reason_from_error($error_code) : $error_code; $status = vasp_event_get_delivery_status(); $failures = (int) $status['consecutive_failures'] + 1; $already_reported = !empty($status['retry_exhaustion_reported']); $log_action = vasp_event_delivery_failure_log_action($failures, $already_reported); $exhausted_now = $log_action === 'error'; $retry_delay = vasp_event_delivery_retry_delay($failures); vasp_event_update_delivery_status([ 'last_error' => sanitize_key((string) $error_code), 'last_batch_size' => max(0, (int) $event_count), 'consecutive_failures' => $failures, 'pending_hint' => true, 'retry_exhaustion_reported' => $already_reported || $exhausted_now, 'retry_not_before' => time() + $retry_delay, ]); $log_context = array_merge((array) $batch_context, [ 'activity_count' => max(0, (int) $event_count), 'failure_reason' => sanitize_key((string) $error_code), 'attempt' => $failures, 'retry_delay_seconds' => $retry_delay, ]); if ($origin_logged) { // The originating WP_Error already owns the warning/error entry. // Keep retry coordination at debug level without duplicating it. vasp_log('Event delivery retry scheduled after reported failure', 'debug', $log_context); } elseif ($log_action === 'error') { // vasp_create_error() owns the single terminal error log. Pending rows // remain durable and the capped recovery schedule continues. vasp_create_error(VASP_ERROR_EVENT_DELIVERY_FAILED, array_merge($log_context, [ 'component' => 'event_delivery', ])); } elseif ($log_action === 'warning') { vasp_log('Event delivery deferred for retry', 'warning', $log_context); } else { vasp_log('Event delivery retry remains deferred', 'debug', $log_context); } vasp_event_schedule_delivery_after_worker($retry_delay); if ($vasp_error_details) { vasp_scheduler_report_error('events', (string) $error_code, true, $vasp_error_details); } return false; } /** Translate internal delivery state into one safe public error code. */ function vasp_event_delivery_public_error_code($sync_status) { $sync_status = is_array($sync_status) ? $sync_status : []; $last_error = sanitize_key((string) ($sync_status['last_error'] ?? '')); if (!empty($sync_status['in_progress']) || ($sync_status['state'] ?? '') === 'delivering') { return VASP_ERROR_EVENT_DELIVERY_BUSY; } $codes = [ 'connection_failed' => VASP_ERROR_CONNECTION_FAILED, 'timeout' => VASP_ERROR_TIMEOUT, 'vasp_error_api_request_failed' => VASP_ERROR_API_REQUEST_FAILED, 'vasp_error_api_response_error' => VASP_ERROR_API_RESPONSE_ERROR, 'vasp_http_invalid_json' => VASP_ERROR_API_RESPONSE_ERROR, 'vasp_http_status_error' => VASP_ERROR_API_RESPONSE_ERROR, 'api_error' => VASP_ERROR_API_ERROR, 'missing_endpoint' => VASP_ERROR_MISSING_ENDPOINT, 'invalid_token' => VASP_ERROR_INVALID_TOKEN, 'missing_token' => VASP_ERROR_MISSING_TOKEN, 'token_expired' => VASP_ERROR_TOKEN_EXPIRED, 'refresh_failed' => VASP_ERROR_REFRESH_FAILED, 'no_refresh_token' => VASP_ERROR_NO_REFRESH_TOKEN, 'rate_limited' => VASP_ERROR_RATE_LIMITED, 'too_many_requests' => VASP_ERROR_TOO_MANY_REQUESTS, 'incomplete_acknowledgement' => VASP_ERROR_EVENT_DELIVERY_INCOMPLETE_ACKNOWLEDGEMENT, 'discard_update_failed' => VASP_ERROR_EVENT_DELIVERY_STATE_UPDATE_FAILED, 'acknowledgement_update_failed' => VASP_ERROR_EVENT_DELIVERY_STATE_UPDATE_FAILED, 'schedule_failed' => VASP_ERROR_EVENT_DELIVERY_SCHEDULE_FAILED, 'unexpected_exception' => VASP_ERROR_EVENT_DELIVERY_UNEXPECTED, ]; return $codes[$last_error] ?? VASP_ERROR_EVENT_DELIVERY_INTERRUPTED; } /** Reduce a logged WP_Error to the safe reason persisted for delivery health. */ function vasp_event_delivery_reason_from_error($error) { if (!is_wp_error($error)) { return 'unexpected_exception'; } $data = (array) $error->get_error_data(); $status = max(0, (int) ($data['status'] ?? 0)); if ($status === 401) { return VASP_ERROR_INVALID_TOKEN; } if ($status === 408 || $status === 504) { return VASP_ERROR_TIMEOUT; } if ($status === 429) { return VASP_ERROR_RATE_LIMITED; } return sanitize_key((string) $error->get_error_code()); } /** Return whether replaying this exact batch cannot repair the contract. */ function vasp_event_delivery_failure_is_permanent($error): bool { if (!is_wp_error($error)) { return false; } $data = (array) $error->get_error_data(); if (array_key_exists('retryable', $data)) { return $data['retryable'] === false; } $status = (int) ($data['status'] ?? 0); return in_array($status, [400, 404, 413, 415, 422], true); } /** Return the allowlisted Gateway contract code carried by a failed request. */ function vasp_event_delivery_contract_error_code($error): string { $data = is_wp_error($error) ? (array) $error->get_error_data() : []; $code = sanitize_key((string) ($data['error_code'] ?? '')); return strlen($code) <= 64 ? $code : ''; } /** Return normalized outstanding Gateway receipts, including pre-ledger state. */ function vasp_event_gateway_receipts($status = null): array { $status = is_array($status) ? $status : vasp_event_get_delivery_status(); $receipts = is_array($status['gateway_receipts'] ?? null) ? $status['gateway_receipts'] : []; if (!$receipts && preg_match('/^[a-f0-9]{16,64}$/i', (string) ($status['gateway_batch_id'] ?? '')) === 1 && in_array((string) ($status['gateway_status'] ?? ''), ['queued', 'processing'], true) ) { $receipts[] = [ 'batch_id' => (string) $status['gateway_batch_id'], 'status' => (string) $status['gateway_status'], 'next_at' => max(0, (int) ($status['gateway_status_next_at'] ?? 0)), 'accepted_at' => max(0, (int) ($status['last_success'] ?? time())), 'updated_at' => (string) ($status['gateway_updated_at'] ?? ''), 'processed' => max(0, (int) ($status['gateway_published'] ?? 0)), 'pending' => max(0, (int) ($status['gateway_pending'] ?? 0)), 'quarantined' => max(0, (int) ($status['gateway_quarantined'] ?? 0)), 'rejected' => max(0, (int) ($status['gateway_rejected'] ?? 0)), ]; } $observation_cutoff = time() - VASP_EVENT_RECEIPT_OBSERVATION_TTL; return array_values(array_filter($receipts, static function ($receipt) use ($observation_cutoff): bool { if (!is_array($receipt) || preg_match('/^[a-f0-9]{16,64}$/i', (string) ($receipt['batch_id'] ?? '')) !== 1 || !in_array((string) ($receipt['status'] ?? ''), ['queued', 'processing', 'needs_attention'], true) ) { return false; } $receipt_status = (string) ($receipt['status'] ?? ''); $accepted_at = max(0, (int) ($receipt['accepted_at'] ?? 0)); return $receipt_status === 'needs_attention' || $accepted_at >= $observation_cutoff; })); } /** Persist one accepted receipt without making it the transport cursor. */ function vasp_event_gateway_store_receipt(array $receipt, $status = null): array { $status = is_array($status) ? $status : vasp_event_get_delivery_status(); $receipts = vasp_event_gateway_receipts($status); $batch_id = (string) ($receipt['batch_id'] ?? ''); foreach ($receipts as $index => $stored) { if (hash_equals((string) $stored['batch_id'], $batch_id)) { unset($receipts[$index]); } } if (in_array((string) ($receipt['status'] ?? ''), ['queued', 'processing', 'needs_attention'], true)) { $receipts[] = $receipt; } if (count($receipts) > VASP_EVENT_RECEIPT_LEDGER_LIMIT) { $receipts = array_slice($receipts, -VASP_EVENT_RECEIPT_LEDGER_LIMIT); } return array_values($receipts); } /** Return the earliest time at which an active receipt should be refreshed. */ function vasp_event_gateway_status_next_at(array $receipts): int { $next = []; foreach ($receipts as $receipt) { if (in_array((string) ($receipt['status'] ?? ''), ['queued', 'processing'], true)) { $next[] = max(0, (int) ($receipt['next_at'] ?? 0)); } } return $next ? min($next) : 0; } /** Summarize outstanding receipt progress for administrator-facing status. */ function vasp_event_gateway_receipt_summary(array $receipts): array { $summary = [ 'gateway_batch_id' => '', 'gateway_status' => '', 'gateway_updated_at' => '', 'gateway_published' => 0, 'gateway_pending' => 0, 'gateway_quarantined' => 0, 'gateway_rejected' => 0, 'gateway_status_next_at' => vasp_event_gateway_status_next_at($receipts), ]; $selected_priority = 0; foreach ($receipts as $receipt) { $summary['gateway_published'] += max(0, (int) ($receipt['processed'] ?? 0)); $summary['gateway_pending'] += max(0, (int) ($receipt['pending'] ?? 0)); $summary['gateway_quarantined'] += max(0, (int) ($receipt['quarantined'] ?? 0)); $summary['gateway_rejected'] += max(0, (int) ($receipt['rejected'] ?? 0)); $receipt_status = (string) ($receipt['status'] ?? ''); $priority = $receipt_status === 'needs_attention' ? 3 : ($receipt_status === 'processing' ? 2 : 1); if ($priority > $selected_priority) { $selected_priority = $priority; $summary['gateway_batch_id'] = (string) ($receipt['batch_id'] ?? ''); $summary['gateway_status'] = $receipt_status; $summary['gateway_updated_at'] = (string) ($receipt['updated_at'] ?? ''); } } return $summary; } /** Return whether any accepted Gateway batch still needs observation. */ function vasp_event_gateway_status_refresh_needed(): bool { foreach (vasp_event_gateway_receipts() as $receipt) { if (in_array((string) ($receipt['status'] ?? ''), ['queued', 'processing'], true)) { return true; } } return false; } /** Return whether an accepted batch reached a terminal attention state. */ function vasp_event_gateway_attention_needed(): bool { foreach (vasp_event_gateway_receipts() as $receipt) { if ((string) ($receipt['status'] ?? '') === 'needs_attention') { return true; } } return false; } /** Build the status URL from the configured Gateway endpoint, never receipt input. */ function vasp_event_gateway_status_url(string $batch_id) { if (preg_match('/^[a-f0-9]{16,64}$/i', $batch_id) !== 1) { return new WP_Error('vasp_event_batch_id_invalid'); } $batch_url = vasp_get_endpoint_url('events_batch_endpoint'); if (is_wp_error($batch_url)) { return $batch_url; } $parts = wp_parse_url((string) $batch_url); if (!is_array($parts) || !in_array(strtolower((string) ($parts['scheme'] ?? '')), ['https', 'http'], true) || empty($parts['host'])) { return new WP_Error('vasp_event_status_url_invalid'); } $path = rtrim((string) ($parts['path'] ?? ''), '/'); if (substr($path, -6) !== '/batch') { return new WP_Error('vasp_event_status_url_invalid'); } $path = substr($path, 0, -6) . '/batches/' . rawurlencode($batch_id); $port = isset($parts['port']) ? ':' . (int) $parts['port'] : ''; return strtolower((string) $parts['scheme']) . '://' . $parts['host'] . $port . $path; } /** Refresh one accepted receipt through the background event worker. */ function vasp_event_refresh_gateway_status() { if (!vasp_event_gateway_status_refresh_needed()) { return true; } $status = vasp_event_get_delivery_status(); $receipts = vasp_event_gateway_receipts($status); $due_index = null; foreach ($receipts as $index => $receipt) { if (in_array((string) ($receipt['status'] ?? ''), ['queued', 'processing'], true) && (int) ($receipt['next_at'] ?? 0) <= time() ) { $due_index = $index; break; } } if ($due_index === null) { return true; } $receipt = $receipts[$due_index]; $batch_id = (string) $receipt['batch_id']; $url = vasp_event_gateway_status_url($batch_id); if (is_wp_error($url)) { return $url; } $token = vasp_resolve_access_token(); if (is_wp_error($token)) { return $token; } $response = vasp_http_request_url($url, [ 'method' => 'GET', 'headers' => ['Authorization' => 'Bearer ' . $token], 'timeout' => 10, 'sslverify' => vasp_get_config('ssl_verify'), ]); if (is_wp_error($response)) { $error_data = (array) $response->get_error_data(); if ((int) ($error_data['status'] ?? 0) === 404) { unset($receipts[$due_index]); $receipts = array_values($receipts); vasp_event_update_delivery_status(array_merge( vasp_event_gateway_receipt_summary($receipts), [ 'gateway_status_url' => $receipts ? (string) ($status['gateway_status_url'] ?? '') : '', 'gateway_receipts' => $receipts, ] )); return true; } return $response; } if (!is_array($response) || ($response['success'] ?? null) !== true || !hash_equals($batch_id, (string) ($response['batchId'] ?? ''))) { return new WP_Error(VASP_ERROR_INVALID_RESPONSE, __('The processing status of the latest events could not be confirmed.', 'valuespace')); } $gateway_status = (string) ($response['status'] ?? ''); if (!in_array($gateway_status, ['queued', 'processing', 'processed', 'needs_attention'], true)) { return new WP_Error(VASP_ERROR_INVALID_RESPONSE, __('The processing status of the latest events could not be confirmed.', 'valuespace')); } $updated_receipt = [ 'batch_id' => $batch_id, 'status' => $gateway_status, 'next_at' => in_array($gateway_status, ['queued', 'processing'], true) ? time() + MINUTE_IN_SECONDS : 0, 'accepted_at' => max(0, (int) ($receipt['accepted_at'] ?? time())), 'updated_at' => sanitize_text_field((string) ($response['updatedAtUtc'] ?? '')), 'processed' => max(0, (int) ($response['processed'] ?? 0)), 'pending' => max(0, (int) ($response['queued'] ?? 0)) + max(0, (int) ($response['processing'] ?? 0)), 'quarantined' => max(0, (int) ($response['quarantined'] ?? 0)), 'rejected' => max(0, (int) ($response['rejected'] ?? 0)), ]; $receipts = vasp_event_gateway_store_receipt($updated_receipt, $status); $receipt_summary = $receipts ? vasp_event_gateway_receipt_summary($receipts) : [ 'gateway_batch_id' => $batch_id, 'gateway_status' => $gateway_status, 'gateway_updated_at' => $updated_receipt['updated_at'], 'gateway_published' => $updated_receipt['processed'], 'gateway_pending' => $updated_receipt['pending'], 'gateway_quarantined' => $updated_receipt['quarantined'], 'gateway_rejected' => $updated_receipt['rejected'], 'gateway_status_next_at' => 0, ]; vasp_event_update_delivery_status(array_merge($receipt_summary, [ 'gateway_receipts' => $receipts, ])); return true; } /** Return the standardized public code and localized message for a failed attempt. */ function vasp_event_delivery_public_error($sync_status) { if (sanitize_key((string) (($sync_status['last_error'] ?? ''))) === 'unsupported_schema') { return [ 'code' => VASP_ERROR_EVENT_DELIVERY_INCOMPLETE_ACKNOWLEDGEMENT, 'message' => __('Update the ValueSpace plugin, then try sending the events again.', 'valuespace'), ]; } $code = vasp_event_delivery_public_error_code($sync_status); return [ 'code' => $code, 'message' => vasp_get_error_message($code), ]; } /** Deliver one outbox slice; stable event UIDs make every retry idempotent. */ function vasp_event_deliver_pending($force = false, $timeout = 15, $allow_refresh = true) { if (!vasp_event_has_pending_delivery() || !vasp_is_event_tracking_enabled() || !function_exists('vasp_valuespace_is_connected') || !vasp_valuespace_is_connected() || !vasp_event_delivery_attempt_is_due((bool) $force) ) { return false; } $generation = vasp_event_delivery_generation(); $lock = vasp_event_acquire_delivery_lock(); if (!$lock) { vasp_log('Event delivery deferred because another worker is active', 'debug', [ 'retry_delay_seconds' => MINUTE_IN_SECONDS, ]); vasp_event_schedule_delivery_after_worker(MINUTE_IN_SECONDS); return false; } try { if (!vasp_event_delivery_worker_is_current($generation)) { return false; } $started = microtime(true); vasp_event_update_delivery_status([ 'last_attempt' => time(), 'next_attempt_at' => 0, ]); $delivery_status = vasp_event_get_delivery_status(); $isolation_limit = max(0, min(VASP_EVENT_DELIVERY_BATCH_SIZE, (int) ($delivery_status['isolation_limit'] ?? 0))); $rows = vasp_event_delivery_rows($isolation_limit > 0 ? $isolation_limit : VASP_EVENT_DELIVERY_BATCH_SIZE); if (!$rows) { vasp_event_update_delivery_status([ 'last_error' => '', 'consecutive_failures' => 0, 'pending_hint' => false, 'next_attempt_at' => 0, 'retry_not_before' => 0, ]); return true; } $events = []; $event_ids = []; $discarded_ids = []; $discarded = []; foreach ($rows as $row) { $discard_reason = null; $item = vasp_event_delivery_item($row, $discard_reason); if ($item !== false) { $events[] = $item; $event_ids[] = (int) $row['event_id']; continue; } $discarded_ids[] = (int) $row['event_id']; $reason = $discard_reason ?: 'invalid_event'; $discarded[$reason] = (int) ($discarded[$reason] ?? 0) + 1; } if (!vasp_event_delivery_worker_is_current($generation)) { return false; } if ($discarded_ids && !vasp_event_mark_delivery_rows($discarded_ids, 'discarded')) { return vasp_event_delivery_failed('discard_update_failed', count($rows)); } if ($discarded) { $status = vasp_event_get_delivery_status(); $totals = is_array($status['discarded'] ?? null) ? $status['discarded'] : []; foreach ($discarded as $reason => $count) { $totals[$reason] = (int) ($totals[$reason] ?? 0) + $count; } vasp_event_update_delivery_status([ 'discarded' => $totals, 'discarded_total' => (int) $status['discarded_total'] + count($discarded_ids), ]); vasp_log('Event delivery discarded ineligible indexed rows', 'debug', [ 'discarded' => count($discarded_ids), 'reasons' => array_keys($discarded), ]); } if (!vasp_event_delivery_worker_is_current($generation)) { return false; } $accepted = 0; $duplicate = 0; $gateway_published = 0; $gateway_pending = 0; $response = []; if ($events) { $batch_context = vasp_event_delivery_batch_log_context($events); vasp_log('Event delivery batch prepared for dispatch', 'debug', $batch_context); if (!vasp_scheduler_renew_claim(VASP_EVENT_DELIVERY_LOCK_OPTION, (string) $lock, 5 * MINUTE_IN_SECONDS)) { return vasp_event_delivery_failed('worker_claim_lost', count($events), $batch_context); } $request_headers = []; if (!$allow_refresh) { $request_headers['Authorization'] = 'Bearer ' . vasp_get_stored_access_token(); } $response = vasp_api_request( 'events_batch_endpoint', 'POST', vasp_event_delivery_envelope($events), [], $request_headers, 'application/json', max(1, min(15, (int) $timeout)), 'json', (bool) $allow_refresh ); if (is_wp_error($response)) { if (vasp_event_delivery_failure_is_permanent($response)) { $status = vasp_event_get_delivery_status(); $contract_code = vasp_event_delivery_contract_error_code($response); if ($contract_code === 'unsupported_schema') { $data = (array) $response->get_error_data(); vasp_event_update_delivery_status([ 'last_error' => 'unsupported_schema', 'consecutive_failures' => (int) $status['consecutive_failures'] + 1, 'compatibility_required' => true, 'supported_schema_versions' => array_values(array_unique(array_filter(array_map( 'absint', (array) ($data['supported_schema_versions'] ?? []) )))), 'pending_hint' => true, 'isolation_limit' => 0, 'retry_not_before' => time() + DAY_IN_SECONDS, 'next_attempt_at' => time() + DAY_IN_SECONDS, ]); vasp_event_schedule_delivery_after_worker(DAY_IN_SECONDS); return false; } if (count($event_ids) > 1) { $next_limit = max(1, (int) ceil(count($event_ids) / 2)); vasp_event_update_delivery_status([ 'last_error' => 'isolating_rejected_event', 'consecutive_failures' => (int) $status['consecutive_failures'] + 1, 'compatibility_required' => false, 'pending_hint' => true, 'isolation_limit' => $next_limit, 'retry_not_before' => time() + 5, 'next_attempt_at' => time() + 5, ]); vasp_event_schedule_delivery_after_worker(5); return false; } if (!vasp_event_mark_delivery_rows($event_ids, 'discarded')) { return vasp_event_delivery_failed('discard_update_failed', count($events), $batch_context); } $discarded = is_array($status['discarded'] ?? null) ? $status['discarded'] : []; $reason = vasp_event_delivery_reason_from_error($response); $discarded[$reason] = (int) ($discarded[$reason] ?? 0) + count($event_ids); vasp_event_update_delivery_status([ 'last_error' => '', 'consecutive_failures' => 0, 'discarded' => $discarded, 'discarded_total' => (int) $status['discarded_total'] + count($event_ids), 'gateway_rejected' => count($event_ids), 'isolation_limit' => 0, 'compatibility_required' => false, 'retry_not_before' => 0, ]); vasp_log('Event delivery isolated a permanently rejected batch', 'warning', array_merge($batch_context, [ 'rejected_count' => count($event_ids), 'failure_reason' => $reason, ])); return true; } else { return vasp_event_delivery_failed( $response, count($events), $batch_context, true ); } } if ($events && !vasp_scheduler_renew_claim(VASP_EVENT_DELIVERY_LOCK_OPTION, (string) $lock, 5 * MINUTE_IN_SECONDS)) { return vasp_event_delivery_failed('worker_claim_lost', count($events), $batch_context); } if ($events) { $accepted = (int) ($response['accepted'] ?? 0); $duplicate = (int) ($response['duplicate'] ?? 0); $gateway_published = (int) ($response['published'] ?? 0); $gateway_pending = (int) ($response['pending'] ?? 0); if (empty($response['success']) || $accepted + $duplicate !== count($events)) { return vasp_event_delivery_failed('incomplete_acknowledgement', count($events), $batch_context); } if (!vasp_event_delivery_worker_is_current($generation)) { return false; } if (!vasp_event_mark_delivery_rows($event_ids, 'acknowledged')) { return vasp_event_delivery_failed('acknowledgement_update_failed', count($events), $batch_context); } } $completion_context = array_merge($batch_context, [ 'accepted_count' => $accepted, 'duplicate_count' => $duplicate, 'published_count' => $gateway_published, 'pending_count' => $gateway_pending, ]); foreach (vasp_event_delivery_completion_log_levels($gateway_pending) as $log_level) { vasp_log( $log_level === 'warning' ? 'Event delivery accepted with server publication pending' : 'Event delivery batch acknowledged', $log_level, $completion_context ); } } $status = vasp_event_get_delivery_status(); $has_more = vasp_event_has_pending_delivery(); $gateway_batch_id = isset($response) && preg_match('/^[a-f0-9]{16,64}$/i', (string) ($response['batchId'] ?? '')) ? (string) $response['batchId'] : ''; $gateway_status = isset($response) && in_array((string) ($response['status'] ?? ''), ['queued', 'processing', 'processed', 'needs_attention'], true) ? (string) $response['status'] : ''; $receipts = vasp_event_gateway_receipts($status); if ($gateway_batch_id !== '' && $gateway_status !== '') { $receipts = vasp_event_gateway_store_receipt([ 'batch_id' => $gateway_batch_id, 'status' => $gateway_status, 'next_at' => in_array($gateway_status, ['queued', 'processing'], true) ? time() + MINUTE_IN_SECONDS : 0, 'accepted_at' => time(), 'updated_at' => sanitize_text_field((string) ($response['updatedAtUtc'] ?? '')), 'processed' => max(0, (int) ($response['processed'] ?? $gateway_published)), 'pending' => max(0, (int) ($response['queued'] ?? $gateway_pending)) + max(0, (int) ($response['processing'] ?? 0)), 'quarantined' => max(0, (int) ($response['quarantined'] ?? 0)), 'rejected' => max(0, (int) ($response['rejected'] ?? 0)), ], $status); } $receipt_summary = $receipts ? vasp_event_gateway_receipt_summary($receipts) : []; vasp_event_update_delivery_status(array_merge([ 'last_success' => time(), 'last_error' => '', 'last_batch_size' => count($events), 'last_duration_ms' => (int) round((microtime(true) - $started) * 1000), 'consecutive_failures' => 0, 'retry_exhaustion_reported' => false, 'accepted_total' => (int) $status['accepted_total'] + $accepted, 'duplicate_total' => (int) $status['duplicate_total'] + $duplicate, 'acknowledged_total' => (int) $status['acknowledged_total'] + count($event_ids), 'gateway_published' => $gateway_published, 'gateway_pending' => $gateway_pending, 'gateway_batch_id' => $gateway_batch_id, 'gateway_status' => $gateway_status, 'gateway_status_url' => esc_url_raw((string) ($response['statusUrl'] ?? '')), 'gateway_updated_at' => sanitize_text_field((string) ($response['updatedAtUtc'] ?? '')), 'gateway_quarantined' => max(0, (int) ($response['quarantined'] ?? 0)), 'gateway_rejected' => max(0, (int) ($response['rejected'] ?? 0)), 'gateway_status_next_at' => vasp_event_gateway_status_next_at($receipts), 'gateway_receipts' => $receipts, 'isolation_limit' => 0, 'compatibility_required' => false, 'supported_schema_versions' => [], 'pending_hint' => $has_more, 'retry_not_before' => 0, ], $receipt_summary)); return true; } catch (Throwable $error) { vasp_create_error(VASP_ERROR_EVENT_DELIVERY_UNEXPECTED, [ 'component' => 'event_delivery', 'exception_class' => get_class($error), ]); return vasp_event_delivery_failed( 'unexpected_exception', isset($rows) && is_array($rows) ? count($rows) : 0, [], true ); } finally { vasp_event_release_delivery_lock($lock); } } /** * Run exactly one bounded delivery batch. * * @param bool $manual Whether an administrator explicitly requested the unit. * @param int $timeout Gateway timeout in seconds. * @param bool $allow_refresh Whether the shared HTTP boundary may refresh auth. * @return bool */ function vasp_event_run_send_unit($manual = false, $timeout = 15, $allow_refresh = true) { $vasp_claim_option = vasp_scheduler_running_option('events'); $vasp_claim = vasp_scheduler_acquire_claim($vasp_claim_option, 15 * MINUTE_IN_SECONDS); if ($vasp_claim === '') { return false; } try { vasp_scheduler_refresh_service_options('events'); return (bool) vasp_event_deliver_pending((bool) $manual, $timeout, (bool) $allow_refresh); } finally { vasp_scheduler_release_claim($vasp_claim_option, $vasp_claim); } } /** Return live, privacy-safe synchronization metrics for administrator views. */ function vasp_event_get_sync_status() { global $wpdb; $vasp_index_table = vasp_event_index_table(); $status = vasp_event_get_delivery_status(); $counts = [ 'indexed_count' => 0, 'pending_count' => 0, 'acknowledged_count' => 0, 'discarded_count' => 0, 'ignored_count' => 0, 'oldest_pending' => '', ]; if (vasp_event_storage_schema_ready()) { $row = $wpdb->get_row($wpdb->prepare( 'SELECT COUNT(*) indexed_count, SUM(delivery_status = \'pending\') pending_count, SUM(delivery_status = \'acknowledged\') acknowledged_count, SUM(delivery_status = \'discarded\') discarded_count, SUM(delivery_status = \'ignored\') ignored_count, MIN(CASE WHEN delivery_status = \'pending\' THEN occurred_at END) oldest_pending FROM %i', $vasp_index_table), ARRAY_A ); if (is_array($row)) { foreach (['indexed_count', 'pending_count', 'acknowledged_count', 'discarded_count', 'ignored_count'] as $field) { $counts[$field] = max(0, (int) ($row[$field] ?? 0)); } $counts['oldest_pending'] = (string) ($row['oldest_pending'] ?? ''); } } $configured = vasp_customer_event_tracking_configured(); $active = vasp_is_event_tracking_enabled(); $running = vasp_event_delivery_is_running(); $scheduled_state = vasp_event_delivery_scheduled_state(); $delivery_next_run = (int) ($scheduled_state['timestamp'] ?? 0); if (!$configured) { $state = 'disabled'; } elseif (!$active) { $state = 'paused'; } elseif ($running) { $state = 'delivering'; } elseif ($counts['pending_count'] > 0 && (int) $status['consecutive_failures'] > 0) { $state = 'retrying'; } elseif ($counts['pending_count'] > 0) { $state = 'queued'; } elseif (vasp_event_gateway_attention_needed()) { $state = 'needs_attention'; } else { $state = 'synchronized'; } return array_merge($status, $counts, [ 'state' => $state, 'active' => $active, 'in_progress' => $running, 'next_run' => $delivery_next_run === false ? 0 : (int) $delivery_next_run, 'delivery_next_run' => $delivery_next_run, 'scheduler_source' => (string) ($scheduled_state['source'] ?? 'none'), 'next_attempt_at' => (int) $status['next_attempt_at'], ]); } /** Reconcile raw-event outbox delivery from durable local state only. */ function vasp_event_scheduler_reconcile() { // The normal enablement check refreshes the one-minute configuration cache. return (bool) vasp_event_reconcile_delivery_schedule(); } /** Connection notifications use the shared reconciliation claim as well. */ function vasp_event_reconcile_connected_delivery(): void { vasp_scheduler_reconcile_service('events'); } /** Cancel pending raw-event delivery and invalidate the active worker. */ function vasp_event_scheduler_cancel() { vasp_event_deactivate_delivery(); return true; } /** Run one bounded administrator-requested raw-event delivery unit. */ function vasp_event_scheduler_run_now() { return vasp_event_run_send_unit(true); } /** Execute one due delivery unit and report whether raw outbox work remains. */ function vasp_event_scheduler_execute(): array { // Retention is outbox hygiene, not event derivation. Keep each cleanup unit // bounded and let raw delivery continue regardless of its database outcome. if (function_exists('vasp_event_purge_expired_index')) { try { vasp_event_purge_expired_index(250); } catch (Throwable $error) { // A later one-off delivery can retry cleanup; transport stays available. } } $vasp_gateway_refreshed = vasp_event_refresh_gateway_status(); if (is_wp_error($vasp_gateway_refreshed)) { $vasp_status = vasp_event_get_delivery_status(); $vasp_receipts = vasp_event_gateway_receipts($vasp_status); foreach ($vasp_receipts as &$vasp_receipt) { if (in_array((string) ($vasp_receipt['status'] ?? ''), ['queued', 'processing'], true) && (int) ($vasp_receipt['next_at'] ?? 0) <= time() ) { $vasp_receipt['next_at'] = time() + MINUTE_IN_SECONDS; break; } } unset($vasp_receipt); vasp_event_update_delivery_status([ 'gateway_receipts' => $vasp_receipts, 'gateway_status_next_at' => vasp_event_gateway_status_next_at($vasp_receipts), ]); } $vasp_quiet_delay = vasp_event_delivery_quiet_period_delay(); if ($vasp_quiet_delay > 0 && vasp_event_has_pending_delivery()) { $vasp_pending = vasp_is_event_tracking_enabled() && function_exists('vasp_valuespace_is_connected') && vasp_valuespace_is_connected(); $vasp_status = vasp_event_get_delivery_status(); $vasp_receipt_delay = vasp_event_gateway_status_refresh_needed() ? max(1, (int) ($vasp_status['gateway_status_next_at'] ?? 0) - time()) : $vasp_quiet_delay; return [ 'pending' => $vasp_pending, 'delay' => $vasp_pending ? min($vasp_quiet_delay, $vasp_receipt_delay) : 0, ]; } // Delivery owns validation too: an invalid head slice must be discarded, // not repeatedly inspected while valid events wait behind it. $vasp_delivered = vasp_event_has_pending_delivery() ? vasp_event_deliver_pending(false) : true; $has_work = vasp_event_has_pending_delivery() || vasp_event_gateway_status_refresh_needed(); $pending = $has_work && vasp_is_event_tracking_enabled() && function_exists('vasp_valuespace_is_connected') && vasp_valuespace_is_connected(); $status = vasp_event_get_delivery_status(); if (!$vasp_delivered && !empty($status['last_error'])) { vasp_scheduler_report_error('events', (string) $status['last_error'], true); } $has_local_pending = vasp_event_has_pending_delivery(); $not_before = $has_local_pending ? max((int) ($status['next_attempt_at'] ?? 0), vasp_event_delivery_retry_not_before()) : max((int) ($status['gateway_status_next_at'] ?? 0), vasp_event_delivery_retry_not_before()); return [ 'pending' => $pending, 'delay' => $pending ? max(0, $not_before - time()) : 0, ]; } /** Clear delivery runtime state while invalidating any current worker. */ function vasp_event_reset_delivery_state() { vasp_event_deactivate_delivery(); delete_option(VASP_EVENT_DELIVERY_LOCK_OPTION); delete_option(VASP_EVENT_DELIVERY_STATUS_OPTION); }