|
| 1 | +import Foundation |
| 2 | + |
| 3 | +actor LogRateLimiter { |
| 4 | + private let maxLogsCount: Int = 20000 |
| 5 | + private let timeDuration: TimeInterval = 5.0 |
| 6 | + private var logCount: Int = 0 |
| 7 | + private var startTime: TimeInterval = CFAbsoluteTimeGetCurrent() |
| 8 | + private var lastTimeCheck: TimeInterval = CFAbsoluteTimeGetCurrent() |
| 9 | + private var isBlocked = false |
| 10 | + |
| 11 | + private let onRateLimitTriggered: () -> Void |
| 12 | + |
| 13 | + init(onRateLimitTriggered: @escaping () -> Void) { |
| 14 | + self.onRateLimitTriggered = onRateLimitTriggered |
| 15 | + } |
| 16 | + |
| 17 | + // Returns true if log can be processed, false if rate limited |
| 18 | + func processLog() -> Bool { |
| 19 | + guard !isBlocked else { return false } |
| 20 | + |
| 21 | + let now = CFAbsoluteTimeGetCurrent() |
| 22 | + |
| 23 | + // Only check time and count every 1 second to reduce overhead |
| 24 | + if now - lastTimeCheck >= 1.0 { |
| 25 | + lastTimeCheck = now |
| 26 | + |
| 27 | + // Reset counter if time window has passed |
| 28 | + if now - startTime >= timeDuration { |
| 29 | + startTime = now |
| 30 | + logCount = 0 |
| 31 | + } |
| 32 | + |
| 33 | + // Check if rate limit exceeded |
| 34 | + if logCount >= maxLogsCount { |
| 35 | + Task { await triggerRateLimit() } |
| 36 | + return false |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + logCount += 1 |
| 41 | + return true |
| 42 | + } |
| 43 | + |
| 44 | + private func triggerRateLimit() async { |
| 45 | + isBlocked = true |
| 46 | + |
| 47 | + // Execute callback on main actor |
| 48 | + await MainActor.run { |
| 49 | + onRateLimitTriggered() |
| 50 | + Logger.log("⚠️ Rate limit triggered: >\(maxLogsCount) logs/\(timeDuration)sec, paused for 1min") |
| 51 | + } |
| 52 | + |
| 53 | + // Resume after 60 seconds |
| 54 | + try? await Task.sleep(nanoseconds: 60_000_000_000) |
| 55 | + |
| 56 | + isBlocked = false |
| 57 | + |
| 58 | + await MainActor.run { |
| 59 | + Logger.log("✅ Rate limit resumed") |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments