Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
fumoboy007 committed Dec 10, 2023
0 parents commit 0936ca9
Show file tree
Hide file tree
Showing 18 changed files with 924 additions and 0 deletions.
42 changes: 42 additions & 0 deletions .github/workflows/documentation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Documentation

on:
push:
branches:
- main

permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false

jobs:
publish:
name: Publish Documentation
# TODO: Use `macos-latest` after the macOS 13 image graduates to GA.
# https://github.com/actions/runner-images/issues/7508#issuecomment-1718206371
runs-on: macos-13

environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

steps:
- name: Set up GitHub Pages
uses: actions/configure-pages@v3
- uses: actions/checkout@v3
- name: Generate documentation
run: "swift package generate-documentation --target Retry --disable-indexing --include-extended-types --transform-for-static-hosting --hosting-base-path swift-retry"
- name: Upload documentation
uses: actions/upload-pages-artifact@v2
with:
path: ".build/plugins/Swift-DocC/outputs/Retry.doccarchive"
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2
35 changes: 35 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Tests

on: [push]

# TODO: Add Windows job after Swift is added to the Windows images [1] or after
# `swift-actions/setup-swift` supports Swift 5.9+ on Windows [2].
# 1. https://github.com/actions/runner-images/issues/8281
# 2. https://github.com/swift-actions/setup-swift/pull/470#issuecomment-1718406382
jobs:
test-macos:
name: Run Tests on macOS
# TODO: Use `macos-latest` after the macOS 13 image graduates to GA.
# https://github.com/actions/runner-images/issues/7508#issuecomment-1718206371
runs-on: macos-13

steps:
- uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: latest-stable
- name: Print Swift compiler version
run: "swift --version"
- uses: actions/checkout@v3
- name: Run tests
run: "swift test"

test-linux:
name: Run Tests on Linux
runs-on: ubuntu-latest

steps:
- name: Print Swift compiler version
run: "swift --version"
- uses: actions/checkout@v3
- name: Run tests
run: "swift test"
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# MIT License

Copyright © 2023 Darren Mo.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14 changes: 14 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "swift-log",
"kind" : "remoteSourceControl",
"location" : "http://github.com/apple/swift-log",
"state" : {
"revision" : "532d8b529501fb73a2455b179e0bbb6d49b652ed",
"version" : "1.5.3"
}
}
],
"version" : 2
}
40 changes: 40 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// swift-tools-version: 5.9

import PackageDescription

let package = Package(
name: "Retry",
platforms: [
.visionOS(.v1),
.macOS(.v13),
.macCatalyst(.v16),
.iOS(.v16),
.tvOS(.v16),
.watchOS(.v9),
],
products: [
.library(
name: "Retry",
targets: [
"Retry",
]
),
],
dependencies: [
.package(url: "http://github.com/apple/swift-log.git", from: "1.5.3"),
],
targets: [
.target(
name: "Retry",
dependencies: [
.product(name: "Logging", package: "swift-log"),
]
),
.testTarget(
name: "RetryTests",
dependencies: [
"Retry",
]
),
]
)
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# swift-retry

Retries in Swift with good default behavior and powerful flexibility.

