$payload, 'destination' => $destination], '', false)) { Logger::error('Could not store the WooCommerce cart update for delivery.'); return false; } if (0 === as_enqueue_async_action(self::HOOK, [$id], self::GROUP)) { delete_option($key); Logger::error('Could not schedule the WooCommerce cart update.'); return false; } return true; } public static function retainSnapshot(string $sessionId, array $payload, string $destination): bool { // Converging on one key lets overlapping requests migrate the same legacy snapshot safely. $id = hash('sha256', (string) wp_json_encode([$destination, $payload])); $key = self::replayPrefix($sessionId) . sprintf('%020d', $payload['revision']) . '_' . $id; $defaultLifetime = (is_user_logged_in() ? 7 : 2) * DAY_IN_SECONDS; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Use WooCommerce's configured session lifetime. $lifetime = (int) apply_filters('wc_session_expiration', $defaultLifetime); $record = [ 'cart' => $payload, 'destination' => $destination, 'expiresAt' => time() + ($lifetime > 0 ? $lifetime : $defaultLifetime), ]; if (add_option($key, $record, '', false) || is_array(get_option($key))) { return true; } Logger::error('Could not retain the WooCommerce cart update for replay.'); return false; } public static function replaySnapshots(string $sessionId, string $destination): bool { foreach (self::optionKeys(self::replayPrefix($sessionId)) as $key) { $record = get_option($key); if (! is_array($record)) { continue; } if ($record['expiresAt'] <= time() || $record['destination'] !== $destination) { delete_option($key); continue; } // Keep the original cart and event IDs so concurrent replays are idempotent in Commerce. if (! self::enqueue($record['cart'], $destination)) { return false; } delete_option($key); } return true; } public static function pruneExpiredSnapshots(): void { foreach (self::optionKeys(self::REPLAY_OPTION_PREFIX) as $key) { $record = get_option($key); if (is_array($record) && $record['expiresAt'] <= time()) { delete_option($key); } } } public static function deliver(string $id, int $attempt = 0): void { $key = self::OPTION_PREFIX . $id; $payload = get_option($key); if (! is_array($payload)) { return; } $retryScheduled = false; try { if (! Options::isEnabled() || ! Options::getBool(Options::SYNC_CARTS) || $payload['destination'] !== (new ConnectionManager())->baseUrl() ) { return; } $result = (new AivieClient())->upsertCart($payload['cart']); if ($result->success) { return; } $delay = self::RETRY_DELAYS[$attempt] ?? null; $retry = 0 === $result->httpCode || 429 === $result->httpCode || $result->isServerError(); $retryScheduled = $retry && null !== $delay && as_schedule_single_action(time() + $delay, self::HOOK, [$id, $attempt + 1], self::GROUP) > 0; if (! $retryScheduled) { Logger::error('Aivie cart delivery failed.', ['http_code' => $result->httpCode, 'attempt' => $attempt + 1]); } } finally { if (! $retryScheduled) { delete_option($key); } } } public static function uninstall(): void { if (function_exists('as_unschedule_all_actions')) { as_unschedule_all_actions(self::HOOK, null, self::GROUP); } foreach (self::optionKeys(self::OPTION_PREFIX) as $key) { delete_option($key); } } private static function replayPrefix(string $sessionId): string { return self::REPLAY_OPTION_PREFIX . hash('sha256', $sessionId) . '_'; } /** @return \Generator */ private static function optionKeys(string $prefix): \Generator { global $wpdb; $pattern = $wpdb->esc_like($prefix) . '%'; $lastKey = ''; do { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Recovery and cleanup need the current list of independently stored options. $keys = $wpdb->get_col($wpdb->prepare( 'SELECT option_name FROM %i WHERE option_name LIKE %s AND option_name > %s ORDER BY option_name LIMIT 100', $wpdb->options, $pattern, $lastKey )); foreach ($keys as $key) { $lastKey = $key; yield $key; } } while (count($keys) === 100); } }