<?php
class LogStreamThrottler
{
private $logStreamName;
private $requestsPerSecond;
private $dryRun;
private $lastRequestTime;
private $requestCount;
public function __construct(string $logStreamName, int $requestsPerSecond, bool $dryRun = false)
{
$this->logStreamName = $logStreamName;
$this->requestsPerSecond = $requestsPerSecond;
$this->dryRun = $dryRun;
$this->lastRequestTime = 0;
$this->requestCount = 0;
}
public function shouldThrottle(): bool
{
$currentTime = time();
if ($this->dryRun) {
return false; // Don't actually throttle in dry run mode
}
if ($currentTime - $this->lastRequestTime < (1 / $this->requestsPerSecond)) {
return true; // Throttle if request frequency is too high
}
// Allow the request
$this->lastRequestTime = $currentTime;
$this->requestCount = 1;
return false;
}
public function processRequest(): void
{
if ($this->shouldThrottle()) {
if ($this->dryRun) {
echo "DRY RUN: Request throttled for log stream: " . $this->logStreamName . "\n";
} else {
// Simulate throttling - in a real implementation, you would delay the request
sleep(1 / $this->requestsPerSecond); // Introduce a delay
echo "Throttling log stream: " . $this->logStreamName . "\n";
}
return;
}
// Process the request (e.g., write to the log stream)
echo "Processing request for log stream: " . $this->logStreamName . "\n";
// Your log stream processing code here
}
}
// Example Usage:
$throttler = new LogStreamThrottler("my_log_stream", 10, true); // Dry run mode
// $throttler = new LogStreamThrottler("my_log_stream", 10); // Normal mode
for ($i = 0; $i < 20; $i++) {
$throttler->processRequest();
}
?>
Add your comment