1. <?php
  2. class TaskQueueDeserializer {
  3. private $rateLimit = 10; // Max tasks per second
  4. private $rateLimitWindow = 1; // Time window for rate limiting (seconds)
  5. private $taskCount = 0;
  6. private $lastReset = 0;
  7. /**
  8. * Deserializes task queue input with rate limiting.
  9. *
  10. * @param string $input The JSON encoded task input.
  11. * @return array|null The deserialized task data, or null on rate limit exceed.
  12. */
  13. public function deserialize(string $input): ?array {
  14. // Rate limiting check
  15. $now = time();
  16. if ($now - $this->lastReset < $this->rateLimitWindow) {
  17. if ($this->taskCount >= $this->rateLimit) {
  18. error_log("Rate limit exceeded."); // Log the event
  19. return null; // Reject the task
  20. }
  21. }
  22. // Increment task count
  23. $this->taskCount++;
  24. $this->lastReset = $now;
  25. try {
  26. $task = json_decode($input, true); // Decode JSON to associative array
  27. if (json_last_error() !== JSON_ERROR_NONE) {
  28. error_log("JSON decode error: " . json_last_error_msg()); // Log JSON decode errors
  29. return null; // Return null if decoding fails
  30. }
  31. //Basic validation, add more as needed.
  32. if (!isset($task['task_id']) || !is_string($task['task_id'])) {
  33. error_log("Invalid task format: missing or invalid task_id");
  34. return null;
  35. }
  36. return $task; // Return the deserialized task
  37. } catch (\Exception $e) {
  38. error_log("Deserialization error: " . $e->getMessage()); // Log any other exceptions
  39. return null;
  40. }
  41. }
  42. }
  43. // Example usage (for testing):
  44. /*
  45. $deserializer = new TaskQueueDeserializer();
  46. $taskData = '{"task_id": "123", "data": "some data"}';
  47. $task = $deserializer->deserialize($taskData);
  48. if ($task) {
  49. echo "Task data: " . json_encode($task) . "\n";
  50. } else {
  51. echo "Task rejected.\n";
  52. }
  53. */
  54. ?>

Add your comment