// // ReconnectPolicy.swift // JetstreamKit // /// How a ``JetstreamClient`` paces its reconnects: a delay that doubles from /// `initialDelay` to `maximumDelay`, reset by a connection that stayed up long /// enough to count as healthy, and a move to the next host after repeated /// failures on the current one. public struct ReconnectPolicy: Sendable, Equatable { public var initialDelay: Duration public var maximumDelay: Duration /// How long a connection must last for its end not to count against the host. public var stableConnection: Duration /// Consecutive failures on one host before trying the next. public var failuresBeforeFailover: Int public init( initialDelay: Duration = .seconds(1), maximumDelay: Duration = .seconds(60), stableConnection: Duration = .seconds(30), failuresBeforeFailover: Int = 3 ) { self.initialDelay = initialDelay self.maximumDelay = maximumDelay self.stableConnection = stableConnection self.failuresBeforeFailover = failuresBeforeFailover } } /// A client's progress through its ``ReconnectPolicy``. struct ReconnectState: Sendable { private let policy: ReconnectPolicy private let hostCount: Int private var delay: Duration private var consecutiveFailures = 0 /// The host the next attempt goes to. private(set) var hostIndex = 0 init(policy: ReconnectPolicy, hostCount: Int) { self.policy = policy self.hostCount = hostCount self.delay = policy.initialDelay } /// Records a connection that opened and then ended after `lifetime`, and /// returns the wait before the next attempt. mutating func connectionEnded(after lifetime: Duration) -> Duration { if lifetime >= policy.stableConnection { delay = policy.initialDelay consecutiveFailures = 0 } return failureRecorded() } /// Records an attempt that never opened, and returns the wait before the /// next one. It says nothing about how long the attempt took, so a host /// that hangs until a timeout can't pass for a stable connection. mutating func connectFailed() -> Duration { failureRecorded() } private mutating func failureRecorded() -> Duration { consecutiveFailures += 1 if consecutiveFailures >= policy.failuresBeforeFailover, hostCount > 1 { hostIndex = (hostIndex + 1) % hostCount consecutiveFailures = 0 } let wait = delay delay = min(delay * 2, policy.maximumDelay) return wait } }