import Testing @testable import JetstreamKit @Suite("Reconnect policy") struct ReconnectPolicyTests { @Test("The default delay doubles from one second and stops at a minute") func backoff() { var state = ReconnectState(policy: .init(), hostCount: 1) let delays = (0..<8).map { _ in state.connectFailed() } #expect(delays == [1, 2, 4, 8, 16, 32, 60, 60].map(Duration.seconds)) } @Test("A connection that lasted thirty seconds resets the delay") func stableConnection() { var state = ReconnectState(policy: .init(), hostCount: 1) _ = state.connectFailed() _ = state.connectFailed() #expect(state.connectionEnded(after: .seconds(30)) == .seconds(1)) #expect(state.connectFailed() == .seconds(2)) } @Test("A short connection keeps growing the delay") func flappingConnection() { var state = ReconnectState(policy: .init(), hostCount: 1) #expect(state.connectionEnded(after: .seconds(29)) == .seconds(1)) #expect(state.connectionEnded(after: .seconds(29)) == .seconds(2)) #expect(state.connectionEnded(after: .seconds(29)) == .seconds(4)) } @Test("Three failures move to the next host, and the last host wraps around") func failover() { var state = ReconnectState(policy: .init(), hostCount: 2) #expect(state.hostIndex == 0) _ = state.connectFailed() _ = state.connectFailed() #expect(state.hostIndex == 0) _ = state.connectFailed() #expect(state.hostIndex == 1) for _ in 0..<3 { _ = state.connectFailed() } #expect(state.hostIndex == 0) } @Test("A stable connection clears the count of failures against the host") func stableClearsFailures() { var state = ReconnectState(policy: .init(), hostCount: 2) _ = state.connectFailed() _ = state.connectFailed() _ = state.connectionEnded(after: .seconds(60)) _ = state.connectFailed() #expect(state.hostIndex == 0) _ = state.connectFailed() #expect(state.hostIndex == 1) } @Test("Connections that keep dropping count as failures, so a flapping host is left") func flappingHostFailsOver() { var state = ReconnectState(policy: .init(), hostCount: 2) for _ in 0..<3 { _ = state.connectionEnded(after: .seconds(5)) } #expect(state.hostIndex == 1) } @Test("A connect that hung for a long time still counts as a failure") func hungConnectIsNotStable() { var state = ReconnectState(policy: .init(), hostCount: 2) // connectFailed takes no duration: the time spent waiting on a dead host can't reset anything. for _ in 0..<3 { _ = state.connectFailed() } #expect(state.hostIndex == 1) } @Test("A single host is never left") func singleHost() { var state = ReconnectState(policy: .init(), hostCount: 1) for _ in 0..<10 { _ = state.connectFailed() } #expect(state.hostIndex == 0) } }