├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── kotlin │ └── io │ └── github │ └── reugn │ └── kotlin │ └── backoff │ ├── Backoff.kt │ ├── StrategyBackoff.kt │ ├── strategy │ ├── ConstantStrategy.kt │ ├── ExponentialStrategy.kt │ ├── FixedStrategy.kt │ ├── Jitter.kt │ ├── PolynomialStrategy.kt │ └── Strategy.kt │ └── util │ ├── ErrorValidator.kt │ ├── Result.kt │ ├── ResultValidator.kt │ └── RetryException.kt └── test └── kotlin └── io └── github └── reugn └── kotlin └── backoff ├── ConstantStrategyTest.kt ├── ExponentialStrategyTest.kt ├── FixedStrategyTest.kt ├── JitterTest.kt ├── PolynomialStrategyTest.kt └── RemoteURLTest.kt /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | push: 4 | pull_request: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | 16 | - name: Set up JDK 1.8 17 | uses: actions/setup-java@v1 18 | with: 19 | java-version: 1.8 20 | 21 | - name: Cache Gradle packages 22 | uses: actions/cache@v2 23 | with: 24 | path: | 25 | ~/.gradle/caches 26 | ~/.gradle/wrapper 27 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 28 | restore-keys: | 29 | ${{ runner.os }}-gradle- 30 | 31 | - name: Build with Gradle 32 | run: ./gradlew clean test 33 | 34 | - name: Cleanup Gradle Cache 35 | # Remove some files from the Gradle cache, so they aren't cached by GitHub Actions. 36 | # Restoring these files from a GitHub Actions cache might cause problems for future builds. 37 | run: | 38 | rm -f ~/.gradle/caches/modules-2/modules-2.lock 39 | rm -f ~/.gradle/caches/modules-2/gc.properties -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # gradle 2 | .gradle 3 | build 4 | 5 | # idea 6 | .idea 7 | *.iml 8 | local.properties 9 | out/ 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kotlin-backoff 2 | [![Build](https://github.com/reugn/kotlin-backoff/actions/workflows/build.yml/badge.svg)](https://github.com/reugn/kotlin-backoff/actions/workflows/build.yml) 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.reugn/kotlin-backoff/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.reugn/kotlin-backoff/) 4 | 5 | Any I/O resource can be temporarily unavailable and cause requests to fail. 6 | Use this library to catch errors and retry, slowing down according to your chosen strategy. 7 | Add validation rules for the result and error types if needed. 8 | 9 | ## Installation 10 | `kotlin-backoff` is available on Maven Central. 11 | Add the library as a dependency to your project: 12 | ```kotlin 13 | dependencies { 14 | implementation("io.github.reugn:kotlin-backoff:0.4.0") 15 | } 16 | ``` 17 | 18 | ## Backoff strategies 19 | Below is a list of backoff strategies implemented. To create your own strategy, implement the `Strategy` interface. 20 | 21 | ### Exponential strategy 22 | A strategy in which the next delay interval is calculated using `baseDelayMs * expBase.pow(attempt)` where: 23 | * `baseDelayMs` is the base delay in milliseconds. 24 | * `attempt` is the number of unsuccessful attempts that have been made. 25 | * `expBase` is the exponent base configured for the strategy. 26 | 27 | The specified jitter¹ and scale factor² are applied to the calculated interval. 28 | The delay time cannot exceed the specified maximum delay in milliseconds. 29 | 30 | ### Polynomial strategy 31 | A strategy in which the next delay interval is calculated using `baseDelayMs * attempt.pow(exponent)` where: 32 | * `baseDelayMs` is the base delay in milliseconds. 33 | * `attempt` is the number of unsuccessful attempts that have been made. 34 | * `exponent` is the exponent configured for the strategy. 35 | 36 | The specified jitter¹ and scale factor² are applied to the calculated interval. 37 | The delay time cannot exceed the specified maximum delay in milliseconds. 38 | 39 | ### Fixed strategy 40 | A strategy that returns the delay time as a fixed value determined by the attempt number. 41 | 42 | ### Constant strategy 43 | A simple backoff strategy that constantly returns the same value. 44 | The specified jitter¹ is applied to the interval. No jitter by default. 45 | 46 | --- 47 | ¹ Jitter adds a retry randomization factor to reduce resource congestion. 48 | Specify 1.0 for full jitter, 0.0 for no jitter. 49 | 50 | ² The delay determined by the backoff strategy is multiplied by the scale factor. By default, the coefficient is 1. 51 | 52 | ## Usage example 53 | First, create an instance of `StrategyBackoff`. Then perform the operation, which may fail, using the `retry` or `withRetries` methods. 54 | ```kotlin 55 | private suspend fun urlAction(): String = withContext(Dispatchers.IO) { 56 | URL("http://worldclockapi.com/api/json/utc/now").readText() 57 | } 58 | 59 | @Test 60 | fun `remote URL`() { 61 | val backoff = StrategyBackoff( 62 | maxRetries = 3, 63 | strategy = ExponentialStrategy(), 64 | errorValidator = ::nonFatal, 65 | resultValidator = { s -> s.isNotEmpty() }, 66 | ) 67 | val result = runBlocking { backoff.withRetries(::urlAction) } 68 | 69 | assert(result.isOk()) 70 | assertEquals(result.retries, 0) 71 | } 72 | ``` 73 | For more examples, see the [tests](./src/test/kotlin/io/github/reugn/kotlin/backoff). 74 | 75 | ## License 76 | Licensed under the [Apache 2.0 License](./LICENSE). 77 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | java 5 | `java-library` 6 | kotlin("jvm") version "1.6.0" 7 | kotlin("plugin.serialization") version "1.6.0" 8 | `maven-publish` 9 | signing 10 | } 11 | 12 | group = "io.github.reugn" 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | java { 19 | withJavadocJar() 20 | withSourcesJar() 21 | } 22 | 23 | dependencies { 24 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") 25 | implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:1.0-M1-1.4.0-rc") 26 | testImplementation("org.junit.jupiter:junit-jupiter:5.8.2") 27 | } 28 | 29 | tasks.withType { 30 | kotlinOptions.jvmTarget = "1.8" 31 | } 32 | 33 | tasks.test { 34 | useJUnitPlatform() 35 | } 36 | 37 | publishing { 38 | publications { 39 | create("mavenCentral") { 40 | groupId = project.group.toString() 41 | artifactId = project.name 42 | version = project.version.toString() 43 | from(components["java"]) 44 | pom { 45 | name.set(project.name) 46 | description.set("An exponential backoff library for Kotlin.") 47 | url.set("https://github.com/reugn/kotlin-backoff") 48 | licenses { 49 | license { 50 | name.set("The Apache License, Version 2.0") 51 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 52 | } 53 | } 54 | developers { 55 | developer { 56 | id.set("reugn") 57 | name.set("reugn") 58 | email.set("reugpro@gmail.com") 59 | url.set("https://github.com/reugn") 60 | } 61 | } 62 | scm { 63 | connection.set("scm:git:git://github.com/reugn/kotlin-backoff.git") 64 | developerConnection.set("scm:git:ssh://github.com/reugn/kotlin-backoff.git") 65 | url.set("https://github.com/reugn/kotlin-backoff") 66 | } 67 | } 68 | } 69 | } 70 | repositories { 71 | maven { 72 | name = "mavenCentral" 73 | credentials(PasswordCredentials::class) 74 | val nexus = "https://s01.oss.sonatype.org/" 75 | val releasesRepoUrl = uri(nexus + "service/local/staging/deploy/maven2") 76 | val snapshotsRepoUrl = uri(nexus + "content/repositories/snapshots") 77 | url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl 78 | } 79 | } 80 | } 81 | 82 | signing { 83 | sign(publishing.publications["mavenCentral"]) 84 | useGpgCmd() 85 | sign(configurations.archives.get()) 86 | } 87 | 88 | tasks.javadoc { 89 | if (JavaVersion.current().isJava9Compatible) { 90 | (options as StandardJavadocDocletOptions).addBooleanOption("html5", true) 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | version=0.4.0 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reugn/kotlin-backoff/6c65f4264deb0cd4adafa7f2b8328b02033361e1/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'kotlin-backoff' 2 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/Backoff.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.util.Result 4 | 5 | interface Backoff { 6 | 7 | /** 8 | * Retries the specified operation with delays and returns the result. 9 | */ 10 | suspend fun retry(operation: suspend () -> T): Result 11 | 12 | /** 13 | * Executes the specified operation with retries and returns the result. 14 | * The difference from [retry] is that the first time the operation is performed without delay. 15 | */ 16 | suspend fun withRetries(operation: suspend () -> T): Result 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/StrategyBackoff.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.ExponentialStrategy 4 | import io.github.reugn.kotlin.backoff.strategy.Strategy 5 | import io.github.reugn.kotlin.backoff.util.* 6 | import kotlinx.coroutines.delay 7 | 8 | /** 9 | * A [Strategy] based [Backoff] implementation. 10 | * Backoff strategies calculate the delay that should be applied between retries. 11 | * 12 | * @param T the return type of operation to be executed with retries. 13 | * @property maxRetries the maximum number of retries. 14 | * @property strategy the next delay time calculation [Strategy]. 15 | * See implemented strategies in the io.github.reugn.kotlin.backoff.strategy package. 16 | * @property errorValidator exits the retry loop on an invalid exception. 17 | * @property resultValidator validates the operation result and returns if successful. Continues to 18 | * another retry cycle otherwise. 19 | */ 20 | class StrategyBackoff( 21 | private val maxRetries: Int = 3, 22 | private val strategy: Strategy = ExponentialStrategy(), 23 | private val errorValidator: ErrorValidator = ::nonFatal, 24 | private val resultValidator: ResultValidator = ::acceptAny, 25 | ) : Backoff, Strategy by strategy { 26 | 27 | init { 28 | require(maxRetries > 0) 29 | } 30 | 31 | override suspend fun retry( 32 | operation: suspend () -> T 33 | ): Result { 34 | return retryWithAttempts(operation, 1) 35 | } 36 | 37 | override suspend fun withRetries( 38 | operation: suspend () -> T 39 | ): Result { 40 | return try { 41 | val result = operation() 42 | if (resultValidator(result)) 43 | Ok(result, 0) 44 | else 45 | retryWithAttempts(operation, 1) 46 | } catch (e: Throwable) { 47 | if (errorValidator(e)) 48 | retryWithAttempts(operation, 1) 49 | else 50 | Err(e, 0) 51 | } 52 | } 53 | 54 | private suspend fun retryWithAttempts( 55 | operation: suspend () -> T, 56 | attempt: Int 57 | ): Result { 58 | while (true) { 59 | return try { 60 | delay(nextDelay(attempt)) 61 | 62 | val result = operation() 63 | if (resultValidator(result)) 64 | Ok(result, attempt) 65 | else 66 | validateAttempts(operation, attempt + 1) 67 | } catch (e: Throwable) { 68 | if (validateThrowable(e)) 69 | validateAttempts(operation, attempt + 1, e) 70 | else 71 | Err(e, attempt) 72 | } 73 | } 74 | } 75 | 76 | private fun validateThrowable(e: Throwable): Boolean { 77 | return e !is RetryException && errorValidator(e) 78 | } 79 | 80 | private suspend fun validateAttempts( 81 | operation: suspend () -> T, 82 | attempt: Int, 83 | e: Throwable? = null 84 | ): Result { 85 | return if (attempt <= maxRetries) { 86 | retryWithAttempts(operation, attempt) 87 | } else { 88 | e?.let { 89 | Err(it, maxRetries) 90 | } ?: Err(RetryException("Result validation failed."), maxRetries) 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/ConstantStrategy.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | /** 4 | * A simple backoff strategy that constantly returns the same value. 5 | * The specified jitter is applied to the interval. 6 | */ 7 | data class ConstantStrategy( 8 | 9 | /** 10 | * The constant delay interval in milliseconds. 11 | */ 12 | private val delayMs: Long = 100L, 13 | 14 | /** 15 | * The relative jitter factor applied to the interval. 16 | * Specify 1.0 for full jitter, 0.0 for no jitter. 17 | * No jitter by default. 18 | */ 19 | private val jitterFactor: Double = 0.0 20 | 21 | ) : Strategy, Jitter { 22 | 23 | init { 24 | require(delayMs > 0) 25 | require(jitterFactor in 0.0..1.0) 26 | } 27 | 28 | override fun nextDelay( 29 | attempt: Int 30 | ): Long { 31 | return withJitter(delayMs, jitterFactor) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/ExponentialStrategy.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | import java.lang.Long.min 4 | import kotlin.math.pow 5 | 6 | /** 7 | * A strategy in which the next delay interval is calculated using 8 | * `baseDelayMs * expBase.pow(attempt)` where: 9 | * - baseDelayMs is the base delay in milliseconds. 10 | * - attempt is the number of unsuccessful attempts that have been made. 11 | * - expBase is the exponent base configured for the strategy. 12 | * 13 | * The specified jitter and scale factor are applied to the calculated interval. 14 | * The delay time cannot exceed the specified maximum delay in milliseconds. 15 | */ 16 | data class ExponentialStrategy( 17 | 18 | /** 19 | * The base delay in milliseconds. 20 | */ 21 | private val baseDelayMs: Long = 100L, 22 | 23 | /** 24 | * The maximum delay in milliseconds. 25 | */ 26 | private val maxDelayMs: Long = 10000L, 27 | 28 | /** 29 | * The exponent base. 30 | */ 31 | private val expBase: Int = 2, 32 | 33 | /** 34 | * The relative jitter factor applied to the interval. 35 | * Specify 1.0 for full jitter, 0.0 for no jitter. 36 | */ 37 | private val jitterFactor: Double = 0.1, 38 | 39 | /** 40 | * The scale factor by which to multiply the calculated interval. 41 | */ 42 | private val scaleFactor: Double = 1.0 43 | 44 | ) : Strategy, Jitter { 45 | 46 | init { 47 | require(baseDelayMs > 0) 48 | require(maxDelayMs > 0) 49 | require(expBase > 0) 50 | require(jitterFactor in 0.0..1.0) 51 | require(scaleFactor > 0) 52 | } 53 | 54 | override fun nextDelay( 55 | attempt: Int, 56 | ): Long { 57 | val expInterval = (baseDelayMs * expBase.toDouble().pow(attempt.toDouble())).toLong() 58 | return min( 59 | maxDelayMs, 60 | (withJitter(expInterval, jitterFactor) * scaleFactor).toLong() 61 | ) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/FixedStrategy.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | import io.github.reugn.kotlin.backoff.util.RetryException 4 | 5 | /** 6 | * A strategy that returns the delay time as a fixed value determined by the attempt number. 7 | */ 8 | data class FixedStrategy( 9 | 10 | /** 11 | * The list of the fixed intervals in milliseconds. 12 | */ 13 | private val intervalsMs: List 14 | 15 | ) : Strategy { 16 | 17 | init { 18 | require(intervalsMs.isNotEmpty()) 19 | } 20 | 21 | override fun nextDelay(attempt: Int): Long { 22 | try { 23 | return intervalsMs.elementAt(attempt - 1) 24 | } catch (e: IndexOutOfBoundsException) { 25 | throw RetryException(e) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/Jitter.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | import kotlin.random.Random 4 | 5 | /** 6 | * Represents the jitter trait for backoff strategies. 7 | */ 8 | interface Jitter { 9 | 10 | /** 11 | * Applies jitter to the delay interval using the specified relative factor. 12 | */ 13 | fun withJitter(delayInterval: Long, jitterFactor: Double): Long { 14 | require(jitterFactor in 0.0..1.0) 15 | 16 | val from = (delayInterval * (1 - jitterFactor)).toLong() 17 | if (from == delayInterval) { 18 | return delayInterval 19 | } 20 | 21 | return Random.nextLong( 22 | from, 23 | delayInterval 24 | ) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/PolynomialStrategy.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | import java.lang.Long.min 4 | import kotlin.math.pow 5 | 6 | /** 7 | * A strategy in which the next delay interval is calculated using 8 | * `baseDelayMs * attempt.pow(exponent)` where: 9 | * - baseDelayMs is the base delay in milliseconds. 10 | * - attempt is the number of unsuccessful attempts that have been made. 11 | * - exponent is the exponent configured for the strategy. 12 | * 13 | * The specified jitter and scale factor are applied to the calculated interval. 14 | * The delay time cannot exceed the specified maximum delay in milliseconds. 15 | */ 16 | data class PolynomialStrategy( 17 | 18 | /** 19 | * The base delay in milliseconds. 20 | */ 21 | private val baseDelayMs: Long = 100L, 22 | 23 | /** 24 | * The maximum delay in milliseconds. 25 | */ 26 | private val maxDelayMs: Long = 10000L, 27 | 28 | /** 29 | * The exponent. 30 | */ 31 | private val exponent: Int = 2, 32 | 33 | /** 34 | * The relative jitter factor applied to the interval. 35 | * Specify 1.0 for full jitter, 0.0 for no jitter. 36 | */ 37 | private val jitterFactor: Double = 0.1, 38 | 39 | /** 40 | * The scale factor by which to multiply the calculated interval. 41 | */ 42 | private val scaleFactor: Double = 1.0 43 | 44 | ) : Strategy, Jitter { 45 | 46 | init { 47 | require(baseDelayMs > 0) 48 | require(maxDelayMs > 0) 49 | require(exponent > 0) 50 | require(jitterFactor in 0.0..1.0) 51 | require(scaleFactor > 0) 52 | } 53 | 54 | override fun nextDelay( 55 | attempt: Int 56 | ): Long { 57 | val polInterval = (baseDelayMs * attempt.toDouble().pow(exponent.toDouble())).toLong() 58 | return min( 59 | maxDelayMs, 60 | (withJitter(polInterval, jitterFactor) * scaleFactor).toLong() 61 | ) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/strategy/Strategy.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.strategy 2 | 3 | /** 4 | * This is the base interface type for all backoff strategies. 5 | */ 6 | interface Strategy { 7 | 8 | /** 9 | * Calculates and returns a delay interval for the next retry. 10 | */ 11 | fun nextDelay(attempt: Int): Long 12 | } 13 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/util/ErrorValidator.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.util 2 | 3 | typealias ErrorValidator = (Throwable) -> Boolean 4 | 5 | /** 6 | * Returns true if the provided Throwable is to be considered non-fatal, 7 | * or false if it is to be considered fatal. 8 | */ 9 | fun nonFatal(e: Throwable): Boolean { 10 | return when (e) { 11 | is VirtualMachineError, is ThreadDeath, is InterruptedException, is LinkageError -> false 12 | else -> true 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/util/Result.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.util 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | /** 6 | * Result is a type that represents either success [Ok] or failure [Err]. 7 | */ 8 | @Serializable 9 | sealed class Result { 10 | 11 | abstract val retries: Int 12 | 13 | abstract fun isOk(): Boolean 14 | 15 | abstract fun isErr(): Boolean 16 | } 17 | 18 | /** 19 | * The [Result] that contains a success value. 20 | */ 21 | @Serializable 22 | data class Ok( 23 | val value: T, 24 | override val retries: Int 25 | ) : Result() { 26 | 27 | override fun isOk(): Boolean = true 28 | 29 | override fun isErr(): Boolean = false 30 | } 31 | 32 | /** 33 | * The [Result] that contains an error value. 34 | */ 35 | @Serializable 36 | data class Err( 37 | val value: E, 38 | override val retries: Int 39 | ) : Result() { 40 | 41 | override fun isOk(): Boolean = false 42 | 43 | override fun isErr(): Boolean = true 44 | } 45 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/util/ResultValidator.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.util 2 | 3 | typealias ResultValidator = (T) -> Boolean 4 | 5 | /** 6 | * Returns true for any result. 7 | */ 8 | @Suppress("UNUSED_PARAMETER") 9 | fun acceptAny(result: T): Boolean { 10 | return true 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/reugn/kotlin/backoff/util/RetryException.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff.util 2 | 3 | /** 4 | * Thrown to indicate that a retry has failed. 5 | */ 6 | class RetryException : Exception { 7 | 8 | constructor(message: String) : super(message) 9 | 10 | constructor(e: Throwable) : super(e) 11 | } 12 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/ConstantStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.ConstantStrategy 4 | import io.github.reugn.kotlin.backoff.util.Err 5 | import io.github.reugn.kotlin.backoff.util.Ok 6 | import kotlinx.coroutines.runBlocking 7 | import org.junit.jupiter.api.Assertions.assertEquals 8 | import org.junit.jupiter.api.Test 9 | import org.junit.jupiter.api.fail 10 | import kotlin.system.measureTimeMillis 11 | 12 | class ConstantStrategyTest { 13 | 14 | @Test 15 | fun `Constant strategy`() { 16 | val backoff = StrategyBackoff( 17 | strategy = ConstantStrategy(), 18 | resultValidator = { i -> i == 1 }, 19 | ) 20 | val t = measureTimeMillis { 21 | when (val v = runBlocking { backoff.retry { 1 } }) { 22 | is Ok -> { 23 | assertEquals(1, v.value) 24 | assertEquals(1, v.retries) 25 | } 26 | else -> { 27 | fail("Retry failed") 28 | } 29 | } 30 | } 31 | assert(t < 200) 32 | } 33 | 34 | @Test 35 | fun `Constant strategy next interval`() { 36 | val strategy = ConstantStrategy() 37 | var interval = 0L 38 | for (attempt in 1..4) { 39 | interval = strategy.nextDelay(attempt) 40 | } 41 | assertEquals(100, interval) 42 | } 43 | 44 | @Test 45 | fun `Constant strategy failure`() { 46 | val backoff = StrategyBackoff( 47 | strategy = ConstantStrategy(), 48 | ) 49 | val t = measureTimeMillis { 50 | when (val v = runBlocking { backoff.retry { throw Exception() } }) { 51 | is Err -> { 52 | assert(v.value is Exception) 53 | assertEquals(3, v.retries) 54 | } 55 | else -> { 56 | fail("Retry succeed") 57 | } 58 | } 59 | } 60 | assert(t < 450) 61 | } 62 | 63 | @Test 64 | fun `Constant strategy with jitter`() { 65 | val backoff = StrategyBackoff( 66 | strategy = ConstantStrategy(jitterFactor = 0.5), 67 | resultValidator = { i -> i == 1 }, 68 | ) 69 | val t = measureTimeMillis { 70 | when (val v = runBlocking { backoff.retry { 1 } }) { 71 | is Ok -> { 72 | assertEquals(1, v.value) 73 | assertEquals(1, v.retries) 74 | } 75 | else -> { 76 | fail("Retry failed") 77 | } 78 | } 79 | } 80 | assert(t < 150) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/ExponentialStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.ExponentialStrategy 4 | import io.github.reugn.kotlin.backoff.util.Err 5 | import io.github.reugn.kotlin.backoff.util.Ok 6 | import kotlinx.coroutines.runBlocking 7 | import org.junit.jupiter.api.Assertions.assertEquals 8 | import org.junit.jupiter.api.Test 9 | import org.junit.jupiter.api.fail 10 | import kotlin.system.measureTimeMillis 11 | 12 | class ExponentialStrategyTest { 13 | 14 | @Test 15 | fun `Exponential strategy no jitter`() { 16 | val backoff = StrategyBackoff( 17 | strategy = ExponentialStrategy(jitterFactor = 0.0), 18 | resultValidator = { i -> i == 1 }, 19 | ) 20 | val t = measureTimeMillis { 21 | when (val v = runBlocking { backoff.retry { 1 } }) { 22 | is Ok -> { 23 | assertEquals(1, v.value) 24 | assertEquals(1, v.retries) 25 | } 26 | else -> { 27 | fail("Retry failed") 28 | } 29 | } 30 | } 31 | assert(t < 300) 32 | } 33 | 34 | @Test 35 | fun `Exponential strategy next interval`() { 36 | val strategy = ExponentialStrategy(jitterFactor = 0.0) 37 | var interval = 0L 38 | for (attempt in 1..5) { 39 | interval = strategy.nextDelay(attempt) 40 | } 41 | assertEquals(3200, interval) 42 | } 43 | 44 | @Test 45 | fun `Exponential strategy retryable error`() { 46 | val backoff = StrategyBackoff( 47 | maxRetries = 2, 48 | strategy = ExponentialStrategy(), 49 | ) 50 | when (val v = runBlocking { backoff.retry { throw Exception() } }) { 51 | is Err -> { 52 | assert(v.value is Exception) 53 | assertEquals(2, v.retries) 54 | } 55 | else -> { 56 | fail("Retry succeed") 57 | } 58 | } 59 | } 60 | 61 | @Test 62 | fun `Exponential strategy unretryable error`() { 63 | val backoff = StrategyBackoff( 64 | maxRetries = 4, 65 | strategy = ExponentialStrategy(), 66 | ) 67 | when (val v = runBlocking { backoff.retry { throw InterruptedException() } }) { 68 | is Err -> { 69 | assert(v.value is InterruptedException) 70 | assertEquals(1, v.retries) 71 | } 72 | else -> { 73 | fail("Retry succeed") 74 | } 75 | } 76 | } 77 | 78 | @Test 79 | fun `Exponential strategy with jitter`() { 80 | val backoff = StrategyBackoff( 81 | strategy = ExponentialStrategy(jitterFactor = 0.5), 82 | resultValidator = { i -> i == 1 }, 83 | ) 84 | val t = measureTimeMillis { 85 | when (val v = runBlocking { backoff.retry { 1 } }) { 86 | is Ok -> { 87 | assertEquals(1, v.value) 88 | assertEquals(1, v.retries) 89 | } 90 | else -> { 91 | fail("Retry failed") 92 | } 93 | } 94 | } 95 | assert(t < 250) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/FixedStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.FixedStrategy 4 | import io.github.reugn.kotlin.backoff.util.Err 5 | import io.github.reugn.kotlin.backoff.util.Ok 6 | import io.github.reugn.kotlin.backoff.util.RetryException 7 | import kotlinx.coroutines.runBlocking 8 | import org.junit.jupiter.api.Assertions.assertEquals 9 | import org.junit.jupiter.api.Test 10 | import org.junit.jupiter.api.fail 11 | import kotlin.system.measureTimeMillis 12 | 13 | class FixedStrategyTest { 14 | 15 | @Test 16 | fun `Fixed strategy`() { 17 | val backoff = StrategyBackoff( 18 | strategy = FixedStrategy(listOf(50)), 19 | resultValidator = { i -> i == 1 }, 20 | ) 21 | val t = measureTimeMillis { 22 | when (val v = runBlocking { backoff.retry { 1 } }) { 23 | is Ok -> { 24 | assertEquals(1, v.value) 25 | assertEquals(1, v.retries) 26 | } 27 | else -> { 28 | fail("Retry failed") 29 | } 30 | } 31 | } 32 | assert(t < 130) 33 | } 34 | 35 | @Test 36 | fun `Fixed strategy next interval`() { 37 | val intervalList = listOf(100, 50, 450, 1000) 38 | val strategy = FixedStrategy(intervalList) 39 | for (attempt in 1..4) { 40 | val interval = strategy.nextDelay(attempt) 41 | assertEquals(intervalList.elementAt(attempt - 1), interval) 42 | } 43 | } 44 | 45 | @Test 46 | fun `Fixed strategy internal error`() { 47 | val backoff = StrategyBackoff( 48 | maxRetries = 5, 49 | strategy = FixedStrategy(listOf(50, 100)), 50 | resultValidator = { i -> i == 1 }, 51 | ) 52 | when (val v = runBlocking { backoff.retry { throw Exception() } }) { 53 | is Err -> { 54 | assert(v.value is RetryException) 55 | assertEquals(3, v.retries) 56 | } 57 | else -> { 58 | fail("Retry succeed") 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/JitterTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.Jitter 4 | import org.junit.jupiter.api.Assertions.assertEquals 5 | import org.junit.jupiter.api.Test 6 | 7 | class JitterTest { 8 | 9 | private val jitterObject = object : Jitter {} 10 | 11 | @Test 12 | fun `Low jitter bound`() { 13 | assertEquals(1000L, jitterObject.withJitter(1000L, 0.0)) 14 | } 15 | 16 | @Test 17 | fun `High jitter bound`() { 18 | for (i in 1..10) { 19 | val interval = jitterObject.withJitter(1000L, 1.0) 20 | assert(interval in 0L..1000L) 21 | } 22 | } 23 | 24 | @Test 25 | fun `Jitter bound`() { 26 | for (i in 1..10) { 27 | val interval = jitterObject.withJitter(1000L, 0.1) 28 | assert(interval in 900L..1000L) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/PolynomialStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.PolynomialStrategy 4 | import io.github.reugn.kotlin.backoff.util.Err 5 | import io.github.reugn.kotlin.backoff.util.Ok 6 | import kotlinx.coroutines.runBlocking 7 | import org.junit.jupiter.api.Assertions.assertEquals 8 | import org.junit.jupiter.api.Test 9 | import org.junit.jupiter.api.fail 10 | import kotlin.system.measureTimeMillis 11 | 12 | class PolynomialStrategyTest { 13 | 14 | @Test 15 | fun `Polynomial strategy no jitter`() { 16 | val backoff = StrategyBackoff( 17 | strategy = PolynomialStrategy(jitterFactor = 0.0), 18 | resultValidator = { i -> i == 1 }, 19 | ) 20 | val t = measureTimeMillis { 21 | when (val v = runBlocking { backoff.retry { 1 } }) { 22 | is Ok -> { 23 | assertEquals(1, v.value) 24 | assertEquals(1, v.retries) 25 | } 26 | else -> { 27 | fail("Retry failed") 28 | } 29 | } 30 | } 31 | assert(t < 200) 32 | } 33 | 34 | @Test 35 | fun `Polynomial strategy next interval`() { 36 | val strategy = PolynomialStrategy(jitterFactor = 0.0) 37 | var interval = 0L 38 | for (attempt in 1..5) { 39 | interval = strategy.nextDelay(attempt) 40 | } 41 | assertEquals(2500, interval) 42 | } 43 | 44 | @Test 45 | fun `Polynomial strategy retryable error`() { 46 | val backoff = StrategyBackoff( 47 | maxRetries = 2, 48 | strategy = PolynomialStrategy(), 49 | ) 50 | when (val v = runBlocking { backoff.retry { throw Exception() } }) { 51 | is Err -> { 52 | assert(v.value is Exception) 53 | assertEquals(2, v.retries) 54 | } 55 | else -> { 56 | fail("Retry succeed") 57 | } 58 | } 59 | } 60 | 61 | @Test 62 | fun `Polynomial strategy unretryable error`() { 63 | val backoff = StrategyBackoff( 64 | maxRetries = 4, 65 | strategy = PolynomialStrategy(), 66 | ) 67 | when (val v = runBlocking { backoff.retry { throw InterruptedException() } }) { 68 | is Err -> { 69 | assert(v.value is InterruptedException) 70 | assertEquals(1, v.retries) 71 | } 72 | else -> { 73 | fail("Retry succeed") 74 | } 75 | } 76 | } 77 | 78 | @Test 79 | fun `Polynomial strategy with jitter`() { 80 | val backoff = StrategyBackoff( 81 | strategy = PolynomialStrategy(jitterFactor = 0.5), 82 | resultValidator = { i -> i == 1 }, 83 | ) 84 | val t = measureTimeMillis { 85 | when (val v = runBlocking { backoff.retry { 1 } }) { 86 | is Ok -> { 87 | assertEquals(1, v.value) 88 | assertEquals(1, v.retries) 89 | } 90 | else -> { 91 | fail("Retry failed") 92 | } 93 | } 94 | } 95 | assert(t < 150) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/reugn/kotlin/backoff/RemoteURLTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.reugn.kotlin.backoff 2 | 3 | import io.github.reugn.kotlin.backoff.strategy.ExponentialStrategy 4 | import io.github.reugn.kotlin.backoff.util.nonFatal 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlinx.coroutines.runBlocking 7 | import kotlinx.coroutines.withContext 8 | import org.junit.jupiter.api.Assertions.assertEquals 9 | import org.junit.jupiter.api.Test 10 | import java.net.URL 11 | 12 | @Suppress("BlockingMethodInNonBlockingContext") 13 | class RemoteURLTest { 14 | 15 | private suspend fun urlAction(): String = withContext(Dispatchers.IO) { 16 | URL("http://worldclockapi.com/api/json/utc/now").readText() 17 | } 18 | 19 | @Test 20 | fun `remote URL`() { 21 | val backoff = StrategyBackoff( 22 | maxRetries = 3, 23 | strategy = ExponentialStrategy(), 24 | errorValidator = ::nonFatal, 25 | resultValidator = { s -> s.isNotEmpty() }, 26 | ) 27 | val result = runBlocking { backoff.withRetries(::urlAction) } 28 | 29 | assert(result.isOk()) 30 | assertEquals(result.retries, 0) 31 | } 32 | } 33 | --------------------------------------------------------------------------------