Skip to content

Commit

Permalink
Fix condition-wrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
osipxd committed Dec 9, 2024
1 parent ea0216c commit cf05f00
Show file tree
Hide file tree
Showing 22 changed files with 128 additions and 113 deletions.
1 change: 0 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ ktlint_standard_annotation = disabled
ktlint_standard_class-naming = disabled
ktlint_standard_class-signature = disabled
ktlint_standard_comment-wrapping = disabled
ktlint_standard_condition-wrapping = disabled
ktlint_standard_filename = disabled
ktlint_standard_function-expression-body = disabled
ktlint_standard_function-signature = disabled
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.util.date.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlinx.coroutines.CompletableDeferred
import kotlin.coroutines.CoroutineContext

internal data class RequestTask(
val request: HttpRequestData,
Expand All @@ -19,9 +19,11 @@ internal data class RequestTask(
)

@OptIn(InternalAPI::class)
internal fun HttpRequestData.requiresDedicatedConnection(): Boolean = listOf(headers, body.headers).any {
it[HttpHeaders.Connection] == "close" || it.contains(HttpHeaders.Upgrade)
} || method !in listOf(HttpMethod.Get, HttpMethod.Head) || containsCustomTimeouts() || isSseRequest()
internal fun HttpRequestData.requiresDedicatedConnection(): Boolean =
listOf(headers, body.headers).any { it[HttpHeaders.Connection] == "close" || it.contains(HttpHeaders.Upgrade) } ||
method !in listOf(HttpMethod.Get, HttpMethod.Head) ||
containsCustomTimeouts() ||
isSseRequest()

internal data class ConnectionResponseTask(
val requestTime: GMTDate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,23 +240,25 @@ public val HttpRequestRetry: ClientPlugin<HttpRequestRetryConfig> = createClient
maxRetries: Int,
shouldRetry: HttpRetryShouldRetryContext.(HttpRequest, HttpResponse) -> Boolean,
call: HttpClientCall
) = retryCount < maxRetries && shouldRetry(
HttpRetryShouldRetryContext(retryCount + 1),
call.request,
call.response
)
) = retryCount < maxRetries &&
shouldRetry(
HttpRetryShouldRetryContext(retryCount + 1),
call.request,
call.response
)

fun shouldRetryOnException(
retryCount: Int,
maxRetries: Int,
shouldRetry: HttpRetryShouldRetryContext.(HttpRequestBuilder, Throwable) -> Boolean,
subRequest: HttpRequestBuilder,
cause: Throwable
) = retryCount < maxRetries && shouldRetry(
HttpRetryShouldRetryContext(retryCount + 1),
subRequest,
cause
)
) = retryCount < maxRetries &&
shouldRetry(
HttpRetryShouldRetryContext(retryCount + 1),
subRequest,
cause
)

fun prepareRequest(request: HttpRequestBuilder): HttpRequestBuilder {
val subRequest = HttpRequestBuilder().takeFrom(request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ public data class LegacyPinnedCertificate(
other = pattern,
otherOffset = 3,
length = suffixLength
) && (prefixLength == 0 || hostname[prefixLength - 1] == '.')
) &&
(prefixLength == 0 || hostname[prefixLength - 1] == '.')
}

pattern.startsWith("*.") -> {
// With * there must be a prefix so include the dot in regionMatches().
val suffixLength = pattern.length - 1
Expand All @@ -52,8 +54,10 @@ public data class LegacyPinnedCertificate(
other = pattern,
otherOffset = 1,
length = suffixLength
) && hostname.lastIndexOf('.', prefixLength - 1) == -1
) &&
hostname.lastIndexOf('.', prefixLength - 1) == -1
}

else -> hostname == pattern
}

Expand All @@ -68,8 +72,8 @@ public data class LegacyPinnedCertificate(
*/
public fun new(pattern: String, pin: String): LegacyPinnedCertificate {
require(
pattern.startsWith("*.") && pattern.indexOf("*", 1) == -1 ||
pattern.startsWith("**.") && pattern.indexOf("*", 2) == -1 ||
(pattern.startsWith("*.") && pattern.indexOf("*", 1) == -1) ||
(pattern.startsWith("**.") && pattern.indexOf("*", 2) == -1) ||
pattern.indexOf("*") == -1
) {
"Unexpected pattern: $pattern"
Expand All @@ -84,6 +88,7 @@ public data class LegacyPinnedCertificate(
hash = hash
)
}

pin.startsWith(HASH_ALGORITHM_SHA_256) -> {
val hash = pin.substring(HASH_ALGORITHM_SHA_256.length)
LegacyPinnedCertificate(
Expand All @@ -92,6 +97,7 @@ public data class LegacyPinnedCertificate(
hash = hash
)
}

else -> throw IllegalArgumentException(
"Pins must start with '$HASH_ALGORITHM_SHA_256' or '$HASH_ALGORITHM_SHA_1': $pin"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ public data class PinnedCertificate(
other = pattern,
otherOffset = 3,
length = suffixLength
) && (prefixLength == 0 || hostname[prefixLength - 1] == '.')
) &&
(prefixLength == 0 || hostname[prefixLength - 1] == '.')
}

pattern.startsWith("*.") -> {
// With * there must be a prefix so include the dot in regionMatches().
val suffixLength = pattern.length - 1
Expand All @@ -52,8 +54,10 @@ public data class PinnedCertificate(
other = pattern,
otherOffset = 1,
length = suffixLength
) && hostname.lastIndexOf('.', prefixLength - 1) == -1
) &&
hostname.lastIndexOf('.', prefixLength - 1) == -1
}

else -> hostname == pattern
}

