Something went wrong. Try again.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637import Foundation
/// A token bucket: `capacity` tokens are available at once and `rate` tokens/// are added per second. Used for the request rate limiter and for the/// budgets on calls that reach Podcast Index.////// The bucket is a value type; keep it inside an actor when several tasks/// share it.struct TokenBucket: Sendable { let rate: Double let capacity: Double private(set) var tokens: Double private(set) var lastRefill: Date
init(rate: Double, burst: Int, now: Date = Date()) { self.rate = rate self.capacity = Double(max(burst, 1)) self.tokens = capacity self.lastRefill = now }
/// Takes one token if available. Returns false when the bucket is empty. mutating func allow(now: Date = Date()) -> Bool { refill(now: now) guard tokens >= 1 else { return false } tokens -= 1 return true }
private mutating func refill(now: Date) { let elapsed = now.timeIntervalSince(lastRefill) guard elapsed > 0 else { return } tokens = min(capacity, tokens + elapsed * rate) lastRefill = now }}