import java.util.HashMap;
import java.util.Map;
import java.time.Instant;
import java.time.Duration;
public class LogDecoder {
private final Map<String, Long> lastRunTimes = new HashMap<>();
private final long rateLimitIntervalSeconds; // e.g., 60 for 1 minute
public LogDecoder(long rateLimitIntervalSeconds) {
this.rateLimitIntervalSeconds = rateLimitIntervalSeconds;
}
public boolean isAllowed(String logEntry) {
// Get the current time
Instant now = Instant.now();
// Get the last run time for this log entry type (key)
Long lastRunTime = lastRunTimes.get(logEntry);
// If this is the first time we've seen this log entry type...
if (lastRunTime == null) {
// ...allow it.
lastRunTimes.put(logEntry, now.toEpochMilli());
return true;
}
// Calculate the time elapsed since the last run
Duration timeElapsed = Duration.between(Instant.ofEpochMilli(lastRunTime), now);
// Check if the time elapsed is greater than or equal to the rate limit interval
if (timeElapsed.getSeconds() >= rateLimitIntervalSeconds) {
// Allow the log entry
lastRunTimes.put(logEntry, now.toEpochMilli());
return true;
} else {
// Rate limited - don't allow the log entry
return false;
}
}
}
Add your comment