1. <?php
  2. class RequestThrottler {
  3. private $request_queue = [];
  4. private $throttle_interval = 1; // seconds
  5. private $max_requests_per_interval = 5;
  6. private $lock = \React\Lock::createLock();
  7. public function __construct(int $throttle_interval = 1, int $max_requests_per_interval = 5) {
  8. $this->throttle_interval = $throttle_interval;
  9. $this->max_requests_per_interval = $max_requests_per_interval;
  10. }
  11. public function acquire(): void {
  12. $this->lock->lock();
  13. }
  14. public function release(): void {
  15. $this->lock->unlock();
  16. }
  17. public function process(callable $callback): void {
  18. $this->acquire();
  19. try {
  20. $request_id = uniqid(); // Generate a unique ID for each request
  21. if (count($this->request_queue) >= $this->max_requests_per_interval) {
  22. throw new \Exception("Rate limit exceeded. Waiting.");
  23. }
  24. $this->request_queue[] = $request_id;
  25. $callback($request_id); // Execute the diagnostic log entry function
  26. } catch (\Exception $e) {
  27. error_log("Diagnostic Log Entry Error: " . $e->getMessage());
  28. } finally {
  29. $this->release();
  30. }
  31. }
  32. public function clearQueue(): void {
  33. $this->request_queue = [];
  34. }
  35. }
  36. // Example usage:
  37. // Define a function for your diagnostic log entry
  38. function logDiagnosticEntry(string $request_id): void {
  39. error_log("Diagnostic Log Entry: Request ID - " . $request_id . " - Data: Some diagnostic data.");
  40. }
  41. // Create a throttler instance
  42. $throttler = new RequestThrottler(throttle_interval: 1, max_requests_per_interval: 3);
  43. // Simulate multiple diagnostic log entries
  44. for ($i = 0; $i < 10; $i++) {
  45. $throttler->process(function ($request_id) use ($i) {
  46. logDiagnosticEntry($request_id);
  47. });
  48. }
  49. ?>

Add your comment