Expand All @@ -68,8 +72,8 @@ public data class PinnedCertificate(
*/
public fun new(pattern: String, pin: String): PinnedCertificate {
require(
pattern.startsWith("*.") && pattern.indexOf("*", 1) == -1 ||
pattern.startsWith("**.") && pattern.indexOf("*", 2) == -1 ||
(pattern.startsWith("*.") && pattern.indexOf("*", 1) == -1) ||
(pattern.startsWith("**.") && pattern.indexOf("*", 2) == -1) ||
pattern.indexOf("*") == -1
) {
"Unexpected pattern: $pattern"
Expand All @@ -84,6 +88,7 @@ public data class PinnedCertificate(
hash = hash
)
}

pin.startsWith(HASH_ALGORITHM_SHA_256) -> {
val hash = pin.substring(HASH_ALGORITHM_SHA_256.length)
PinnedCertificate(
Expand All @@ -92,6 +97,7 @@ public data class PinnedCertificate(
hash = hash
)
}

else -> throw IllegalArgumentException(
"Pins must start with '$HASH_ALGORITHM_SHA_256' or '$HASH_ALGORITHM_SHA_1': $pin"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ package io.ktor.client.engine.okhttp
import io.ktor.client.plugins.sse.*
import io.ktor.http.*
import io.ktor.sse.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import okhttp3.*
import okhttp3.sse.*
import kotlin.coroutines.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources
import kotlin.coroutines.CoroutineContext

internal class OkHttpSSESession(
engine: OkHttpClient,
Expand Down Expand Up @@ -64,18 +70,22 @@ internal class OkHttpSSESession(
}

private fun mapException(response: Response?): SSEClientException {
fun unexpectedError() = SSEClientException(message = "Unexpected error occurred in OkHttpSSESession")

return when {
response != null && response.code != HttpStatusCode.OK.value ->
response == null -> unexpectedError()

response.code != HttpStatusCode.OK.value ->
SSEClientException(message = "Expected status code ${HttpStatusCode.OK.value} but was ${response.code}")

response != null && response.headers[HttpHeaders.ContentType]
response.headers[HttpHeaders.ContentType]
?.let { ContentType.parse(it) }?.withoutParameters() != ContentType.Text.EventStream ->
@Suppress("ktlint:standard:max-line-length")
SSEClientException(
message = "Content type must be ${ContentType.Text.EventStream} but was ${response.headers[HttpHeaders.ContentType]}"
)

else -> SSEClientException(message = "Unexpected error occurred in OkHttpSSESession")
else -> unexpectedError()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ actual abstract class ClientLoader actual constructor(val timeoutSeconds: Int) {
onlyWithEngine: String?
): Boolean {
val engineName = engine.toString()
return onlyWithEngine != null && !onlyWithEngine.equals(engineName, ignoreCase = true) ||
return (onlyWithEngine != null && !onlyWithEngine.equals(engineName, ignoreCase = true)) ||
skipEngines.any { shouldSkip(engineName, it) }
}

Expand All @@ -68,9 +68,8 @@ actual abstract class ClientLoader actual constructor(val timeoutSeconds: Int) {
}

val platformShouldBeSkipped = "*" == platform || OS_NAME == platform
val engineShouldBeSkipped = "*" == skipEngineName || engineName.lowercase(locale) == skipEngineName.lowercase(
locale
)
val engineShouldBeSkipped = "*" == skipEngineName ||
engineName.lowercase(locale) == skipEngineName.lowercase(locale)

return engineShouldBeSkipped && platformShouldBeSkipped
}
Expand Down
13 changes: 6 additions & 7 deletions ktor-http/common/src/io/ktor/http/CacheControl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,13 @@ public abstract class CacheControl(public val visibility: Visibility?) {
}

override fun equals(other: Any?): Boolean {
return other === this || (
return other === this ||
other is MaxAge &&
other.maxAgeSeconds == maxAgeSeconds &&
other.proxyMaxAgeSeconds == proxyMaxAgeSeconds &&
other.mustRevalidate == mustRevalidate &&
other.proxyRevalidate == proxyRevalidate &&
other.visibility == visibility
)
other.maxAgeSeconds == maxAgeSeconds &&
other.proxyMaxAgeSeconds == proxyMaxAgeSeconds &&
other.mustRevalidate == mustRevalidate &&
other.proxyRevalidate == proxyRevalidate &&
other.visibility == visibility
}

override fun hashCode(): Int {
Expand Down
3 changes: 2 additions & 1 deletion ktor-http/common/src/io/ktor/http/Codecs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ public fun String.encodeURLPath(
continue
}

if (!encodeEncoded && current == '%' &&
if (!encodeEncoded &&
current == '%' &&
index + 2 < this@encodeURLPath.length &&
this@encodeURLPath[index + 1] in HEX_ALPHABET &&
this@encodeURLPath[index + 2] in HEX_ALPHABET
Expand Down
13 changes: 7 additions & 6 deletions ktor-http/common/src/io/ktor/http/RangesSpecifier.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ public data class RangesSpecifier(val unit: String = RangeUnits.Bytes.unitToken,
* Verify ranges
*/
public fun isValid(rangeUnitPredicate: (String) -> Boolean = { it == RangeUnits.Bytes.unitToken }): Boolean =
rangeUnitPredicate(unit) && ranges.none {
when (it) {
is ContentRange.Bounded -> it.from < 0 || it.to < it.from
is ContentRange.TailFrom -> it.from < 0
is ContentRange.Suffix -> it.lastCount < 0
rangeUnitPredicate(unit) &&
ranges.none {
when (it) {
is ContentRange.Bounded -> it.from < 0 || it.to < it.from
is ContentRange.TailFrom -> it.from < 0
is ContentRange.Suffix -> it.lastCount < 0
}
}
}

/**
* Resolve and merge all overlapping and neighbours ranges
Expand Down
10 changes: 5 additions & 5 deletions ktor-http/jvm/src/io/ktor/http/content/BlockingBridge.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

package io.ktor.http.content

import kotlinx.coroutines.*
import java.lang.reflect.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.lang.reflect.Method

private val isParkingAllowedFunction: Method? by lazy {
try {
Expand All @@ -32,9 +33,8 @@ internal suspend fun withBlocking(block: suspend () -> Unit) {
}

private fun safeToRunInPlace(): Boolean {
val isParkingAllowed = isParkingAllowedFunction
return isParkingAllowed != null && try {
isParkingAllowed.invoke(null) == true
return try {
isParkingAllowedFunction?.invoke(null) == true
} catch (cause: Throwable) {
false
}
Expand Down
13 changes: 7 additions & 6 deletions ktor-io/js/src/io/ktor/utils/io/charsets/Charset.js.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package io.ktor.utils.io.charsets

import kotlinx.io.*
import org.khronos.webgl.*
import org.khronos.webgl.Int8Array

/**
* Find a charset by name.
Expand Down Expand Up @@ -41,9 +41,9 @@ public actual abstract class Charset(internal val _name: String) {
public companion object {
public fun forName(name: String): Charset {
if (name == "UTF-8" || name == "utf-8" || name == "UTF8" || name == "utf8") return Charsets.UTF_8
if (name == "ISO-8859-1" || name == "iso-8859-1" ||
if ((name == "ISO-8859-1" || name == "iso-8859-1") ||
name.replace('_', '-').let { it == "iso-8859-1" || it.lowercase() == "iso-8859-1" } ||
name == "latin1" || name == "Latin1"
(name == "latin1" || name == "Latin1")
) {
return Charsets.ISO_8859_1
}
Expand All @@ -52,9 +52,10 @@ public actual abstract class Charset(internal val _name: String) {

public fun isSupported(charset: String): Boolean = when {
charset == "UTF-8" || charset == "utf-8" || charset == "UTF8" || charset == "utf8" -> true
charset == "ISO-8859-1" || charset == "iso-8859-1" || charset.replace('_', '-').let {
it == "iso-8859-1" || it.lowercase() == "iso-8859-1"
} || charset == "latin1" -> true
(charset == "ISO-8859-1" || charset == "iso-8859-1") ||
charset.replace('_', '-')
.let { it == "iso-8859-1" || it.lowercase() == "iso-8859-1" } ||
charset == "latin1" -> true

else -> false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@

package io.ktor.network.sockets

import java.io.*
import java.lang.reflect.*
import java.nio.channels.*
import java.io.IOException
import java.lang.reflect.Field
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.nio.channels.DatagramChannel
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel

private const val SO_REUSEPORT = "SO_REUSEPORT"

Expand All @@ -32,9 +36,8 @@ internal object SocketOptionsPlatformCapabilities {
val socketChannelClass = Class.forName("java.nio.channels.SocketChannel")

socketChannelClass.methods.firstOrNull { method ->
method.modifiers.let { modifiers ->
Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)
} && method.name == "setOption" &&
method.modifiers.let { modifiers -> Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) } &&
method.name == "setOption" &&
method.parameterTypes.size == 2 &&
method.returnType == socketChannelClass &&
method.parameterTypes[0] == socketOptionType &&
Expand All @@ -49,9 +52,7 @@ internal object SocketOptionsPlatformCapabilities {
val socketChannelClass = Class.forName("java.nio.channels.ServerSocketChannel")

socketChannelClass.methods.firstOrNull { method ->
method.modifiers.let { modifiers ->
Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)
} &&
method.modifiers.let { modifiers -> Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) } &&
method.name == "setOption" &&
method.parameterTypes.size == 2 &&
method.returnType == socketChannelClass &&
Expand Down
Loading

0 comments on commit cf05f00

Please sign in to comment.