1. <?php
  2. /**
  3. * Simple message queue retrier.
  4. *
  5. * This script assumes a simple message queue implementation where messages
  6. * are stored in an array. It retries failed operations a specified
  7. * number of times.
  8. *
  9. * @param array $queue An array representing the message queue. Each element
  10. * is an associative array containing the message data and
  11. * a 'attempts' key indicating the number of retry attempts.
  12. * @param int $maxAttempts The maximum number of retry attempts allowed.
  13. * @param callable $processMessage A callable (function) that processes a single message.
  14. * @return array An array containing the results of processing each message,
  15. * including success/failure status and any error messages.
  16. */
  17. function processQueue(array $queue, int $maxAttempts, callable $processMessage): array
  18. {
  19. $results = [];
  20. foreach ($queue as $message) {
  21. $attempts = $message['attempts'] ?? 0; // Default to 0 attempts if not set
  22. $success = false;
  23. $errorMessage = null;
  24. $attempt = 0;
  25. while (!$success && $attempt < $maxAttempts) {
  26. $attempt++;
  27. try {
  28. $result = $processMessage($message);
  29. $success = true;
  30. } catch (Exception $e) {
  31. $errorMessage = "Attempt " . $attempt . " failed: " . $e->getMessage();
  32. }
  33. if (!$success) {
  34. $message['attempts'] = $attempts + 1; // Increment attempts
  35. usleep(100000); // Sleep for 100ms before retrying (optional)
  36. }
  37. }
  38. $results[] = [
  39. 'message' => $message,
  40. 'success' => $success,
  41. 'errorMessage' => $errorMessage,
  42. 'attempted' => $attempt
  43. ];
  44. }
  45. return $results;
  46. }
  47. /**
  48. * Example usage (replace with your actual message processing logic).
  49. */
  50. if (count($argv) > 1) {
  51. $queueData = json_decode(file_get_contents($argv[1]), true);
  52. if (is_array($queueData)) {
  53. $results = processQueue($queueData, 3, function ($message) {
  54. // Simulate a message processing operation
  55. if (rand(0, 2) == 0) {
  56. throw new Exception("Simulated processing error");
  57. }
  58. return "Message processed successfully: " . json_encode($message);
  59. });
  60. echo json_encode($results, JSON_PRETTY_PRINT); // Output results
  61. } else {
  62. echo "Invalid queue data format.\n";
  63. }
  64. } else {
  65. echo "Usage: php script.php <queue_data_file>\n";
  66. }
  67. ?>

Add your comment