Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

calculating a backoff value for auto-reconnect timing #11

Merged
merged 1 commit into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Sources/AutomergeRepo/Backoff.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Foundation

public enum Backoff {
// fibonacci numbers for 0...15
static let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

public static func delay(_ step: UInt, withJitter: Bool) -> Int {
let boundedStep = Int(min(15, step))

if withJitter {
// pick a range of +/- values that's one fibonacci step lower
let jitterStep = max(min(15,boundedStep - 1),0)
if jitterStep < 1 {
// picking a random number between -0 and 0 is just silly, and kinda wrong
// so just return the fibonacci number
return Self.fibonacci[boundedStep]
}
let jitterRange = -1*Self.fibonacci[jitterStep]...Self.fibonacci[jitterStep]
let selectedValue = Int.random(in: jitterRange)
// no delay should be less than 0
let adjustedValue = max(0, Self.fibonacci[boundedStep] + selectedValue)
// max value is 987, min value is 0
return adjustedValue
}
return Self.fibonacci[boundedStep]
}
}
25 changes: 25 additions & 0 deletions Tests/AutomergeRepoTests/BackoffTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import AutomergeRepo
import XCTest

final class BackoffTests: XCTestCase {
func testSimpleBackoff() throws {
XCTAssertEqual(0, Backoff.delay(0, withJitter: false))
XCTAssertEqual(1, Backoff.delay(1, withJitter: false))
XCTAssertEqual(1, Backoff.delay(2, withJitter: false))
XCTAssertEqual(2, Backoff.delay(3, withJitter: false))
XCTAssertEqual(3, Backoff.delay(4, withJitter: false))
XCTAssertEqual(610, Backoff.delay(15, withJitter: false))
XCTAssertEqual(610, Backoff.delay(16, withJitter: false))
XCTAssertEqual(610, Backoff.delay(100, withJitter: false))
}

func testWithJitterBackoff() throws {
XCTAssertEqual(0, Backoff.delay(0, withJitter: true))
XCTAssertEqual(1, Backoff.delay(1, withJitter: true))
for i: UInt in 2...50 {
XCTAssertTrue(Backoff.delay(i, withJitter: true) <= 987)
print(Backoff.delay(i, withJitter: true))
}
}

}
Loading