|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the AsyncHTTPClient open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import NIOCore |
| 16 | +#if canImport(Darwin) |
| 17 | + import func Darwin.pow |
| 18 | +#else |
| 19 | + import func Glibc.pow |
| 20 | +#endif |
| 21 | + |
| 22 | +extension HTTPConnectionPool { |
| 23 | + /// Calculates the delay for the next connection attempt after the given number of failed `attempts`. |
| 24 | + /// |
| 25 | + /// Our backoff formula is: 100ms * 1.25^(attempts - 1) that is capped of at 1 minute. |
| 26 | + /// This means for: |
| 27 | + /// - 1 failed attempt : 100ms |
| 28 | + /// - 5 failed attempts: ~300ms |
| 29 | + /// - 10 failed attempts: ~930ms |
| 30 | + /// - 15 failed attempts: ~2.84s |
| 31 | + /// - 20 failed attempts: ~8.67s |
| 32 | + /// - 25 failed attempts: ~26s |
| 33 | + /// - 29 failed attempts: ~60s (max out) |
| 34 | + /// |
| 35 | + /// - Parameter attempts: number of failed attempts in a row |
| 36 | + /// - Returns: time to wait until trying to establishing a new connection |
| 37 | + static func calculateBackoff(failedAttempt attempts: Int) -> TimeAmount { |
| 38 | + // Our backoff formula is: 100ms * 1.25^(attempts - 1) that is capped of at 1minute |
| 39 | + // This means for: |
| 40 | + // - 1 failed attempt : 100ms |
| 41 | + // - 5 failed attempts: ~300ms |
| 42 | + // - 10 failed attempts: ~930ms |
| 43 | + // - 15 failed attempts: ~2.84s |
| 44 | + // - 20 failed attempts: ~8.67s |
| 45 | + // - 25 failed attempts: ~26s |
| 46 | + // - 29 failed attempts: ~60s (max out) |
| 47 | + |
| 48 | + let start = Double(TimeAmount.milliseconds(100).nanoseconds) |
| 49 | + let backoffNanoseconds = Int64(start * pow(1.25, Double(attempts - 1))) |
| 50 | + |
| 51 | + let backoff: TimeAmount = min(.nanoseconds(backoffNanoseconds), .seconds(60)) |
| 52 | + |
| 53 | + // Calculate a 3% jitter range |
| 54 | + let jitterRange = (backoff.nanoseconds / 100) * 3 |
| 55 | + // Pick a random element from the range +/- jitter range. |
| 56 | + let jitter: TimeAmount = .nanoseconds((-jitterRange...jitterRange).randomElement()!) |
| 57 | + let jitteredBackoff = backoff + jitter |
| 58 | + return jitteredBackoff |
| 59 | + } |
| 60 | +} |
0 commit comments