1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.time.Instant;
  4. import java.time.Duration;
  5. public class LogDecoder {
  6. private final Map<String, Long> lastRunTimes = new HashMap<>();
  7. private final long rateLimitIntervalSeconds; // e.g., 60 for 1 minute
  8. public LogDecoder(long rateLimitIntervalSeconds) {
  9. this.rateLimitIntervalSeconds = rateLimitIntervalSeconds;
  10. }
  11. public boolean isAllowed(String logEntry) {
  12. // Get the current time
  13. Instant now = Instant.now();
  14. // Get the last run time for this log entry type (key)
  15. Long lastRunTime = lastRunTimes.get(logEntry);
  16. // If this is the first time we've seen this log entry type...
  17. if (lastRunTime == null) {
  18. // ...allow it.
  19. lastRunTimes.put(logEntry, now.toEpochMilli());
  20. return true;
  21. }
  22. // Calculate the time elapsed since the last run
  23. Duration timeElapsed = Duration.between(Instant.ofEpochMilli(lastRunTime), now);
  24. // Check if the time elapsed is greater than or equal to the rate limit interval
  25. if (timeElapsed.getSeconds() >= rateLimitIntervalSeconds) {
  26. // Allow the log entry
  27. lastRunTimes.put(logEntry, now.toEpochMilli());
  28. return true;
  29. } else {
  30. // Rate limited - don't allow the log entry
  31. return false;
  32. }
  33. }
  34. }

Add your comment