generated from Kotlin/multiplatform-library-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from kresil/ktor-retry-plugin
Issue (kresil/kresil#7): Includes examples and documentation for the Ktor retry plugin
- Loading branch information
Showing
25 changed files
with
747 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Ktor Retry Plugin | ||
|
||
### Install | ||
|
||
The `HttpRequestRetry` plugin can be installed using the `install` function | ||
and configured using its **last parameter function** | ||
(_trailing lambda_), as with other Ktor plugins. | ||
|
||
The plugin is part of the `ktor-client-core` module. | ||
|
||
### Configuration | ||
|
||
| Property | Description | | ||
|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ||
| `maxRetries` | The maximum number of retries | | | ||
| `retryIf` | A lambda that returns `true` if the request should be retried on specific request details and or responses. | | ||
| `retryOnExceptionIf` | A lambda that returns `true` if the request should be retried on specific request details and or exceptions that occurred. | | ||
| `delayMillis` | A lambda that returns the delay in milliseconds before the next retry. Some methods are provided to create more complex delays, such as `exponentialDelay()` or `constantDelay()`. | | ||
|
||
> [!NOTE] | ||
> The plugin also provides more specific methods to retry for | ||
> (e.g., on server errors, for example, `retryOnServerErrors()` retries on server 5xx errors). | ||
Example: | ||
|
||
```kotlin | ||
val client = HttpClient(CIO) { | ||
install(HttpRequestRetry) { | ||
maxRetries = 5 | ||
retryIf { request, response -> | ||
!response.status.isSuccess() | ||
} | ||
retryOnExceptionIf { request, cause -> | ||
cause is NetworkError | ||
} | ||
delayMillis { retry -> | ||
retry * 3000L | ||
} // retries in 3, 6, 9, etc. seconds | ||
} | ||
// other configurations | ||
} | ||
``` | ||
|
||
Default configuration: | ||
|
||
```kotlin | ||
install(HttpRequestRetry) { | ||
retryOnExceptionOrServerErrors(3) | ||
exponentialDelay() | ||
} | ||
``` | ||
|
||
### Changing a Request Before Retry | ||
|
||
It is possible to modify the request | ||
before retrying it by using the `modifyRequest` method inside the configuration block of the plugin. | ||
This method receives a lambda that takes the request and returns the modified request. | ||
One usage example is to add a header with the current retry count: | ||
|
||
```kotlin | ||
val client = HttpClient(CIO) { | ||
install(HttpRequestRetry) { | ||
modifyRequest { request -> | ||
request.headers.append("x-retry-count", retryCount.toString()) | ||
} | ||
} | ||
// other configurations | ||
} | ||
``` | ||
|
||
> [!IMPORTANT] | ||
> To preserve configuration context between retry attempts, the plugin uses request attibutes to store data. | ||
> If those are altered, the plugin may not work as expected. | ||
> | ||
> If an attribute is not present in the request, the plugin will use the default configuration associated with that attribute. | ||
> Such behaviour can be seen in the source code: | ||
> - [after applying configuration](https://github.com/ktorio/ktor/blob/7c76fa7c0f2b7dcc6e0445da8612d75bb5d11609/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt#L366-L373) | ||
> - [before each retry attempt](https://github.com/ktorio/ktor/blob/7c76fa7c0f2b7dcc6e0445da8612d75bb5d11609/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt#L267-L274) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Client Retry | ||
|
||
A sample Ktor project showing how to use the [HttpRequestRetry](https://ktor.io/docs/client-retry.html) plugin. | ||
|
||
## Running | ||
|
||
This client sample uses the server from the [simulate-slow-server](../simulate-slow-server) example. | ||
The server sample has the `/error` route that returns the `200 OK` response from the third attempt only. | ||
|
||
To see `HttpRequestRetry` in action, run this example by executing the following command: | ||
|
||
```bash | ||
./gradlew :client-retry:run | ||
``` | ||
|
||
The client will send three consequent requests automatically to get a success response from the server. | ||
|
||
> Note that this example uses the [Logging](https://ktor.io/docs/client-logging.html) plugin to show all requests in a console. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
plugins { | ||
application | ||
alias(libs.plugins.kotlinJvm) | ||
} | ||
|
||
application { | ||
mainClass.set("application.ApplicationKt") | ||
} | ||
|
||
repositories { | ||
mavenCentral() | ||
maven { url = uri("https://maven.pkg.jetbrains.space/public/p/ktor/eap") } | ||
} | ||
|
||
dependencies { | ||
implementation(libs.ktor.client.core) | ||
implementation(libs.ktor.client.cio) | ||
implementation(libs.ktor.client.logging) | ||
implementation(libs.ktor.server.core) | ||
implementation(libs.ktor.server.cio) | ||
implementation(libs.ktor.server.hostcommon) | ||
implementation(libs.logback.classic) | ||
implementation(project(":simulate-slow-server")) | ||
implementation(project(":end-to-end-utilities")) | ||
testImplementation(libs.junit) | ||
testImplementation(libs.hamcrest) | ||
} |
28 changes: 28 additions & 0 deletions
28
ktor-retry-plugin/client-retry/src/main/kotlin/application/Application.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package application | ||
|
||
import e2e.* | ||
import io.ktor.client.* | ||
import io.ktor.client.engine.cio.* | ||
import io.ktor.client.plugins.* | ||
import io.ktor.client.plugins.logging.* | ||
import io.ktor.client.request.* | ||
import io.ktor.client.statement.* | ||
import io.ktor.server.application.* | ||
import kotlinx.coroutines.* | ||
import slowserver.main | ||
|
||
fun main() { | ||
defaultServer(Application::main).start() | ||
runBlocking { | ||
val client = HttpClient(CIO) { | ||
install(HttpRequestRetry) { | ||
retryOnServerErrors(maxRetries = 5) | ||
exponentialDelay() | ||
} | ||
install(Logging) { level = LogLevel.INFO } | ||
} | ||
|
||
val response: HttpResponse = client.get("http://0.0.0.0:8080/error") | ||
println(response.bodyAsText()) | ||
} | ||
} |
44 changes: 44 additions & 0 deletions
44
ktor-retry-plugin/client-retry/src/test/kotlin/application/ApplicationTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package application | ||
|
||
import e2e.readString | ||
import e2e.runGradleAppWaiting | ||
import kotlinx.coroutines.runBlocking | ||
import org.junit.* | ||
import org.junit.Assert.* | ||
import java.io.File | ||
|
||
class ApplicationTest { | ||
|
||
companion object { | ||
private const val GRADLEW_WINDOWS = "gradlew.bat" | ||
private const val GRADLEW_UNIX = "gradlew" | ||
|
||
@JvmStatic | ||
fun findGradleWrapper(): String { | ||
val currentDir = File(System.getProperty("user.dir")) | ||
val parentDir = currentDir.parent ?: error("Cannot find parent directory of $currentDir") | ||
val gradlewName = if (System.getProperty("os.name").startsWith("Windows")) { | ||
GRADLEW_WINDOWS | ||
} else { | ||
GRADLEW_UNIX | ||
} | ||
val gradlewFile = File(parentDir, gradlewName) | ||
check(gradlewFile.exists()) { "Gradle Wrapper not found at ${gradlewFile.absolutePath}" } | ||
return gradlewFile.absolutePath | ||
} | ||
} | ||
|
||
@Before | ||
fun setup() { | ||
System.setProperty("gradlew", findGradleWrapper()) | ||
} | ||
|
||
@Test | ||
fun outputContainsAllResponses() = runBlocking { | ||
runGradleAppWaiting().inputStream.readString().let { outputString -> | ||
assertTrue(outputString.contains("RESPONSE: 500 Internal Server Error")) | ||
assertTrue(outputString.contains("RESPONSE: 200 OK")) | ||
assertTrue(outputString.contains("Server is back online!")) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# End-to-end utilities | ||
|
||
This project isn't runnable and contains helper classes and functions for testing samples from this repository. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
plugins { | ||
alias(libs.plugins.kotlinJvm) | ||
} | ||
|
||
repositories { | ||
mavenCentral() | ||
maven { url = uri("https://maven.pkg.jetbrains.space/public/p/ktor/eap") } | ||
} | ||
|
||
dependencies { | ||
implementation(libs.ktor.server.core) | ||
implementation(libs.ktor.server.cio) | ||
} |
16 changes: 16 additions & 0 deletions
16
ktor-retry-plugin/end-to-end-utilities/src/main/kotlin/e2e/defaultServer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package e2e | ||
|
||
import io.ktor.server.application.* | ||
import io.ktor.server.cio.* | ||
import io.ktor.server.engine.* | ||
import org.slf4j.helpers.NOPLogger | ||
|
||
fun defaultServer(module: Application.() -> Unit) = embeddedServer(CIO, environment = applicationEngineEnvironment { | ||
log = NOPLogger.NOP_LOGGER | ||
|
||
connector { | ||
port = 8080 | ||
} | ||
|
||
module(module) | ||
}) |
21 changes: 21 additions & 0 deletions
21
ktor-retry-plugin/end-to-end-utilities/src/main/kotlin/e2e/gradleProcess.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package e2e | ||
|
||
import java.io.InputStream | ||
|
||
fun runGradleAppWaiting(): Process = runGradleWaiting("run") | ||
fun runGradleApp(): Process = runGradle("run") | ||
|
||
fun runGradleWaiting(vararg args: String): Process { | ||
val process = runGradle(*args) | ||
process.waitFor() | ||
return process | ||
} | ||
|
||
fun runGradle(vararg args: String): Process { | ||
val gradlewPath = | ||
System.getProperty("gradlew") ?: error("System property 'gradlew' should point to Gradle Wrapper file") | ||
val processArgs = listOf(gradlewPath, "-Dorg.gradle.logging.level=quiet", "--quiet") + args | ||
return ProcessBuilder(processArgs).start() | ||
} | ||
|
||
fun InputStream.readString(): String = readAllBytes().toString(Charsets.UTF_8) |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
distributionBase=GRADLE_USER_HOME | ||
distributionPath=wrapper/dists | ||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip | ||
networkTimeout=10000 | ||
validateDistributionUrl=true | ||
zipStoreBase=GRADLE_USER_HOME | ||
zipStorePath=wrapper/dists |
Oops, something went wrong.