![Swift 5.9](https://img.shields.io/badge/swift-v5.9-%23F05138)
![Linux, visionOS 1, macOS 13, iOS 16, tvOS 16, watchOS 9](https://img.shields.io/badge/platform-Linux%20%7C%20visionOS%201%20%7C%20macOS%2013%20%7C%20iOS%2016%20%7C%20tvOS%2016%20%7C%20watchOS%209-blue)
![MIT License](https://img.shields.io/github/license/fumoboy007/swift-retry)
![Automated Tests Workflow Status](https://img.shields.io/github/actions/workflow/status/fumoboy007/swift-retry/tests.yml?event=push&label=tests)

## Usage

See the [documentation](https://fumoboy007.github.io/swift-retry/documentation/retry/).
33 changes: 33 additions & 0 deletions Sources/Retry/Backoff/Algorithms/ConstantBackoff.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// MIT License
//
// Copyright © 2023 Darren Mo.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

struct ConstantBackoff<ClockType: Clock>: BackoffAlgorithm {
private let delay: ClockType.Duration

init(delay: ClockType.Duration) {
self.delay = delay
}

func nextDelay(of clockType: ClockType.Type) -> ClockType.Duration {
return delay
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// MIT License
//
// Copyright © 2023 Darren Mo.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

struct FullJitterExponentialBackoff<ClockType: Clock>: BackoffAlgorithm {
private let clockMinResolution: ClockType.Duration

private let baseDelayInClockTicks: Int
private let maxExponent: Int

private var attempt = 0

init(clock: ClockType,
baseDelay: ClockType.Duration,
maxDelay: ClockType.Duration?) {
self.clockMinResolution = clock.minimumResolution

self.baseDelayInClockTicks = Int((baseDelay / clockMinResolution).rounded())
precondition(baseDelayInClockTicks > 0)

var maxExponent = Self.closestBaseTwoExponentOfValue(lessThanOrEqualTo: Int.max / baseDelayInClockTicks)
if let maxDelay {
precondition(maxDelay >= baseDelay)
let maxDelayInClockTicks = Int((maxDelay / clockMinResolution).rounded())

maxExponent = min(Self.closestBaseTwoExponentOfValue(lessThanOrEqualTo: maxDelayInClockTicks),
maxExponent)
}
self.maxExponent = maxExponent
}

private static func closestBaseTwoExponentOfValue(lessThanOrEqualTo value: Int) -> Int {
precondition(value >= 0)

return max(Int.bitWidth - value.leadingZeroBitCount - 1, 0)
}

mutating func nextDelay(of clockType: ClockType.Type) -> ClockType.Duration {
defer {
attempt += 1
}

let exponent = min(attempt, maxExponent)
let maxDelayInClockTicks = baseDelayInClockTicks * 1 << exponent

let delayInClockTicks = Int.random(in: 0...maxDelayInClockTicks)
return clockMinResolution * delayInClockTicks
}
}
104 changes: 104 additions & 0 deletions Sources/Retry/Backoff/Backoff.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// MIT License
//
// Copyright © 2023 Darren Mo.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

/// The choice of algorithm that will be used to determine how long to sleep in between attempts.
public struct Backoff<ClockType: Clock> {
// MARK: - Built-In Algorithm

/// The default algorithm, which is suitable for most use cases.
///
/// This algorithm is an exponential backoff algorithm. The specific choice of algorithm is an implementation
/// detail, which may change in the future.
///
/// - Parameters:
/// - baseDelay: A duration that all delays will be based on. For example, in a simple exponential
/// backoff algorithm, the first delay might be `baseDelay`, the second delay might be
/// `baseDelay * 2`, the third delay might be `baseDelay * 2 * 2`, and so on.
/// - maxDelay: The desired maximum duration in between attempts. There may also be a maximum
/// enforced by the algorithm implementation.
public static func `default`(baseDelay: ClockType.Duration,
maxDelay: ClockType.Duration?) -> Self {
return exponentialWithFullJitter(baseDelay: baseDelay,
maxDelay: maxDelay)
}

/// Exponential backoff with “full jitter”.
///
/// This algorithm is used by [AWS](https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html#feature-retry-behavior-sdk-compat)
/// and [Google Cloud](https://github.com/googleapis/gax-go/blob/465d35f180e8dc8b01979d09c780a10c41f15136/v2/call_option.go#L181-L205)
/// among others. The advantages and disadvantages of the algorithm are detailed in a [blog post](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
/// by AWS.
///
/// - Parameters:
/// - baseDelay: A duration that all delays will be based on. For example, in a simple exponential
/// backoff algorithm, the first delay might be `baseDelay`, the second delay might be
/// `baseDelay * 2`, the third delay might be `baseDelay * 2 * 2`, and so on.
/// - maxDelay: The desired maximum duration in between attempts. There may also be a maximum
/// enforced by the algorithm implementation.
///
/// - SeeAlso: ``default(baseDelay:maxDelay:)``
public static func exponentialWithFullJitter(baseDelay: ClockType.Duration,
maxDelay: ClockType.Duration?) -> Self {
return Self { clock in
return FullJitterExponentialBackoff(clock: clock,
baseDelay: baseDelay,
maxDelay: maxDelay)
}
}

/// Constant delay.
///
/// - Warning: This algorithm should only be used as an optimization for a small set of use cases.
/// Most retry use cases involve a resource, such as a server, with potentially many clients where an
/// exponential backoff algorithm would be ideal to avoid [DDoSing the server](https://cloud.google.com/blog/products/gcp/how-to-avoid-a-self-inflicted-ddos-attack-cre-life-lessons).
/// The constant delay algorithm should only be used in cases where there is no possibility of a DDoS.
///
/// - Parameter delay: The constant duration to sleep in between attempts.
///
/// - SeeAlso: ``default(baseDelay:maxDelay:)``
public static func constant(_ delay: ClockType.Duration) -> Self {
return Self { _ in
return ConstantBackoff<ClockType>(delay: delay)
}
}

// MARK: - Private Properties

private let makeAlgorithmClosure: (ClockType) -> any BackoffAlgorithm<ClockType>

// MARK: - Initialization

/// Initializes the instance with a specific algorithm.
///
/// - Parameter makeAlgorithm: A closure that returns a ``BackoffAlgorithm`` implementation.
///
/// - SeeAlso: ``default(baseDelay:maxDelay:)``
public init(makeAlgorithm: @escaping (ClockType) -> any BackoffAlgorithm<ClockType>) {
self.makeAlgorithmClosure = makeAlgorithm
}

// MARK: - Making the Algorithm

func makeAlgorithm(clock: ClockType) -> any BackoffAlgorithm<ClockType> {
return makeAlgorithmClosure(clock)
}
}
Loading

0 comments on commit 0936ca9

Please sign in to comment.