<?php
class TaskQueueDeserializer {
private $rateLimit = 10; // Max tasks per second
private $rateLimitWindow = 1; // Time window for rate limiting (seconds)
private $taskCount = 0;
private $lastReset = 0;
/**
* Deserializes task queue input with rate limiting.
*
* @param string $input The JSON encoded task input.
* @return array|null The deserialized task data, or null on rate limit exceed.
*/
public function deserialize(string $input): ?array {
// Rate limiting check
$now = time();
if ($now - $this->lastReset < $this->rateLimitWindow) {
if ($this->taskCount >= $this->rateLimit) {
error_log("Rate limit exceeded."); // Log the event
return null; // Reject the task
}
}
// Increment task count
$this->taskCount++;
$this->lastReset = $now;
try {
$task = json_decode($input, true); // Decode JSON to associative array
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("JSON decode error: " . json_last_error_msg()); // Log JSON decode errors
return null; // Return null if decoding fails
}
//Basic validation, add more as needed.
if (!isset($task['task_id']) || !is_string($task['task_id'])) {
error_log("Invalid task format: missing or invalid task_id");
return null;
}
return $task; // Return the deserialized task
} catch (\Exception $e) {
error_log("Deserialization error: " . $e->getMessage()); // Log any other exceptions
return null;
}
}
}
// Example usage (for testing):
/*
$deserializer = new TaskQueueDeserializer();
$taskData = '{"task_id": "123", "data": "some data"}';
$task = $deserializer->deserialize($taskData);
if ($task) {
echo "Task data: " . json_encode($task) . "\n";
} else {
echo "Task rejected.\n";
}
*/
?>
Add your comment