Something went wrong. Try again.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import Foundation
/// Backoff for the Jetstream consumer: doubling from one second to a minute,/// reset after a connection that stayed up long enough to count as healthy,/// and a switch to the next host after repeated failures on the current one.struct ReconnectPolicy: Sendable, Equatable { static let initialDelay: Duration = .seconds(1) static let maximumDelay: Duration = .seconds(60) static let stableConnection: Duration = .seconds(30) /// Consecutive failures on one host before trying the next. static let failuresBeforeFailover = 3
private(set) var delay: Duration = ReconnectPolicy.initialDelay private(set) var consecutiveFailures = 0 private(set) var hostIndex = 0 let hostCount: Int
init(hostCount: Int) { self.hostCount = max(hostCount, 1) }
/// Records a disconnect. `connectedFor` is how long the connection lasted. mutating func connectionEnded(after connectedFor: Duration) { if connectedFor >= Self.stableConnection { delay = Self.initialDelay consecutiveFailures = 0 } consecutiveFailures += 1 if consecutiveFailures >= Self.failuresBeforeFailover, hostCount > 1 { hostIndex = (hostIndex + 1) % hostCount consecutiveFailures = 0 } }
/// The delay to wait before the next attempt, then grows it for the attempt after. mutating func nextDelay() -> Duration { let current = delay delay = min(delay * 2, Self.maximumDelay) return current }
mutating func connected() { consecutiveFailures = 0 }}