1. <?php
  2. class LogStreamThrottler
  3. {
  4. private $logStreamName;
  5. private $requestsPerSecond;
  6. private $dryRun;
  7. private $lastRequestTime;
  8. private $requestCount;
  9. public function __construct(string $logStreamName, int $requestsPerSecond, bool $dryRun = false)
  10. {
  11. $this->logStreamName = $logStreamName;
  12. $this->requestsPerSecond = $requestsPerSecond;
  13. $this->dryRun = $dryRun;
  14. $this->lastRequestTime = 0;
  15. $this->requestCount = 0;
  16. }
  17. public function shouldThrottle(): bool
  18. {
  19. $currentTime = time();
  20. if ($this->dryRun) {
  21. return false; // Don't actually throttle in dry run mode
  22. }
  23. if ($currentTime - $this->lastRequestTime < (1 / $this->requestsPerSecond)) {
  24. return true; // Throttle if request frequency is too high
  25. }
  26. // Allow the request
  27. $this->lastRequestTime = $currentTime;
  28. $this->requestCount = 1;
  29. return false;
  30. }
  31. public function processRequest(): void
  32. {
  33. if ($this->shouldThrottle()) {
  34. if ($this->dryRun) {
  35. echo "DRY RUN: Request throttled for log stream: " . $this->logStreamName . "\n";
  36. } else {
  37. // Simulate throttling - in a real implementation, you would delay the request
  38. sleep(1 / $this->requestsPerSecond); // Introduce a delay
  39. echo "Throttling log stream: " . $this->logStreamName . "\n";
  40. }
  41. return;
  42. }
  43. // Process the request (e.g., write to the log stream)
  44. echo "Processing request for log stream: " . $this->logStreamName . "\n";
  45. // Your log stream processing code here
  46. }
  47. }
  48. // Example Usage:
  49. $throttler = new LogStreamThrottler("my_log_stream", 10, true); // Dry run mode
  50. // $throttler = new LogStreamThrottler("my_log_stream", 10); // Normal mode
  51. for ($i = 0; $i < 20; $i++) {
  52. $throttler->processRequest();
  53. }
  54. ?>

Add your comment