diff --git a/.editorconfig b/.editorconfig index 72362cbd77a..2ae1cac53f5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,13 +13,22 @@ indent_size = 2 ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL ij_kotlin_packages_to_use_import_on_demand = java.util.*, io.ktor.** +ktlint_code_style = intellij_idea +ktlint_standard_annotation = disabled +ktlint_standard_class-naming = disabled +ktlint_standard_class-signature = disabled +ktlint_standard_comment-wrapping = disabled +ktlint_standard_filename = disabled +ktlint_standard_function-expression-body = disabled +ktlint_standard_function-signature = disabled +ktlint_standard_if-else-bracing = enabled +ktlint_standard_if-else-wrapping = enabled +ktlint_standard_no-consecutive-comments = enabled ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_property-naming = disabled ktlint_standard_trailing-comma-on-call-site = disabled ktlint_standard_trailing-comma-on-declaration-site = disabled -ktlint_standard_filename = disabled -ktlint_standard_class-naming = disabled -ktlint_standard_annotation = disabled -ktlint_standard_comment-wrapping = disabled +ktlint_standard_try-catch-finally-spacing = enabled [*.kts] # Always use wildcard imports in scripts diff --git a/buildSrc/src/main/kotlin/KotlinExtensions.kt b/buildSrc/src/main/kotlin/KotlinExtensions.kt index 610463b7f20..72c6def8fb1 100644 --- a/buildSrc/src/main/kotlin/KotlinExtensions.kt +++ b/buildSrc/src/main/kotlin/KotlinExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import org.gradle.api.* import org.gradle.kotlin.dsl.* @@ -47,16 +47,6 @@ fun NamedDomainObjectContainer.jvmAndPosixTest(block: KotlinSou block(sourceSet) } -fun NamedDomainObjectContainer.jvmAndNixMain(block: KotlinSourceSet.() -> Unit) { - val sourceSet = findByName("jvmAndNixMain") ?: getByName("jvmMain") - block(sourceSet) -} - -fun NamedDomainObjectContainer.jvmAndNixTest(block: KotlinSourceSet.() -> Unit) { - val sourceSet = findByName("jvmAndNixTest") ?: getByName("jvmTest") - block(sourceSet) -} - fun NamedDomainObjectContainer.nixTest(block: KotlinSourceSet.() -> Unit) { val sourceSet = findByName("nixTest") ?: return block(sourceSet) diff --git a/buildSrc/src/main/kotlin/TargetsConfig.kt b/buildSrc/src/main/kotlin/TargetsConfig.kt index d82cb47dfe3..2293c5b70f8 100644 --- a/buildSrc/src/main/kotlin/TargetsConfig.kt +++ b/buildSrc/src/main/kotlin/TargetsConfig.kt @@ -15,10 +15,9 @@ import java.io.* private val Project.files: Array get() = project.projectDir.listFiles() ?: emptyArray() val Project.hasCommon: Boolean get() = files.any { it.name == "common" } val Project.hasJvmAndPosix: Boolean get() = hasCommon || files.any { it.name == "jvmAndPosix" } -val Project.hasJvmAndNix: Boolean get() = hasCommon || files.any { it.name == "jvmAndNix" } val Project.hasPosix: Boolean get() = hasCommon || hasJvmAndPosix || files.any { it.name == "posix" } val Project.hasDesktop: Boolean get() = hasPosix || files.any { it.name == "desktop" } -val Project.hasNix: Boolean get() = hasPosix || hasJvmAndNix || files.any { it.name == "nix" } +val Project.hasNix: Boolean get() = hasPosix || files.any { it.name == "nix" } val Project.hasLinux: Boolean get() = hasNix || files.any { it.name == "linux" } val Project.hasDarwin: Boolean get() = hasNix || files.any { it.name == "darwin" } val Project.hasAndroidNative: Boolean get() = hasPosix || files.any { it.name == "androidNative" } @@ -26,7 +25,7 @@ val Project.hasWindows: Boolean get() = hasPosix || files.any { it.name == "wind val Project.hasJsAndWasmShared: Boolean get() = files.any { it.name == "jsAndWasmShared" } val Project.hasJs: Boolean get() = hasCommon || files.any { it.name == "js" } || hasJsAndWasmShared val Project.hasWasmJs: Boolean get() = hasCommon || files.any { it.name == "wasmJs" } || hasJsAndWasmShared -val Project.hasJvm: Boolean get() = hasCommon || hasJvmAndNix || hasJvmAndPosix || files.any { it.name == "jvm" } +val Project.hasJvm: Boolean get() = hasCommon || hasJvmAndPosix || files.any { it.name == "jvm" } val Project.hasExplicitNative: Boolean get() = hasNix || hasPosix || hasLinux || hasAndroidNative || hasDarwin || hasDesktop || hasWindows @@ -110,11 +109,6 @@ private val hierarchyTemplate = KotlinHierarchyTemplate { group("posix") } - group("jvmAndNix") { - withJvm() - group("nix") - } - group("desktop") { group("linux") group("windows") diff --git a/buildSrc/src/main/kotlin/test/server/tests/Events.kt b/buildSrc/src/main/kotlin/test/server/tests/Events.kt index 0447e187902..e7b89937261 100644 --- a/buildSrc/src/main/kotlin/test/server/tests/Events.kt +++ b/buildSrc/src/main/kotlin/test/server/tests/Events.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package test.server.tests import io.ktor.http.* diff --git a/buildSrc/src/main/kotlin/test/server/tests/Serialization.kt b/buildSrc/src/main/kotlin/test/server/tests/Serialization.kt index 1f927d842bd..370d1284d1d 100644 --- a/buildSrc/src/main/kotlin/test/server/tests/Serialization.kt +++ b/buildSrc/src/main/kotlin/test/server/tests/Serialization.kt @@ -9,7 +9,6 @@ import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* -@OptIn(ExperimentalStdlibApi::class) internal fun Application.serializationTestServer() { routing { route("/json") { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index faaec6d72bf..d887ba749ca 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -10,7 +10,7 @@ serialization = "1.7.3" binaryCompatibilityValidator = "0.16.3" dokka = "1.9.20" kover = "0.8.3" -ktlint = "3.15.0" +ktlint = "4.5.0" kotlinx-browser = "0.2" # Used for test server in buildSrc diff --git a/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/ApacheEngineConfig.kt b/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/ApacheEngineConfig.kt index 5d8ad4cc14e..4ebcd28216b 100644 --- a/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/ApacheEngineConfig.kt +++ b/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/ApacheEngineConfig.kt @@ -5,9 +5,9 @@ package io.ktor.client.engine.apache import io.ktor.client.engine.* -import org.apache.http.client.config.* -import org.apache.http.impl.nio.client.* -import javax.net.ssl.* +import org.apache.http.client.config.RequestConfig +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder +import javax.net.ssl.SSLContext /** * A configuration for the [Apache] client engine. @@ -64,7 +64,7 @@ public class ApacheEngineConfig : HttpClientEngineConfig() { */ public fun customizeRequest(block: RequestConfig.Builder.() -> Unit) { val current = customRequest - customRequest = { current(); block(); this } + customRequest = { current().apply(block) } } /** @@ -72,6 +72,6 @@ public class ApacheEngineConfig : HttpClientEngineConfig() { */ public fun customizeClient(block: HttpAsyncClientBuilder.() -> Unit) { val current = customClient - customClient = { current(); block(); this } + customClient = { current().apply(block) } } } diff --git a/ktor-client/ktor-client-apache/jvm/test/io/ktor/client/engine/apache/RequestProducerTest.kt b/ktor-client/ktor-client-apache/jvm/test/io/ktor/client/engine/apache/RequestProducerTest.kt index 27d74083879..48d0fa62f10 100644 --- a/ktor-client/ktor-client-apache/jvm/test/io/ktor/client/engine/apache/RequestProducerTest.kt +++ b/ktor-client/ktor-client-apache/jvm/test/io/ktor/client/engine/apache/RequestProducerTest.kt @@ -86,7 +86,7 @@ class RequestProducerTest { producer.close() } - @OptIn(DelicateCoroutinesApi::class, InternalAPI::class) + @OptIn(DelicateCoroutinesApi::class) @Test fun testProducingReadChannelContent() = runTest { val content = ByteChannel(true) @@ -171,8 +171,9 @@ class RequestProducerTest { repeat(1000) { val body = ChannelWriterContent( body = { - for (i in 0 until sampleSize) + for (i in 0 until sampleSize) { writeByte(i.toByte()) + } }, contentType = null ) @@ -231,7 +232,6 @@ private class TestEncoder : ContentEncoder { src.limit() } - @OptIn(InternalAPI::class) override fun complete() { channel.close() } diff --git a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5EngineConfig.kt b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5EngineConfig.kt index a0b9e223e9d..ab68958c14e 100644 --- a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5EngineConfig.kt +++ b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5EngineConfig.kt @@ -5,9 +5,9 @@ package io.ktor.client.engine.apache5 import io.ktor.client.engine.* -import org.apache.hc.client5.http.config.* -import org.apache.hc.client5.http.impl.async.* -import javax.net.ssl.* +import org.apache.hc.client5.http.config.RequestConfig +import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder +import javax.net.ssl.SSLContext /** * A configuration for the [Apache5] client engine. @@ -56,7 +56,7 @@ public class Apache5EngineConfig : HttpClientEngineConfig() { */ public fun customizeRequest(block: RequestConfig.Builder.() -> Unit) { val current = customRequest - customRequest = { current(); block(); this } + customRequest = { current().apply(block) } } /** @@ -64,6 +64,6 @@ public class Apache5EngineConfig : HttpClientEngineConfig() { */ public fun customizeClient(block: HttpAsyncClientBuilder.() -> Unit) { val current = customClient - customClient = { current(); block(); this } + customClient = { current().apply(block) } } } diff --git a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt index 53df59059db..deceaf29bd9 100644 --- a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt +++ b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.apache5 @@ -22,6 +22,7 @@ import java.nio.* import java.util.concurrent.* import kotlin.coroutines.* +@Suppress("FunctionName") @OptIn(InternalAPI::class) internal fun ApacheRequestProducer( requestData: HttpRequestData, diff --git a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt index b4bbf500cc3..4c0695a3577 100644 --- a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt +++ b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt @@ -151,7 +151,6 @@ internal class ApacheResponseConsumer( responseChannel.cancel(mappedCause) } - @OptIn(InternalAPI::class) internal fun close() { channel.close() consumerJob.complete() diff --git a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/ConnectionPipeline.kt b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/ConnectionPipeline.kt index 678fc8ec3b7..0d75c9bb267 100644 --- a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/ConnectionPipeline.kt +++ b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/ConnectionPipeline.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.cio @@ -18,7 +18,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.sync.* -import kotlinx.io.EOFException +import kotlinx.io.* import java.nio.channels.* import kotlin.coroutines.* import io.ktor.utils.io.ByteChannel as KtorByteChannel @@ -61,9 +61,7 @@ internal actual class ConnectionPipeline actual constructor( } catch (_: CancellationException) { } finally { responseChannel.close() - /** - * Workaround bug with socket.close - */ + // Workaround bug with socket.close // outputChannel.close() } } @@ -109,7 +107,9 @@ internal actual class ConnectionPipeline actual constructor( val proxyChannel = KtorByteChannel() skipTask = skipCancels(responseChannel, proxyChannel) proxyChannel - } else ByteReadChannel.Empty + } else { + ByteReadChannel.Empty + } callJob.invokeOnCompletion { body.cancel() diff --git a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt index 76aec2967b2..c3fd6d563ff 100644 --- a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt +++ b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.websocket.cio @@ -37,7 +37,9 @@ public suspend fun HttpClient.webSocketRawSession( session.outgoing.invokeOnClose { if (it != null) { sessionCompleted.completeExceptionally(it) - } else sessionCompleted.complete(Unit) + } else { + sessionCompleted.complete(Unit) + } } sessionCompleted.await() } diff --git a/ktor-client/ktor-client-cio/jvm/test/io/ktor/client/engine/cio/ConnectErrorsTest.kt b/ktor-client/ktor-client-cio/jvm/test/io/ktor/client/engine/cio/ConnectErrorsTest.kt index c3d10016b39..80702b6a17e 100644 --- a/ktor-client/ktor-client-cio/jvm/test/io/ktor/client/engine/cio/ConnectErrorsTest.kt +++ b/ktor-client/ktor-client-cio/jvm/test/io/ktor/client/engine/cio/ConnectErrorsTest.kt @@ -102,7 +102,8 @@ class ConnectErrorsTest { } client.getInputStream().readBytes() } - } catch (_: Exception) { } + } catch (_: Exception) { + } } assertEquals("OK", client.get("http://localhost:${serverSocket.localPort}/").body()) thread.join() diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt index ee1023e3bd6..4120918adfe 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt +++ b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.cio diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt index 59fac79bfd4..3439cf2a474 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt +++ b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt @@ -16,8 +16,8 @@ import io.ktor.util.collections.* import io.ktor.util.network.* import io.ktor.utils.io.* import kotlinx.coroutines.* -import kotlinx.coroutines.channels.* -import kotlin.coroutines.* +import kotlinx.coroutines.channels.ClosedSendChannelException +import kotlin.coroutines.CoroutineContext @OptIn(InternalAPI::class, DelicateCoroutinesApi::class) internal class CIOEngine( @@ -61,7 +61,6 @@ internal class CIOEngine( val requestJob = requestField[Job]!! val selector = selectorManager - @OptIn(ExperimentalCoroutinesApi::class) GlobalScope.launch(parentContext, start = CoroutineStart.ATOMIC) { try { requestJob.join() diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt index b7bb982c485..f9eaa6e0413 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt +++ b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.cio diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt index 876f8ac6607..34153968c44 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt +++ b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt @@ -92,7 +92,6 @@ internal class Endpoint( deliveryPoint.send(task) } - @OptIn(InternalAPI::class) private suspend fun makeDedicatedRequest( request: HttpRequestData, callContext: CoroutineContext diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt index 97af506c9f7..91536831b40 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt +++ b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt @@ -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, @@ -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, diff --git a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt b/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt index 1c9c9baf521..cccabfcd47c 100644 --- a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt +++ b/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.cio diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/call/HttpClientCall.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/call/HttpClientCall.kt index 1b517c17073..22184f5f5c5 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/call/HttpClientCall.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/call/HttpClientCall.kt @@ -73,7 +73,6 @@ public open class HttpClientCall( * @throws NoTransformationFoundException If no transformation is found for the type [info]. * @throws DoubleReceiveException If already called [body]. */ - @OptIn(InternalAPI::class) public suspend fun bodyNullable(info: TypeInfo): Any? { try { if (response.instanceOf(info.type)) return response @@ -107,7 +106,6 @@ public open class HttpClientCall( * @throws DoubleReceiveException If already called [body]. * @throws NullPointerException If content is `null`. */ - @OptIn(InternalAPI::class) public suspend fun body(info: TypeInfo): Any = bodyNullable(info)!! override fun toString(): String = "HttpClientCall[${request.url}, ${response.status}]" diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt index 5416e3ac91e..a9b84bb0e64 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt @@ -23,7 +23,6 @@ private val LOGGER = KtorSimpleLogger("io.ktor.client.plugins.defaultTransformer * Usually installed by default so there is no need to use it * unless you have disabled it via [HttpClientConfig.useDefaultTransformers]. */ -@OptIn(InternalAPI::class) public fun HttpClient.defaultTransformers() { requestPipeline.intercept(HttpRequestPipeline.Render) { body -> if (context.headers[HttpHeaders.Accept] == null) { diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpCallValidator.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpCallValidator.kt index 168e9ec5edd..7d8a202a4e1 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpCallValidator.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpCallValidator.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins @@ -155,7 +155,7 @@ internal object ReceiveError : ClientHook Th } } -private fun HttpRequest(builder: HttpRequestBuilder) = object : HttpRequest { +private fun HttpRequest(builder: HttpRequestBuilder): HttpRequest = object : HttpRequest { override val call: HttpClientCall get() = error("Call is not initialized") override val method: HttpMethod = builder.method override val url: Url = builder.url.build() @@ -169,6 +169,7 @@ private fun HttpRequest(builder: HttpRequestBuilder) = object : HttpRequest { /** * Install [HttpCallValidator] with [block] configuration. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.HttpResponseValidator(block: HttpCallValidatorConfig.() -> Unit) { install(HttpCallValidator, block) } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt index 6644d8b3f08..72a7123deb8 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins @@ -240,11 +240,12 @@ public val HttpRequestRetry: ClientPlugin = 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, @@ -252,11 +253,12 @@ public val HttpRequestRetry: ClientPlugin = createClient 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) @@ -264,7 +266,9 @@ public val HttpRequestRetry: ClientPlugin = createClient val subRequestJob = subRequest.executionContext as CompletableJob if (cause == null) { subRequestJob.complete() - } else subRequestJob.completeExceptionally(cause) + } else { + subRequestJob.completeExceptionally(cause) + } } return subRequest } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/UserAgent.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/UserAgent.kt index 6b096f9e6eb..98e30d59ff4 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/UserAgent.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/UserAgent.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins @@ -35,6 +35,7 @@ public val UserAgent: ClientPlugin = createClientPlugin("UserAg /** * Installs the [UserAgent] plugin with a browser-like user agent. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.BrowserUserAgent() { install(UserAgent) { agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + @@ -45,6 +46,7 @@ public fun HttpClientConfig<*>.BrowserUserAgent() { /** * Installs the [UserAgent] plugin with a CURL user agent. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.CurlUserAgent() { install(UserAgent) { agent = "curl/7.61.0" diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt index 4e0b58717db..46bf10e8307 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.client.plugins.api import io.ktor.client.* diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt index fc86fd1e9ff..3500070fc22 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt @@ -144,7 +144,6 @@ public class HttpCache private constructor( } } - @OptIn(InternalAPI::class) override fun install(plugin: HttpCache, scope: HttpClient) { val CachePhase = PipelinePhase("Cache") scope.sendPipeline.insertPhaseAfter(HttpSendPipeline.State, CachePhase) diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheEntry.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheEntry.kt index fc1256a1203..0554b4557be 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheEntry.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheEntry.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins.cache @@ -137,5 +137,7 @@ internal fun shouldValidate( } internal enum class ValidateStatus { - ShouldValidate, ShouldNotValidate, ShouldWarn + ShouldValidate, + ShouldNotValidate, + ShouldWarn, } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheLegacy.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheLegacy.kt index ef4d83720cc..ec592f4c3b6 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheLegacy.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCacheLegacy.kt @@ -52,7 +52,6 @@ internal suspend fun PipelineContext.interceptSendLegac } } -@OptIn(InternalAPI::class) internal suspend fun PipelineContext.interceptReceiveLegacy( response: HttpResponse, plugin: HttpCache, diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt index e8c4e8f82bc..df22ae7ee70 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins.sse @@ -21,6 +21,7 @@ internal val showRetryEventsAttr = AttributeKey("SSEShowRetryEvents") /** * Installs the [SSE] plugin using the [config] as configuration. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.SSE(config: SSEConfig.() -> Unit) { install(SSE) { config() diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt index 30cd810efa1..e413f4cd8aa 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt @@ -174,8 +174,9 @@ public class WebSockets internal constructor( return@intercept } if (status != HttpStatusCode.SwitchingProtocols) { + @Suppress("ktlint:standard:max-line-length") throw WebSocketException( - "Handshake exception, expected status code ${HttpStatusCode.SwitchingProtocols.value} but was ${status.value}" // ktlint-disable max-line-length + "Handshake exception, expected status code ${HttpStatusCode.SwitchingProtocols.value} but was ${status.value}" ) } if (session !is WebSocketSession) { diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt index 6da82ec46e6..12337c04fe6 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins.websocket @@ -14,6 +14,7 @@ import kotlinx.coroutines.* /** * Installs the [WebSockets] plugin using the [config] as configuration. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit) { install(WebSockets) { config() @@ -44,7 +45,9 @@ public suspend fun HttpClient.webSocketSession( session.outgoing.invokeOnClose { if (it != null) { sessionCompleted.completeExceptionally(it) - } else sessionCompleted.complete(Unit) + } else { + sessionCompleted.complete(Unit) + } } sessionCompleted.await() } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt index a55c6b4395d..a735421314e 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.request @@ -294,7 +294,7 @@ public operator fun HttpRequestBuilder.Companion.invoke( /** * Sets the [HttpRequestBuilder.url] from [urlString]. */ -public fun HttpRequestBuilder.url(urlString: String) { // ktlint-disable filename +public fun HttpRequestBuilder.url(urlString: String) { url.takeFrom(urlString) } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/builders.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/builders.kt index f33832dad8e..5a775111dc6 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/builders.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/builders.kt @@ -413,7 +413,10 @@ public fun request(block: HttpRequestBuilder.() -> Unit): HttpRequestBuilder = public suspend inline fun HttpClient.get( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = get { url(urlString); block() } +): HttpResponse = get { + url(urlString) + block() +} /** * Executes an [HttpClient]'s POST request with the specified [url] and @@ -424,7 +427,10 @@ public suspend inline fun HttpClient.get( public suspend inline fun HttpClient.post( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = post { url(urlString); block() } +): HttpResponse = post { + url(urlString) + block() +} /** * Executes an [HttpClient]'s PUT request with the specified [url] and @@ -435,7 +441,10 @@ public suspend inline fun HttpClient.post( public suspend inline fun HttpClient.put( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = put { url(urlString); block() } +): HttpResponse = put { + url(urlString) + block() +} /** * Executes an [HttpClient]'s DELETE request with the specified [url] and @@ -446,7 +455,10 @@ public suspend inline fun HttpClient.put( public suspend inline fun HttpClient.delete( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = delete { url(urlString); block() } +): HttpResponse = delete { + url(urlString) + block() +} /** * Executes an [HttpClient]'s OPTIONS request with the specified [url] and @@ -457,7 +469,10 @@ public suspend inline fun HttpClient.delete( public suspend inline fun HttpClient.options( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = options { url(urlString); block() } +): HttpResponse = options { + url(urlString) + block() +} /** * Executes an [HttpClient]'s PATCH request with the specified [url] and @@ -468,7 +483,10 @@ public suspend inline fun HttpClient.options( public suspend inline fun HttpClient.patch( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = patch { url(urlString); block() } +): HttpResponse = patch { + url(urlString) + block() +} /** * Executes an [HttpClient]'s HEAD request with the specified [url] and @@ -479,7 +497,10 @@ public suspend inline fun HttpClient.patch( public suspend inline fun HttpClient.head( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpResponse = head { url(urlString); block() } +): HttpResponse = head { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s GET request with the specified [url] and @@ -488,7 +509,10 @@ public suspend inline fun HttpClient.head( public suspend inline fun HttpClient.prepareGet( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = prepareGet { url(urlString); block() } +): HttpStatement = prepareGet { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s POST request with the specified [url] and @@ -497,7 +521,10 @@ public suspend inline fun HttpClient.prepareGet( public suspend inline fun HttpClient.preparePost( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = preparePost { url(urlString); block() } +): HttpStatement = preparePost { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s PUT request with the specified [url] and @@ -506,7 +533,10 @@ public suspend inline fun HttpClient.preparePost( public suspend inline fun HttpClient.preparePut( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = preparePut { url(urlString); block() } +): HttpStatement = preparePut { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s DELETE request with the specified [url] and @@ -515,7 +545,10 @@ public suspend inline fun HttpClient.preparePut( public suspend inline fun HttpClient.prepareDelete( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = prepareDelete { url(urlString); block() } +): HttpStatement = prepareDelete { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s OPTIONS request with the specified [url] and @@ -524,7 +557,10 @@ public suspend inline fun HttpClient.prepareDelete( public suspend inline fun HttpClient.prepareOptions( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = prepareOptions { url(urlString); block() } +): HttpStatement = prepareOptions { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s PATCH request with the specified [url] and @@ -533,7 +569,10 @@ public suspend inline fun HttpClient.prepareOptions( public suspend inline fun HttpClient.preparePatch( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = preparePatch { url(urlString); block() } +): HttpStatement = preparePatch { + url(urlString) + block() +} /** * Prepares an [HttpClient]'s HEAD request with the specified [url] and @@ -542,4 +581,7 @@ public suspend inline fun HttpClient.preparePatch( public suspend inline fun HttpClient.prepareHead( urlString: String, block: HttpRequestBuilder.() -> Unit = {} -): HttpStatement = prepareHead { url(urlString); block() } +): HttpStatement = prepareHead { + url(urlString) + block() +} diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/buildersWithUrl.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/buildersWithUrl.kt index 2411af424bf..192619f308d 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/buildersWithUrl.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/buildersWithUrl.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.request @@ -193,6 +193,6 @@ public suspend inline fun HttpClient.prepareDelete( /** * Sets the [HttpRequestBuilder.url] from [url]. */ -public fun HttpRequestBuilder.url(url: Url): Unit { // ktlint-disable no-unit-return +public fun HttpRequestBuilder.url(url: Url) { this.url.takeFrom(url) } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/forms/FormDataContent.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/forms/FormDataContent.kt index b2a5abacd0f..e9da3990dad 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/forms/FormDataContent.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/forms/FormDataContent.kt @@ -112,7 +112,6 @@ public class MultiPartFormDataContent( contentLength = rawLength } - @OptIn(ExperimentalStdlibApi::class) override suspend fun writeTo(channel: ByteWriteChannel) { try { for (part in rawParts) { diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/utils.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/utils.kt index 501eb50911a..83a711a003a 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/utils.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/utils.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.request @@ -45,7 +45,7 @@ public fun HttpMessageBuilder.cookie( secure: Boolean = false, httpOnly: Boolean = false, extensions: Map = emptyMap() -): Unit { // ktlint-disable no-unit-return +) { val renderedCookie = Cookie( name = name, value = value, diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpStatement.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpStatement.kt index a6389304b3d..10d878032c4 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpStatement.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpStatement.kt @@ -155,7 +155,7 @@ public class HttpStatement( * Completes [HttpResponse] and releases resources. */ @PublishedApi - @OptIn(InternalAPI::class, InternalCoroutinesApi::class) + @OptIn(InternalAPI::class) internal suspend fun HttpResponse.cleanup() { val job = coroutineContext[Job]!! as CompletableJob diff --git a/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt b/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt index f03be3daa73..e1210e2a295 100644 --- a/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt +++ b/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.client.plugins.cache.tests import io.ktor.client.call.* diff --git a/ktor-client/ktor-client-core/common/test/MultiPartFormDataContentTest.kt b/ktor-client/ktor-client-core/common/test/MultiPartFormDataContentTest.kt index cfded8308cf..c46a0f0b75d 100644 --- a/ktor-client/ktor-client-core/common/test/MultiPartFormDataContentTest.kt +++ b/ktor-client/ktor-client-core/common/test/MultiPartFormDataContentTest.kt @@ -12,7 +12,6 @@ import kotlin.test.* class MultiPartFormDataContentTest { - @OptIn(InternalAPI::class) @Test fun testMultiPartFormDataContentHasCorrectPrefix() = testSuspend { val formData = MultiPartFormDataContent( @@ -234,7 +233,6 @@ class MultiPartFormDataContentTest { return bytes.decodeToString(0, 0 + bytes.size) } - @OptIn(InternalAPI::class) private suspend fun MultiPartFormDataContent.readBytes(): ByteArray = coroutineScope { val channel = ByteChannel() val writeJob = launch { diff --git a/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibDom.kt b/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibDom.kt index da5f34d3bfa..6de06849fc5 100644 --- a/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibDom.kt +++ b/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibDom.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.fetch @@ -11,17 +11,17 @@ import kotlin.js.Promise public external fun fetch(input: String, init: RequestInit? = definedExternally): Promise public external interface Request : Body { - /* "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" */ + // "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" public var cache: dynamic get() = definedExternally set(value) = definedExternally - /* "omit" | "same-origin" | "include" */ + // "omit" | "same-origin" | "include" public var credentials: dynamic get() = definedExternally set(value) = definedExternally - /* "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt" */ + // "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt" public var destination: dynamic get() = definedExternally set(value) = definedExternally @@ -32,18 +32,18 @@ public external interface Request : Body { public var keepalive: Boolean public var method: String - /* "navigate" | "same-origin" | "no-cors" | "cors" */ + // "navigate" | "same-origin" | "no-cors" | "cors" public var mode: dynamic get() = definedExternally set(value) = definedExternally - /* "follow" | "error" | "manual" */ + // "follow" | "error" | "manual" public var redirect: dynamic get() = definedExternally set(value) = definedExternally public var referrer: String - /* "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" */ + // "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" public var referrerPolicy: dynamic get() = definedExternally set(value) = definedExternally @@ -63,7 +63,7 @@ public external interface Response : Body { public var statusText: String public var trailer: Promise - /* "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect" */ + // "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect" public var type: dynamic get() = definedExternally set(value) = definedExternally @@ -89,14 +89,14 @@ public external interface FormData { public fun append(name: String, value: Blob, fileName: String? = definedExternally) public fun delete(name: String) - /* File | String */ - public fun get(name: String): dynamic - public fun getAll(name: String): Array + public fun get(name: String): dynamic // File | String + public fun getAll(name: String): Array // File | String public fun has(name: String): Boolean public fun set(name: String, value: String, fileName: String? = definedExternally) public fun set(name: String, value: Blob, fileName: String? = definedExternally) public fun forEach( - callbackfn: (value: dynamic /* File | String */, key: String, parent: FormData) -> Unit, + // value: File | String + callbackfn: (value: dynamic, key: String, parent: FormData) -> Unit, thisArg: Any? = definedExternally ) } @@ -121,7 +121,7 @@ public external interface ReadableStream { public fun pipeTo(dest: WritableStream, options: PipeOptions? = definedExternally): Promise - /* JsTuple, ReadableStream> */ + // JsTuple, ReadableStream> public fun tee(): dynamic } @@ -190,22 +190,22 @@ public external interface Headers { } public external interface RequestInit { - /* Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream | String */ + // Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream | String public var body: dynamic get() = definedExternally set(value) = definedExternally - /* "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" */ + // "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" public var cache: dynamic get() = definedExternally set(value) = definedExternally - /* "omit" | "same-origin" | "include" */ + // "omit" | "same-origin" | "include" public var credentials: dynamic get() = definedExternally set(value) = definedExternally - /* Headers | Array> | Record */ + // Headers | Array> | Record public var headers: dynamic get() = definedExternally set(value) = definedExternally @@ -222,12 +222,12 @@ public external interface RequestInit { get() = definedExternally set(value) = definedExternally - /* "navigate" | "same-origin" | "no-cors" | "cors" */ + // "navigate" | "same-origin" | "no-cors" | "cors" public var mode: dynamic get() = definedExternally set(value) = definedExternally - /* "follow" | "error" | "manual" */ + // "follow" | "error" | "manual" public var redirect: dynamic get() = definedExternally set(value) = definedExternally @@ -235,7 +235,7 @@ public external interface RequestInit { get() = definedExternally set(value) = definedExternally - /* "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" */ + // "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" public var referrerPolicy: dynamic get() = definedExternally set(value) = definedExternally diff --git a/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibEs5.kt b/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibEs5.kt index bb2d31bd329..625917e7d63 100644 --- a/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibEs5.kt +++ b/ktor-client/ktor-client-core/js/src/io/ktor/client/fetch/LibEs5.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.fetch @@ -30,7 +30,7 @@ public external interface Uint8Array { public var byteLength: Number public var byteOffset: Number - public fun copyWithin(target: Number, start: Number, end: Number? = definedExternally): Uint8Array /* this */ + public fun copyWithin(target: Number, start: Number, end: Number? = definedExternally): Uint8Array // this public fun every( callbackfn: (value: Number, index: Number, array: Uint8Array) -> Any, thisArg: Any? = definedExternally @@ -40,7 +40,7 @@ public external interface Uint8Array { value: Number, start: Number? = definedExternally, end: Number? = definedExternally - ): Uint8Array /* this */ + ): Uint8Array // this public fun filter( callbackfn: (value: Number, index: Number, array: Uint8Array) -> Any, @@ -101,7 +101,7 @@ public external interface Uint8Array { thisArg: Any? = definedExternally ): Boolean - public fun sort(compareFn: ((a: Number, b: Number) -> Number)? = definedExternally): Uint8Array /* this */ + public fun sort(compareFn: ((a: Number, b: Number) -> Number)? = definedExternally): Uint8Array // this public fun subarray(begin: Number? = definedExternally, end: Number? = definedExternally): Uint8Array public fun toLocaleString(): String override fun toString(): String diff --git a/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/engine/js/Js.kt b/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/engine/js/Js.kt index a579421500b..76d19cd4e10 100644 --- a/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/engine/js/Js.kt +++ b/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/engine/js/Js.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.js @@ -28,5 +28,6 @@ public expect open class JsClientEngineConfig : HttpClientEngineConfig /** * Creates a [Js] client engine. */ +@Suppress("FunctionName") @JsName("JsClient") public fun JsClient(): HttpClientEngineFactory = Js diff --git a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/DefaultTransformersJvm.kt b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/DefaultTransformersJvm.kt index 8617ec26680..111a3e24eaf 100644 --- a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/DefaultTransformersJvm.kt +++ b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/DefaultTransformersJvm.kt @@ -14,7 +14,6 @@ import io.ktor.utils.io.jvm.javaio.* import kotlinx.coroutines.* import java.io.* -@OptIn(InternalAPI::class) internal actual fun HttpClient.platformResponseDefaultTransformers() { responsePipeline.intercept(HttpResponsePipeline.Parse) { (info, body) -> if (body !is ByteReadChannel) return@intercept diff --git a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt index 40887edfb05..02a90a6de93 100644 --- a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt +++ b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.cache.storage @@ -22,6 +22,7 @@ import java.security.* * @param directory directory to store cache data. * @param dispatcher dispatcher to use for file operations. */ +@Suppress("FunctionName") public fun FileStorage( directory: File, dispatcher: CoroutineDispatcher = Dispatchers.IO @@ -86,7 +87,6 @@ private class FileCacheStorage( private fun key(url: Url) = hex(MessageDigest.getInstance("SHA-256").digest(url.toString().encodeToByteArray())) - @OptIn(InternalAPI::class) private suspend fun writeCache(urlHex: String, caches: List) = coroutineScope { val mutex = mutexes.computeIfAbsent(urlHex) { Mutex() } mutex.withLock { diff --git a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/utils/CoroutineDispatcherUtils.kt b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/utils/CoroutineDispatcherUtils.kt index eae81e44fc3..4fbc4397caf 100644 --- a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/utils/CoroutineDispatcherUtils.kt +++ b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/utils/CoroutineDispatcherUtils.kt @@ -10,7 +10,6 @@ import kotlinx.coroutines.* /** * Creates [CoroutineDispatcher] based on thread pool of [threadCount] threads. */ -@OptIn(ExperimentalCoroutinesApi::class) @InternalAPI public actual fun Dispatchers.clientDispatcher( threadCount: Int, diff --git a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibDom.kt b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibDom.kt index f54fdf00e3d..1f88e909ade 100644 --- a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibDom.kt +++ b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibDom.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.fetch @@ -12,17 +12,17 @@ import kotlin.js.Promise public external fun fetch(input: String, init: RequestInit? = definedExternally): Promise public external interface Request : Body { - /* "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" */ + // "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" public var cache: JsAny? get() = definedExternally set(value) = definedExternally - /* "omit" | "same-origin" | "include" */ + // "omit" | "same-origin" | "include" public var credentials: JsAny? get() = definedExternally set(value) = definedExternally - /* "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt" */ + // "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt" public var destination: JsAny? get() = definedExternally set(value) = definedExternally @@ -33,18 +33,18 @@ public external interface Request : Body { public var keepalive: Boolean public var method: String - /* "navigate" | "same-origin" | "no-cors" | "cors" */ + // "navigate" | "same-origin" | "no-cors" | "cors" public var mode: JsAny? get() = definedExternally set(value) = definedExternally - /* "follow" | "error" | "manual" */ + // "follow" | "error" | "manual" public var redirect: JsAny? get() = definedExternally set(value) = definedExternally public var referrer: String - /* "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" */ + // "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" public var referrerPolicy: JsAny? get() = definedExternally set(value) = definedExternally @@ -64,7 +64,7 @@ public external interface Response : Body { public var statusText: String public var trailer: Promise - /* "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect" */ + // "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect" public var type: JsAny? get() = definedExternally set(value) = definedExternally @@ -90,14 +90,14 @@ public external interface FormData : JsAny { public fun append(name: String, value: Blob, fileName: String? = definedExternally) public fun delete(name: String) - /* File | String */ - public fun get(name: String): JsAny? - public fun getAll(name: String): ArrayLike /* File | String */ + public fun get(name: String): JsAny? // File | String + public fun getAll(name: String): ArrayLike // File | String public fun has(name: String): Boolean public fun set(name: String, value: String, fileName: String? = definedExternally) public fun set(name: String, value: Blob, fileName: String? = definedExternally) public fun forEach( - callbackfn: (value: JsAny? /* File | String */, key: String, parent: FormData) -> Unit, + // value: File | String + callbackfn: (value: JsAny?, key: String, parent: FormData) -> Unit, thisArg: JsAny? = definedExternally ) } @@ -122,7 +122,7 @@ public external interface ReadableStream : JsAny { public fun pipeTo(dest: WritableStream, options: PipeOptions? = definedExternally): Promise - /* JsTuple, ReadableStream> */ + // JsTuple, ReadableStream> public fun tee(): JsAny? } @@ -191,22 +191,22 @@ public external interface Headers : JsAny { } public external interface RequestInit : JsAny { - /* Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream | String */ + // Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream | String public var body: JsAny? get() = definedExternally set(value) = definedExternally - /* "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" */ + // "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached" public var cache: JsAny? get() = definedExternally set(value) = definedExternally - /* "omit" | "same-origin" | "include" */ + // "omit" | "same-origin" | "include" public var credentials: JsAny? get() = definedExternally set(value) = definedExternally - /* Headers | Array> | Record */ + // Headers | Array> | Record public var headers: JsAny? get() = definedExternally set(value) = definedExternally @@ -223,12 +223,12 @@ public external interface RequestInit : JsAny { get() = definedExternally set(value) = definedExternally - /* "navigate" | "same-origin" | "no-cors" | "cors" */ + // "navigate" | "same-origin" | "no-cors" | "cors" public var mode: JsAny? get() = definedExternally set(value) = definedExternally - /* "follow" | "error" | "manual" */ + // "follow" | "error" | "manual" public var redirect: JsAny? get() = definedExternally set(value) = definedExternally @@ -236,7 +236,7 @@ public external interface RequestInit : JsAny { get() = definedExternally set(value) = definedExternally - /* "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" */ + // "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" public var referrerPolicy: JsAny? get() = definedExternally set(value) = definedExternally diff --git a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibEs5.kt b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibEs5.kt index f54464daf2b..086cc79868b 100644 --- a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibEs5.kt +++ b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/fetch/LibEs5.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.fetch @@ -34,7 +34,7 @@ public external interface Uint8Array : JsAny { target: JsNumber, start: JsNumber, end: JsNumber? = definedExternally - ): Uint8Array /* this */ + ): Uint8Array // this public fun every( callbackfn: (value: JsNumber, index: JsNumber, array: Uint8Array) -> JsAny, @@ -45,7 +45,7 @@ public external interface Uint8Array : JsAny { value: JsNumber, start: JsNumber? = definedExternally, end: JsNumber? = definedExternally - ): Uint8Array /* this */ + ): Uint8Array // this public fun filter( callbackfn: (value: JsNumber, index: JsNumber, array: Uint8Array) -> JsAny, @@ -147,7 +147,7 @@ public external interface Uint8Array : JsAny { thisArg: JsAny? = definedExternally ): Boolean - public fun sort(compareFn: ((a: JsNumber, b: JsNumber) -> JsNumber)? = definedExternally): Uint8Array /* this */ + public fun sort(compareFn: ((a: JsNumber, b: JsNumber) -> JsNumber)? = definedExternally): Uint8Array // this public fun subarray(begin: JsNumber? = definedExternally, end: JsNumber? = definedExternally): Uint8Array diff --git a/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlAdapters.kt b/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlAdapters.kt index ca25667c919..6cfb7418c49 100644 --- a/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlAdapters.kt +++ b/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlAdapters.kt @@ -1,11 +1,10 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.curl.internal import io.ktor.client.engine.* -import io.ktor.client.engine.curl.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.utils.io.* @@ -82,6 +81,6 @@ internal fun UInt.fromCurl(): HttpProtocolVersion = when (this) { CURL_HTTP_VERSION_1_0 -> HttpProtocolVersion.HTTP_1_0 CURL_HTTP_VERSION_1_1 -> HttpProtocolVersion.HTTP_1_1 CURL_HTTP_VERSION_2_0 -> HttpProtocolVersion.HTTP_2_0 - /* old curl fallback */ + // old curl fallback else -> HttpProtocolVersion.HTTP_1_1 } diff --git a/ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyPinnedCertificate.kt b/ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyPinnedCertificate.kt index 07ab601a453..df754f64fa1 100644 --- a/ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyPinnedCertificate.kt +++ b/ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyPinnedCertificate.kt @@ -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 @@ -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 } @@ -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" @@ -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( @@ -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" ) diff --git a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/certificates/PinnedCertificate.kt b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/certificates/PinnedCertificate.kt index da60b32fbf3..5ea8379aa08 100644 --- a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/certificates/PinnedCertificate.kt +++ b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/certificates/PinnedCertificate.kt @@ -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 @@ -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 } @@ -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" @@ -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( @@ -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" ) diff --git a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt index 00de3dc5093..943735e5ab6 100644 --- a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt +++ b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.darwin.internal @@ -18,7 +18,7 @@ import platform.Foundation.* import platform.darwin.* import kotlin.coroutines.* -@OptIn(UnsafeNumber::class, ExperimentalCoroutinesApi::class, ExperimentalForeignApi::class) +@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) internal class DarwinWebsocketSession( callContext: CoroutineContext, private val task: NSURLSessionWebSocketTask, @@ -100,17 +100,21 @@ internal class DarwinWebsocketSession( ) { error -> if (error == null) { continuation.resume(Unit) - } else continuation.resumeWithException(DarwinHttpRequestException(error)) + } else { + continuation.resumeWithException(DarwinHttpRequestException(error)) + } } } } FrameType.BINARY -> { - suspendCancellableCoroutine { continuation -> + suspendCancellableCoroutine { continuation -> task.sendMessage(NSURLSessionWebSocketMessage(frame.data.toNSData())) { error -> if (error == null) { continuation.resume(Unit) - } else continuation.resumeWithException(DarwinHttpRequestException(error)) + } else { + continuation.resumeWithException(DarwinHttpRequestException(error)) + } } } } diff --git a/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpWebSocket.kt b/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpWebSocket.kt index a15383feda1..a4d7ab9fb90 100644 --- a/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpWebSocket.kt +++ b/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpWebSocket.kt @@ -113,7 +113,6 @@ internal class JavaHttpWebSocket( } } - @OptIn(ExperimentalCoroutinesApi::class) GlobalScope.launch(callContext, start = CoroutineStart.ATOMIC) { try { socketJob[Job]!!.join() diff --git a/ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/CORSTest.kt b/ktor-client/ktor-client-js/js/.gitkeep similarity index 100% rename from ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/CORSTest.kt rename to ktor-client/ktor-client-js/js/.gitkeep diff --git a/ktor-client/ktor-client-js/js/src/Js.kt b/ktor-client/ktor-client-js/js/src/Js.kt deleted file mode 100644 index 9d9ed90fbfa..00000000000 --- a/ktor-client/ktor-client-js/js/src/Js.kt +++ /dev/null @@ -1,3 +0,0 @@ -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ diff --git a/ktor-utils/jsAndWasmShared/test/io.ktor.util/KtorSimpleLoggerTest.kt b/ktor-client/ktor-client-js/wasmJs/.gitkeep similarity index 100% rename from ktor-utils/jsAndWasmShared/test/io.ktor.util/KtorSimpleLoggerTest.kt rename to ktor-client/ktor-client-js/wasmJs/.gitkeep diff --git a/ktor-client/ktor-client-js/wasmJs/src/Wasm.kt b/ktor-client/ktor-client-js/wasmJs/src/Wasm.kt deleted file mode 100644 index e88e11fb9d9..00000000000 --- a/ktor-client/ktor-client-js/wasmJs/src/Wasm.kt +++ /dev/null @@ -1,3 +0,0 @@ -/* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ diff --git a/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt b/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt index 022e9c96834..120b091f39b 100644 --- a/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt +++ b/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.mock @@ -25,7 +25,7 @@ public class MockEngine(override val config: MockEngineConfig) : HttpClientEngin private val mutex = SynchronizedObject() private val contextState: CompletableJob = Job() - private val _requestsHistory: MutableList = mutableListOf() + private val _requestHistory: MutableList = mutableListOf() private val _responseHistory: MutableList = mutableListOf() private var invocationCount: Int = 0 @@ -39,7 +39,7 @@ public class MockEngine(override val config: MockEngineConfig) : HttpClientEngin /** * History of executed requests. */ - public val requestHistory: List get() = _requestsHistory + public val requestHistory: List get() = _requestHistory /** * History of sent responses. @@ -67,7 +67,7 @@ public class MockEngine(override val config: MockEngineConfig) : HttpClientEngin } synchronized(mutex) { - _requestsHistory.add(data) + _requestHistory.add(data) _responseHistory.add(response) } diff --git a/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockUtils.kt b/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockUtils.kt index 8a9bc35d3ff..3c5f56e8473 100644 --- a/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockUtils.kt +++ b/ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockUtils.kt @@ -14,7 +14,7 @@ import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlinx.io.* -@OptIn(DelicateCoroutinesApi::class, InternalAPI::class) +@OptIn(DelicateCoroutinesApi::class) public suspend fun OutgoingContent.toByteArray(): ByteArray = when (this) { is OutgoingContent.ContentWrapper -> delegate().toByteArray() is OutgoingContent.ByteArrayContent -> bytes() @@ -32,7 +32,7 @@ public suspend fun OutgoingContent.toByteArray(): ByteArray = when (this) { } @Suppress("KDocMissingDocumentation", "DEPRECATION") -@OptIn(DelicateCoroutinesApi::class, InternalAPI::class) +@OptIn(DelicateCoroutinesApi::class) public suspend fun OutgoingContent.toByteReadPacket(): Source = when (this) { is OutgoingContent.ByteArrayContent -> ByteReadPacket(bytes()) is OutgoingContent.ReadChannelContent -> readFrom().readRemaining() diff --git a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt index d4eba7134c9..2d38a17775e 100644 --- a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt +++ b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt @@ -44,7 +44,6 @@ public class OkHttpEngine(override val config: OkHttpConfig) : HttpClientEngineB requestsJob = SilentSupervisor(parent) coroutineContext = super.coroutineContext + requestsJob - @OptIn(ExperimentalCoroutinesApi::class) GlobalScope.launch(super.coroutineContext, start = CoroutineStart.ATOMIC) { try { requestsJob[Job]!!.join() diff --git a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpSSESession.kt b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpSSESession.kt index f62eab234ee..90f0ac0ccf4 100644 --- a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpSSESession.kt +++ b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpSSESession.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.okhttp @@ -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, @@ -64,17 +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]}" // ktlint-disable max-line-length + message = "Content type must be ${ContentType.Text.EventStream} but was ${response.headers[HttpHeaders.ContentType]}" ) - else -> SSEClientException(message = "Unexpected error occurred in OkHttpSSESession") + else -> unexpectedError() } } } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt index 1fd57fa6d25..1bdc315d6f1 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.auth @@ -156,6 +156,7 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon /** * Install [Auth] plugin. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.Auth(block: AuthConfig.() -> Unit) { install(Auth, block) } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BasicAuthProvider.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BasicAuthProvider.kt index 83b96974702..1e62ef8e70c 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BasicAuthProvider.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BasicAuthProvider.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.auth.providers @@ -20,7 +20,7 @@ import io.ktor.utils.io.core.* @KtorDsl public fun AuthConfig.basic(block: BasicAuthConfig.() -> Unit) { with(BasicAuthConfig().apply(block)) { - this@basic.providers.add(BasicAuthProvider(_credentials, realm, _sendWithoutRequest)) + this@basic.providers.add(BasicAuthProvider(credentials, realm, _sendWithoutRequest)) } } @@ -52,11 +52,11 @@ public class BasicAuthConfig { */ public var realm: String? = null - @Suppress("DEPRECATION_ERROR") + @Suppress("DEPRECATION_ERROR", "PropertyName") internal var _sendWithoutRequest: (HttpRequestBuilder) -> Boolean = { sendWithoutRequest } @Suppress("DEPRECATION_ERROR") - internal var _credentials: suspend () -> BasicAuthCredentials? = { + internal var credentials: suspend () -> BasicAuthCredentials? = { BasicAuthCredentials(username = username, password = password) } @@ -71,7 +71,7 @@ public class BasicAuthConfig { * Allows you to specify authentication credentials. */ public fun credentials(block: suspend () -> BasicAuthCredentials?) { - _credentials = block + credentials = block } } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BearerAuthProvider.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BearerAuthProvider.kt index 33fb1c2c056..879cb47929d 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BearerAuthProvider.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BearerAuthProvider.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.auth.providers @@ -17,7 +17,7 @@ import io.ktor.utils.io.* */ public fun AuthConfig.bearer(block: BearerAuthConfig.() -> Unit) { with(BearerAuthConfig().apply(block)) { - this@bearer.providers.add(BearerAuthProvider(_refreshTokens, _loadTokens, _sendWithoutRequest, realm)) + this@bearer.providers.add(BearerAuthProvider(refreshTokens, loadTokens, sendWithoutRequest, realm)) } } @@ -48,9 +48,9 @@ public class RefreshTokensParams( */ @KtorDsl public class BearerAuthConfig { - internal var _refreshTokens: suspend RefreshTokensParams.() -> BearerTokens? = { null } - internal var _loadTokens: suspend () -> BearerTokens? = { null } - internal var _sendWithoutRequest: (HttpRequestBuilder) -> Boolean = { true } + internal var refreshTokens: suspend RefreshTokensParams.() -> BearerTokens? = { null } + internal var loadTokens: suspend () -> BearerTokens? = { null } + internal var sendWithoutRequest: (HttpRequestBuilder) -> Boolean = { true } public var realm: String? = null @@ -58,7 +58,7 @@ public class BearerAuthConfig { * Configures a callback that refreshes a token when the 401 status code is received. */ public fun refreshTokens(block: suspend RefreshTokensParams.() -> BearerTokens?) { - _refreshTokens = block + refreshTokens = block } /** @@ -66,14 +66,14 @@ public class BearerAuthConfig { * Note: Using the same client instance here to make a request will result in a deadlock. */ public fun loadTokens(block: suspend () -> BearerTokens?) { - _loadTokens = block + loadTokens = block } /** * Sends credentials without waiting for [HttpStatusCode.Unauthorized]. */ public fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean) { - _sendWithoutRequest = block + sendWithoutRequest = block } } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/DigestAuthProvider.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/DigestAuthProvider.kt index 1d57c85e752..6e1e5001dc3 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/DigestAuthProvider.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/DigestAuthProvider.kt @@ -9,7 +9,6 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.auth.* -import io.ktor.http.auth.HeaderValueEncoding import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* @@ -22,7 +21,7 @@ import kotlinx.atomicfu.* public fun AuthConfig.digest(block: DigestAuthConfig.() -> Unit) { val config = DigestAuthConfig().apply(block) with(config) { - this@digest.providers += DigestAuthProvider(_credentials, realm, algorithmName) + this@digest.providers += DigestAuthProvider(credentials, realm, algorithmName) } } @@ -52,7 +51,7 @@ public class DigestAuthConfig { public var realm: String? = null @Suppress("DEPRECATION_ERROR") - internal var _credentials: suspend () -> DigestAuthCredentials? = { + internal var credentials: suspend () -> DigestAuthCredentials? = { DigestAuthCredentials(username = username, password = password) } @@ -60,7 +59,7 @@ public class DigestAuthConfig { * Allows you to specify authentication credentials. */ public fun credentials(block: suspend () -> DigestAuthCredentials?) { - _credentials = block + credentials = block } } diff --git a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/ktor-client-content-negotiation-tests/jvm/src/io/ktor/client/plugins/contentnegotiation/tests/AbstractClientContentNegotiationTest.kt b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/ktor-client-content-negotiation-tests/jvm/src/io/ktor/client/plugins/contentnegotiation/tests/AbstractClientContentNegotiationTest.kt index 2d5e39426b7..06f031d0139 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/ktor-client-content-negotiation-tests/jvm/src/io/ktor/client/plugins/contentnegotiation/tests/AbstractClientContentNegotiationTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/ktor-client-content-negotiation-tests/jvm/src/io/ktor/client/plugins/contentnegotiation/tests/AbstractClientContentNegotiationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.client.plugins.contentnegotiation.tests import com.fasterxml.jackson.annotation.* @@ -95,7 +96,8 @@ abstract class AbstractClientContentNegotiationTest : TestWithKtor() { Response.serializer(ListSerializer(User.serializer())) ) } - get("/users-x") { // route for testing custom content type, namely "application/x-${contentSubtype}" + // route for testing custom content type, namely "application/x-${contentSubtype}" + get("/users-x") { call.respond( """{"ok":true,"result":[{"name":"x","age":10},{"name":"y","age":45}]}""", customContentType, diff --git a/ktor-client/ktor-client-plugins/ktor-client-encoding/common/src/ContentEncoding.kt b/ktor-client/ktor-client-plugins/ktor-client-encoding/common/src/ContentEncoding.kt index 6cf4e701a82..bd5ce105198 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-encoding/common/src/ContentEncoding.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-encoding/common/src/ContentEncoding.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.plugins.compression @@ -26,7 +26,9 @@ private val LOGGER = KtorSimpleLogger("io.ktor.client.plugins.compression.Conten public class ContentEncodingConfig { public enum class Mode(internal val request: Boolean, internal val response: Boolean) { - CompressRequest(true, false), DecompressResponse(false, true), All(true, true) + CompressRequest(true, false), + DecompressResponse(false, true), + All(true, true), } internal val encoders: MutableMap = CaseInsensitiveMap() @@ -217,6 +219,7 @@ internal object ReceiveStateHook : ClientHook HttpResp * * @param block: a [ContentEncoding] configuration. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.ContentEncoding( mode: ContentEncodingConfig.Mode = ContentEncodingConfig.Mode.DecompressResponse, block: ContentEncodingConfig.() -> Unit = { diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonPlugin.kt b/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonPlugin.kt index bacc893efe3..0830659513c 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonPlugin.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonPlugin.kt @@ -232,6 +232,7 @@ public class JsonPlugin internal constructor( /** * Install [JsonPlugin]. */ +@Suppress("FunctionName") @Deprecated( "Please use ContentNegotiation plugin: https://ktor.io/docs/migration-to-20x.html#serialization-client", level = DeprecationLevel.ERROR diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonSerializer.kt b/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonSerializer.kt index 223cf7861f2..4ed1badd3f8 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonSerializer.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/common/src/io/ktor/client/plugins/json/JsonSerializer.kt @@ -12,8 +12,9 @@ import io.ktor.utils.io.core.* /** * Client json serializer. */ +@Suppress("ktlint:standard:max-line-length") @Deprecated( - "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", // ktlint-disable max-line-length + "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", level = DeprecationLevel.ERROR ) public interface JsonSerializer { diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-gson/jvm/src/io/ktor/client/plugins/gson/GsonSerializer.kt b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-gson/jvm/src/io/ktor/client/plugins/gson/GsonSerializer.kt index 516ab931b70..a507a765a92 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-gson/jvm/src/io/ktor/client/plugins/gson/GsonSerializer.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-gson/jvm/src/io/ktor/client/plugins/gson/GsonSerializer.kt @@ -15,8 +15,9 @@ import io.ktor.utils.io.core.* /** * [JsonSerializer] using [Gson] as backend. */ +@Suppress("ktlint:standard:max-line-length") @Deprecated( - "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", // ktlint-disable max-line-length + "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", level = DeprecationLevel.ERROR ) public class GsonSerializer(block: GsonBuilder.() -> Unit = {}) : JsonSerializer { diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-jackson/jvm/src/io/ktor/client/plugins/jackson/JacksonSerializer.kt b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-jackson/jvm/src/io/ktor/client/plugins/jackson/JacksonSerializer.kt index c8007793877..33942958e80 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-jackson/jvm/src/io/ktor/client/plugins/jackson/JacksonSerializer.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-jackson/jvm/src/io/ktor/client/plugins/jackson/JacksonSerializer.kt @@ -14,8 +14,9 @@ import io.ktor.http.content.* import io.ktor.util.reflect.* import io.ktor.utils.io.core.* +@Suppress("ktlint:standard:max-line-length") @Deprecated( - "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", // ktlint-disable max-line-length + "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", level = DeprecationLevel.ERROR ) public class JacksonSerializer( diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/src/io/ktor/client/plugins/kotlinx/serializer/KotlinxSerializer.kt b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/src/io/ktor/client/plugins/kotlinx/serializer/KotlinxSerializer.kt index 28fbbf856c0..0822a6fbcd9 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/src/io/ktor/client/plugins/kotlinx/serializer/KotlinxSerializer.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/src/io/ktor/client/plugins/kotlinx/serializer/KotlinxSerializer.kt @@ -19,8 +19,9 @@ import kotlinx.serialization.modules.* /** * A [JsonSerializer] implemented for kotlinx [Serializable] classes. */ +@Suppress("ktlint:standard:max-line-length") @Deprecated( - "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", // ktlint-disable max-line-length + "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migration-to-20x.html#serialization-client", level = DeprecationLevel.ERROR ) public class KotlinxSerializer( diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/KtorMDCContext.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/KtorMDCContext.kt index d0131ca9cdd..a3a84222c9f 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/KtorMDCContext.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/KtorMDCContext.kt @@ -7,5 +7,6 @@ package io.ktor.client.plugins.logging import io.ktor.utils.io.* import kotlin.coroutines.* +@Suppress("FunctionName") @InternalAPI public expect fun MDCContext(): CoroutineContext.Element diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt index df08d200cbe..2665b76d500 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.logging @@ -242,6 +242,7 @@ public val Logging: ClientPlugin = createClientPlugin("Logging", /** * Configures and installs [Logging] in [HttpClient]. */ +@Suppress("FunctionName") public fun HttpClientConfig<*>.Logging(block: LoggingConfig.() -> Unit = {}) { install(Logging, block) } diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/jsAndWasmShared/src/io/ktor/client/plugins/logging/KtorMDCContext.jsAndWasmShared.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/jsAndWasmShared/src/io/ktor/client/plugins/logging/KtorMDCContext.jsAndWasmShared.kt index 44ed24d4d55..8571a6315b1 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/jsAndWasmShared/src/io/ktor/client/plugins/logging/KtorMDCContext.jsAndWasmShared.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/jsAndWasmShared/src/io/ktor/client/plugins/logging/KtorMDCContext.jsAndWasmShared.kt @@ -7,6 +7,7 @@ package io.ktor.client.plugins.logging import io.ktor.utils.io.* import kotlin.coroutines.* +@Suppress("FunctionName") @InternalAPI public actual fun MDCContext(): CoroutineContext.Element = MDCContextElement diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/src/io/ktor/client/plugins/logging/KtorMDCContext.jvm.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/src/io/ktor/client/plugins/logging/KtorMDCContext.jvm.kt index 85f830518a7..db83ca21e54 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/src/io/ktor/client/plugins/logging/KtorMDCContext.jvm.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/src/io/ktor/client/plugins/logging/KtorMDCContext.jvm.kt @@ -5,9 +5,9 @@ package io.ktor.client.plugins.logging import io.ktor.utils.io.* -import kotlinx.coroutines.slf4j.* import kotlin.coroutines.* +@Suppress("FunctionName") @InternalAPI public actual fun MDCContext(): CoroutineContext.Element { return kotlinx.coroutines.slf4j.MDCContext() diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/posix/src/io/ktor/client/plugins/logging/KtorMDCContext.posix.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/posix/src/io/ktor/client/plugins/logging/KtorMDCContext.posix.kt index 44ed24d4d55..8571a6315b1 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/posix/src/io/ktor/client/plugins/logging/KtorMDCContext.posix.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/posix/src/io/ktor/client/plugins/logging/KtorMDCContext.posix.kt @@ -7,6 +7,7 @@ package io.ktor.client.plugins.logging import io.ktor.utils.io.* import kotlin.coroutines.* +@Suppress("FunctionName") @InternalAPI public actual fun MDCContext(): CoroutineContext.Element = MDCContextElement diff --git a/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketRemoteTest.kt b/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketRemoteTest.kt index f9f694f60e9..9e7a527cc98 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketRemoteTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketRemoteTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.client.tests.plugins import io.ktor.client.plugins.* diff --git a/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketTest.kt b/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketTest.kt index fa39d86ba80..2e15d5f5843 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-websockets/common/test/io/ktor/client/tests/plugins/WebSocketTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.plugins @@ -34,7 +34,8 @@ class WebSocketTest { path = "/websocket" ) { } - } catch (_: Throwable) {} + } catch (_: Throwable) { + } assertEquals(443, port) } diff --git a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt index 59ac996b784..1dd64ca5266 100644 --- a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt +++ b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NO_EXPLICIT_RETURN_TYPE_IN_API_MODE_WARNING", "KDocMissingDocumentation") @@ -148,6 +148,6 @@ fun TestClientBuilder<*>.test(block: suspend TestInfo.(client: HttpClient) -> Un test = block } -fun TestClientBuilder<*>.after(block: suspend (client: HttpClient) -> Unit) { // ktlint-disable no-unit-return +fun TestClientBuilder<*>.after(block: suspend (client: HttpClient) -> Unit) { after = block } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt index 41c47af0e37..c67f33eaaf5 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt @@ -19,9 +19,14 @@ import io.ktor.http.content.* import io.ktor.serialization.kotlinx.json.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* -import kotlinx.coroutines.* -import kotlinx.serialization.* -import kotlin.test.* +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import kotlinx.serialization.Serializable +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue private val DOUBLE_TEST_ARRAY = ByteArray(16 * 1025) { 1 } private val TEST_ARRAY = ByteArray(8 * 1025) { 1 } @@ -45,12 +50,11 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val response: HttpResponse = client.post("$TEST_SERVER/content/echo") { contentType(ContentType.Application.Json) setBody(User(TEST_NAME, 1)) - onUpload(listener) + onUpload { _, _ -> invokedCount++ } } assertEquals("""{"login":"$TEST_NAME","id":1}""", response.body()) assertTrue(invokedCount >= 2) @@ -61,7 +65,6 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { fun testSendWriteChannelContent() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val response: HttpResponse = client.post("$TEST_SERVER/content/echo") { setBody( @@ -74,19 +77,17 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { } } ) - onUpload(listener) + onUpload { _, _ -> invokedCount++ } } assertContentEquals(DOUBLE_TEST_ARRAY, response.body()) assertTrue(invokedCount >= 2) } } - @OptIn(InternalAPI::class) @Test fun testSendChannel() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val channel = ByteChannel() GlobalScope.launch { @@ -97,7 +98,7 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { val response: HttpResponse = client.post("$TEST_SERVER/content/echo") { setBody(channel) - onUpload(listener) + onUpload { _, _ -> invokedCount++ } } assertContentEquals(DOUBLE_TEST_ARRAY, response.body()) assertTrue(invokedCount > 2) @@ -108,11 +109,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { fun testSendByteArray() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val response: HttpResponse = client.post("$TEST_SERVER/content/echo") { setBody(DOUBLE_TEST_ARRAY) - onUpload(listener) + onUpload { _, _ -> invokedCount++ } } assertContentEquals(DOUBLE_TEST_ARRAY, response.body()) assertTrue(invokedCount > 2) @@ -129,11 +129,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } client.prepareGet("$TEST_SERVER/json/users-long") { contentType(ContentType.Application.Json) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.execute { val result = it.body>() val users = buildList { repeat(300) { add(User(id = it.toLong(), login = "TestLogin-$it")) } } @@ -153,11 +152,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } client.prepareGet("$TEST_SERVER/json/users-long") { contentType(ContentType.Application.Json) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.body, Unit> { val users = buildList { repeat(300) { add(User(id = it.toLong(), login = "TestLogin-$it")) } } assertEquals(users, it) @@ -166,12 +164,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { } } - @OptIn(InternalAPI::class) @Test fun testReceiveChannelWithExecute() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val channel = ByteChannel() GlobalScope.launch { @@ -182,7 +178,7 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { client.preparePost("$TEST_SERVER/content/echo") { setBody(channel) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.execute { val result = it.body().readRemaining().readBytes() assertContentEquals(DOUBLE_TEST_ARRAY, result) @@ -191,12 +187,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { } } - @OptIn(InternalAPI::class) @Test fun testReceiveChannelWithReceive() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } val channel = ByteChannel() GlobalScope.launch { @@ -207,7 +201,7 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { client.preparePost("$TEST_SERVER/content/echo") { setBody(channel) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.body { val result = it.readRemaining().readBytes() assertContentEquals(DOUBLE_TEST_ARRAY, result) @@ -220,11 +214,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { fun testReceiveByteArrayWithExecute() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } client.preparePost("$TEST_SERVER/content/echo") { setBody(DOUBLE_TEST_ARRAY) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.execute { val result = it.body() assertContentEquals(DOUBLE_TEST_ARRAY, result) @@ -237,11 +230,10 @@ class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { fun testReceiveByteArrayWithReceive() = clientTests { test { client -> invokedCount = 0 - val listener = { _: Long, _: Long? -> invokedCount++; Unit } client.preparePost("$TEST_SERVER/content/echo") { setBody(DOUBLE_TEST_ARRAY) - onDownload(listener) + onDownload { _, _ -> invokedCount++ } }.body { assertContentEquals(DOUBLE_TEST_ARRAY, it) } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt index e0a79af01ad..758e62889a8 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt @@ -403,16 +403,18 @@ class ContentTest : ClientLoader(5 * 60) { HttpResponseValidator { validateResponse { response -> val channel = response.rawContent - for (i in 0..100) + for (i in 0..100) { assertEquals(expected, channel.readByteArray(expected.length).decodeToString()) + } } } }.get("$TEST_SERVER/content/big-plain-text").bodyAsText() val lines = responseText.trim().lines() assertEquals(10_000, lines.size, "Should be same number of lines") - for ((i, line) in lines.withIndex()) + for ((i, line) in lines.withIndex()) { assertEquals(expected.trim(), line, "Difference on line $i") + } } } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt index 5d2e93d892c..9285dd2a14b 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests @@ -11,11 +11,11 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.client.tests.utils.* import io.ktor.http.* -import io.ktor.util.PlatformUtils +import io.ktor.util.* import io.ktor.utils.io.* -import io.ktor.utils.io.CancellationException -import kotlinx.coroutines.* -import kotlinx.io.* +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.withTimeout +import kotlinx.io.IOException import kotlin.test.* private const val TEST_URL = "$TEST_SERVER/timeout" @@ -438,7 +438,7 @@ class HttpTimeoutTest : ClientLoader() { assertFails { try { client.get("http://localhost:11").body() - } catch (_: ConnectTimeoutException) { /* Ignore. */ + } catch (_: ConnectTimeoutException) { } } } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt index 58b59a3ed90..f3c983e0f48 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt @@ -20,7 +20,6 @@ class JsonTest : ClientLoader() { @Polymorphic data class Result(val message: String, val data: T) - @OptIn(ExperimentalStdlibApi::class) @Test fun testUserGenerics() = clientTests(listOf("js")) { config { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingMockedTests.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingMockedTests.kt index a0ebab05450..7764d072ac8 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingMockedTests.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingMockedTests.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.tests @@ -18,6 +18,7 @@ import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlin.test.* +import kotlin.time.Duration.Companion.seconds class LoggingMockedTests { @@ -299,7 +300,6 @@ class LoggingMockedTests { } } - @OptIn(InternalAPI::class) @Test fun testCanStream() = testWithEngine(MockEngine) { val channel = ByteChannel(autoFlush = true) @@ -332,7 +332,8 @@ class LoggingMockedTests { channel.writeStringUtf8("Hello world!\n") - withTimeout(5_000) { // the bug will cause this to timeout + // the bug will cause this to timeout + withTimeout(5.seconds) { content.collect { channel.close() } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt index f77e7115cce..4643a98a45a 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests @@ -48,11 +48,13 @@ class MockedTests { engine { // these differ by one char at the end + @Suppress("ktlint:standard:max-line-length") val longJSONString = - """{"author": "H. P. Lovecraft", "name": "The Nameless City", "text": "When I drew nigh the nameless city I knew it was accursed. I was traveling in a parched and terrible valley under the moon, and afar I saw it protruding uncannily above the sands as parts of a corpse may protrude from an ill-made grave. Fear spoke from the age-worn stones of this hoary survivor of the deluge, this great-grandfather of the eldest pyramid; and a viewless aura repelled me and bade me retreat from antique and sinister secrets that no man should see, and no man else had dared to see..\nRemote in the desert of Araby lies the nameless city, crumbling and inarticulate, its low walls nearly hidden by the sands of uncounted ages. It must have been thus before the first stones of Memphis were laid, and while the bricks of Babylon were yet unbaked. There is no legend so old as to give it a name, or to recall that it was ever alive; but it is told of in whispers around campfires and muttered about by grandams in the tents of sheiks so that all the tribes shun it without wholly knowing why. It was of this place that Abdul Alhazred the mad poet dreamed of the night before he sang his unexplained couplet:\nThat is not dead which can eternal lie, / And with strange aeons even death may die.\nI should have known that the Arabs had good reason for shunning the nameless city, the city told of in strange tales but seen by no living man, yet I defied them and went into the untrodden waste with my camel. I alone have seen it, and that is why no other face bears such hideous lines of fear as mine; why no other man shivers so horribly when the night wind rattles the windows. When I came upon it in the ghastly stillness of unending sleep it looked at me, chilly from the rays of a cold moon amidst the desert's heat. And as I returned its look I forgot my triumph at finding it, and stopped still with my camel to wait for the dawn.\nFor hours I waited, till the east grew grey and the stars faded, and the grey turned to roseate light edged with gold. I heard a moaning and saw a storm of sand stirring among the antique stones though the sky was clear and the vast reaches of desert still. Then suddenly above the desert's far rim came the blazing edge of the sun, seen through the tiny sandstorm which was passing away, and in my fevered state I fancied that from some remote depth there came a crash of musical metal to hail the fiery disc as Memnon hails it from the banks of the Nile. My ears rang and my imagination seethed as I led my camel slowly across the sand to that unvocal place; that place which I alone of living men had seen.\nIn and out amongst the shapeless foundations of houses and places I wandered, finding never a carving or inscription to tell of these men, if men they were, who built this city and dwelt therein so long ago. The antiquity of the spot was unwholesome, and I longed to encounter some sign or device to prove that the city was indeed fashioned by mankind. There were certain proportions and dimensions in the ruins which I did not like. I had with me many tools, and dug much within the walls of the obliterated edifices; but progress was slow, and nothing significant was revealed. When night and the moon returned I felt a chill wind which brought new fear, so that I did not dare to remain in the city. And as I went outside the antique walls to sleep, a small sighing sandstorm gathered behind me, blowing over the grey stones though the moon was bright and most of the desert still.\nI awakened just at dawn from a pageant of horrible dreams, my ears ringing as from some metallic peal. I saw the sun peering redly through the last gusts of a little sandstorm that hovered over the nameless city, and marked the quietness of the rest of the landscape. Once more I ventured within those brooding ruins that swelled beneath the sand like an ogre under a coverlet, and again dug vainly for relics of the forgotten race. At noon I rested, and in the afternoon I spent much time tracing the walls and bygone streets, and the outlines of the nearly vanish..."}""" // ktlint-disable max-line-length + """{"author": "H. P. Lovecraft", "name": "The Nameless City", "text": "When I drew nigh the nameless city I knew it was accursed. I was traveling in a parched and terrible valley under the moon, and afar I saw it protruding uncannily above the sands as parts of a corpse may protrude from an ill-made grave. Fear spoke from the age-worn stones of this hoary survivor of the deluge, this great-grandfather of the eldest pyramid; and a viewless aura repelled me and bade me retreat from antique and sinister secrets that no man should see, and no man else had dared to see..\nRemote in the desert of Araby lies the nameless city, crumbling and inarticulate, its low walls nearly hidden by the sands of uncounted ages. It must have been thus before the first stones of Memphis were laid, and while the bricks of Babylon were yet unbaked. There is no legend so old as to give it a name, or to recall that it was ever alive; but it is told of in whispers around campfires and muttered about by grandams in the tents of sheiks so that all the tribes shun it without wholly knowing why. It was of this place that Abdul Alhazred the mad poet dreamed of the night before he sang his unexplained couplet:\nThat is not dead which can eternal lie, / And with strange aeons even death may die.\nI should have known that the Arabs had good reason for shunning the nameless city, the city told of in strange tales but seen by no living man, yet I defied them and went into the untrodden waste with my camel. I alone have seen it, and that is why no other face bears such hideous lines of fear as mine; why no other man shivers so horribly when the night wind rattles the windows. When I came upon it in the ghastly stillness of unending sleep it looked at me, chilly from the rays of a cold moon amidst the desert's heat. And as I returned its look I forgot my triumph at finding it, and stopped still with my camel to wait for the dawn.\nFor hours I waited, till the east grew grey and the stars faded, and the grey turned to roseate light edged with gold. I heard a moaning and saw a storm of sand stirring among the antique stones though the sky was clear and the vast reaches of desert still. Then suddenly above the desert's far rim came the blazing edge of the sun, seen through the tiny sandstorm which was passing away, and in my fevered state I fancied that from some remote depth there came a crash of musical metal to hail the fiery disc as Memnon hails it from the banks of the Nile. My ears rang and my imagination seethed as I led my camel slowly across the sand to that unvocal place; that place which I alone of living men had seen.\nIn and out amongst the shapeless foundations of houses and places I wandered, finding never a carving or inscription to tell of these men, if men they were, who built this city and dwelt therein so long ago. The antiquity of the spot was unwholesome, and I longed to encounter some sign or device to prove that the city was indeed fashioned by mankind. There were certain proportions and dimensions in the ruins which I did not like. I had with me many tools, and dug much within the walls of the obliterated edifices; but progress was slow, and nothing significant was revealed. When night and the moon returned I felt a chill wind which brought new fear, so that I did not dare to remain in the city. And as I went outside the antique walls to sleep, a small sighing sandstorm gathered behind me, blowing over the grey stones though the moon was bright and most of the desert still.\nI awakened just at dawn from a pageant of horrible dreams, my ears ringing as from some metallic peal. I saw the sun peering redly through the last gusts of a little sandstorm that hovered over the nameless city, and marked the quietness of the rest of the landscape. Once more I ventured within those brooding ruins that swelled beneath the sand like an ogre under a coverlet, and again dug vainly for relics of the forgotten race. At noon I rested, and in the afternoon I spent much time tracing the walls and bygone streets, and the outlines of the nearly vanish..."}""" + @Suppress("ktlint:standard:max-line-length") val longerJSONString = - """{"author": "H. P. Lovecraft", "name": "The Nameless City", "text": "When I drew nigh the nameless city I knew it was accursed. I was traveling in a parched and terrible valley under the moon, and afar I saw it protruding uncannily above the sands as parts of a corpse may protrude from an ill-made grave. Fear spoke from the age-worn stones of this hoary survivor of the deluge, this great-grandfather of the eldest pyramid; and a viewless aura repelled me and bade me retreat from antique and sinister secrets that no man should see, and no man else had dared to see..\nRemote in the desert of Araby lies the nameless city, crumbling and inarticulate, its low walls nearly hidden by the sands of uncounted ages. It must have been thus before the first stones of Memphis were laid, and while the bricks of Babylon were yet unbaked. There is no legend so old as to give it a name, or to recall that it was ever alive; but it is told of in whispers around campfires and muttered about by grandams in the tents of sheiks so that all the tribes shun it without wholly knowing why. It was of this place that Abdul Alhazred the mad poet dreamed of the night before he sang his unexplained couplet:\nThat is not dead which can eternal lie, / And with strange aeons even death may die.\nI should have known that the Arabs had good reason for shunning the nameless city, the city told of in strange tales but seen by no living man, yet I defied them and went into the untrodden waste with my camel. I alone have seen it, and that is why no other face bears such hideous lines of fear as mine; why no other man shivers so horribly when the night wind rattles the windows. When I came upon it in the ghastly stillness of unending sleep it looked at me, chilly from the rays of a cold moon amidst the desert's heat. And as I returned its look I forgot my triumph at finding it, and stopped still with my camel to wait for the dawn.\nFor hours I waited, till the east grew grey and the stars faded, and the grey turned to roseate light edged with gold. I heard a moaning and saw a storm of sand stirring among the antique stones though the sky was clear and the vast reaches of desert still. Then suddenly above the desert's far rim came the blazing edge of the sun, seen through the tiny sandstorm which was passing away, and in my fevered state I fancied that from some remote depth there came a crash of musical metal to hail the fiery disc as Memnon hails it from the banks of the Nile. My ears rang and my imagination seethed as I led my camel slowly across the sand to that unvocal place; that place which I alone of living men had seen.\nIn and out amongst the shapeless foundations of houses and places I wandered, finding never a carving or inscription to tell of these men, if men they were, who built this city and dwelt therein so long ago. The antiquity of the spot was unwholesome, and I longed to encounter some sign or device to prove that the city was indeed fashioned by mankind. There were certain proportions and dimensions in the ruins which I did not like. I had with me many tools, and dug much within the walls of the obliterated edifices; but progress was slow, and nothing significant was revealed. When night and the moon returned I felt a chill wind which brought new fear, so that I did not dare to remain in the city. And as I went outside the antique walls to sleep, a small sighing sandstorm gathered behind me, blowing over the grey stones though the moon was bright and most of the desert still.\nI awakened just at dawn from a pageant of horrible dreams, my ears ringing as from some metallic peal. I saw the sun peering redly through the last gusts of a little sandstorm that hovered over the nameless city, and marked the quietness of the rest of the landscape. Once more I ventured within those brooding ruins that swelled beneath the sand like an ogre under a coverlet, and again dug vainly for relics of the forgotten race. At noon I rested, and in the afternoon I spent much time tracing the walls and bygone streets, and the outlines of the nearly vanishe..."}""" // ktlint-disable max-line-length + """{"author": "H. P. Lovecraft", "name": "The Nameless City", "text": "When I drew nigh the nameless city I knew it was accursed. I was traveling in a parched and terrible valley under the moon, and afar I saw it protruding uncannily above the sands as parts of a corpse may protrude from an ill-made grave. Fear spoke from the age-worn stones of this hoary survivor of the deluge, this great-grandfather of the eldest pyramid; and a viewless aura repelled me and bade me retreat from antique and sinister secrets that no man should see, and no man else had dared to see..\nRemote in the desert of Araby lies the nameless city, crumbling and inarticulate, its low walls nearly hidden by the sands of uncounted ages. It must have been thus before the first stones of Memphis were laid, and while the bricks of Babylon were yet unbaked. There is no legend so old as to give it a name, or to recall that it was ever alive; but it is told of in whispers around campfires and muttered about by grandams in the tents of sheiks so that all the tribes shun it without wholly knowing why. It was of this place that Abdul Alhazred the mad poet dreamed of the night before he sang his unexplained couplet:\nThat is not dead which can eternal lie, / And with strange aeons even death may die.\nI should have known that the Arabs had good reason for shunning the nameless city, the city told of in strange tales but seen by no living man, yet I defied them and went into the untrodden waste with my camel. I alone have seen it, and that is why no other face bears such hideous lines of fear as mine; why no other man shivers so horribly when the night wind rattles the windows. When I came upon it in the ghastly stillness of unending sleep it looked at me, chilly from the rays of a cold moon amidst the desert's heat. And as I returned its look I forgot my triumph at finding it, and stopped still with my camel to wait for the dawn.\nFor hours I waited, till the east grew grey and the stars faded, and the grey turned to roseate light edged with gold. I heard a moaning and saw a storm of sand stirring among the antique stones though the sky was clear and the vast reaches of desert still. Then suddenly above the desert's far rim came the blazing edge of the sun, seen through the tiny sandstorm which was passing away, and in my fevered state I fancied that from some remote depth there came a crash of musical metal to hail the fiery disc as Memnon hails it from the banks of the Nile. My ears rang and my imagination seethed as I led my camel slowly across the sand to that unvocal place; that place which I alone of living men had seen.\nIn and out amongst the shapeless foundations of houses and places I wandered, finding never a carving or inscription to tell of these men, if men they were, who built this city and dwelt therein so long ago. The antiquity of the spot was unwholesome, and I longed to encounter some sign or device to prove that the city was indeed fashioned by mankind. There were certain proportions and dimensions in the ruins which I did not like. I had with me many tools, and dug much within the walls of the obliterated edifices; but progress was slow, and nothing significant was revealed. When night and the moon returned I felt a chill wind which brought new fear, so that I did not dare to remain in the city. And as I went outside the antique walls to sleep, a small sighing sandstorm gathered behind me, blowing over the grey stones though the moon was bright and most of the desert still.\nI awakened just at dawn from a pageant of horrible dreams, my ears ringing as from some metallic peal. I saw the sun peering redly through the last gusts of a little sandstorm that hovered over the nameless city, and marked the quietness of the rest of the landscape. Once more I ventured within those brooding ruins that swelled beneath the sand like an ogre under a coverlet, and again dug vainly for relics of the forgotten race. At noon I rested, and in the afternoon I spent much time tracing the walls and bygone streets, and the outlines of the nearly vanishe..."}""" val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Application.Json.toString())) addHandler { request -> diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt index c723daff28f..e6e44a41849 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.client.tests.plugins import io.ktor.client.call.* diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/UserAgentTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/UserAgentTest.kt index 104c069cd2c..b52832098c7 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/UserAgentTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/UserAgentTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.client.tests.plugins import io.ktor.client.call.* diff --git a/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt b/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt index cc158c7b8c6..656d8ba9950 100644 --- a/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt +++ b/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt @@ -1,14 +1,13 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils import io.ktor.client.engine.* import io.ktor.client.engine.js.* -import kotlinx.coroutines.* -import kotlinx.coroutines.test.* +import kotlinx.coroutines.test.TestResult +import kotlinx.coroutines.test.runTest /** * Helper interface to test client. @@ -17,7 +16,6 @@ actual abstract class ClientLoader actual constructor(private val timeoutSeconds /** * Perform test against all clients from dependencies. */ - @OptIn(DelicateCoroutinesApi::class) actual fun clientTests( skipEngines: List, onlyWithEngine: String?, diff --git a/ktor-client/ktor-client-tests/js/test/io/ktor/client/tests/utils/NodeFetchOptionsTest.kt b/ktor-client/ktor-client-tests/js/test/io/ktor/client/tests/utils/NodeFetchOptionsTest.kt index b451b8094f5..560c0467050 100644 --- a/ktor-client/ktor-client-tests/js/test/io/ktor/client/tests/utils/NodeFetchOptionsTest.kt +++ b/ktor-client/ktor-client-tests/js/test/io/ktor/client/tests/utils/NodeFetchOptionsTest.kt @@ -1,19 +1,15 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils import io.ktor.client.* import io.ktor.client.call.* -import io.ktor.client.engine.* import io.ktor.client.engine.js.* import io.ktor.client.request.* -import io.ktor.client.statement.* import io.ktor.test.dispatcher.* import io.ktor.util.* -import kotlinx.coroutines.* import kotlin.test.* class NodeFetchOptionsTest { diff --git a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt index 124c7559a49..d3244e777cb 100644 --- a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt +++ b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt @@ -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) } } @@ -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 } @@ -92,8 +91,8 @@ actual abstract class ClientLoader actual constructor(val timeoutSeconds: Int) { * Issues to fix before unlock: * 1. Pinger & Ponger in ws * 2. Nonce generator + * Then @After should be added to the function */ - // @After @OptIn(ExperimentalCoroutinesApi::class) fun waitForAllCoroutines() { check(DebugProbes.isInstalled) { diff --git a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/FileCacheTest.kt b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/FileCacheTest.kt index 6dc60c1ddb5..f6a402abc48 100644 --- a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/FileCacheTest.kt +++ b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/FileCacheTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.client.tests import io.ktor.client.call.* diff --git a/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt b/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt index bac76c033d8..f1f7794a390 100644 --- a/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt +++ b/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils @@ -17,7 +16,6 @@ actual abstract class ClientLoader actual constructor(private val timeoutSeconds /** * Perform test against all clients from dependencies. */ - @OptIn(DelicateCoroutinesApi::class) actual fun clientTests( skipEngines: List, onlyWithEngine: String?, diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpConnect.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpConnect.kt index fc738081398..7c5a81f7735 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpConnect.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpConnect.kt @@ -14,13 +14,13 @@ import platform.winhttp.* @OptIn(ExperimentalForeignApi::class) internal typealias WinHttpStatusHandler = (statusInfo: LPVOID?, statusInfoLength: DWORD) -> Unit -internal class WinHttpConnect @OptIn(ExperimentalForeignApi::class) constructor( +@OptIn(ExperimentalForeignApi::class) +internal class WinHttpConnect( private val hConnect: COpaquePointer ) : Closeable { private val closed = atomic(false) - @OptIn(ExperimentalForeignApi::class) val handlers = mutableMapOf() val isClosed: Boolean diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt index c4318957f28..fef99f25189 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt @@ -9,29 +9,31 @@ import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.utils.io.core.* -import kotlinx.atomicfu.* +import kotlinx.atomicfu.atomic import kotlinx.cinterop.* -import platform.windows.* +import platform.windows.DWORDVar +import platform.windows.ERROR_INSUFFICIENT_BUFFER +import platform.windows.GetLastError import platform.windows.SECURITY_FLAG_IGNORE_CERT_CN_INVALID import platform.windows.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID import platform.windows.SECURITY_FLAG_IGNORE_UNKNOWN_CA import platform.winhttp.* -import kotlin.coroutines.* +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException @OptIn(ExperimentalForeignApi::class) -internal class WinHttpRequest @OptIn(ExperimentalForeignApi::class) constructor( +internal class WinHttpRequest( hSession: COpaquePointer, data: HttpRequestData, config: WinHttpClientEngineConfig ) : Closeable { private val connect: WinHttpConnect - @OptIn(ExperimentalForeignApi::class) private val hRequest: COpaquePointer private val closed = atomic(false) private val requestClosed = atomic(false) - @OptIn(ExperimentalForeignApi::class) private val connectReference: StableRef init { diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpSession.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpSession.kt index d6d6ec08cb5..43a3a4f34c0 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpSession.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpSession.kt @@ -9,14 +9,13 @@ import io.ktor.client.engine.winhttp.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.utils.io.core.* -import kotlinx.atomicfu.* +import kotlinx.atomicfu.atomic import kotlinx.cinterop.* import platform.winhttp.* @OptIn(ExperimentalForeignApi::class) internal class WinHttpSession(private val config: WinHttpClientEngineConfig) : Closeable { - @OptIn(ExperimentalForeignApi::class) private var hSession: COpaquePointer private val closed = atomic(false) private val timeoutConfigured = atomic(false) diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpWebSocket.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpWebSocket.kt index 1886b6d50fa..ed7021c291e 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpWebSocket.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpWebSocket.kt @@ -7,13 +7,18 @@ package io.ktor.client.engine.winhttp.internal import io.ktor.utils.io.core.* import io.ktor.utils.io.pool.* import io.ktor.websocket.* -import kotlinx.atomicfu.* +import kotlinx.atomicfu.atomic import kotlinx.cinterop.* -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.* -import platform.windows.* +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.ReceiveChannel +import kotlinx.coroutines.channels.SendChannel +import kotlinx.coroutines.launch +import platform.windows.NULL import platform.winhttp.* -import kotlin.coroutines.* +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException private object WinHttpWebSocketBuffer { val BinaryMessage = WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE @@ -24,7 +29,7 @@ private object WinHttpWebSocketBuffer { } @OptIn(ExperimentalForeignApi::class) -internal class WinHttpWebSocket @OptIn(ExperimentalForeignApi::class) constructor( +internal class WinHttpWebSocket( private val hWebSocket: COpaquePointer, private val connect: WinHttpConnect, callContext: CoroutineContext diff --git a/ktor-http/common/src/io/ktor/http/CacheControl.kt b/ktor-http/common/src/io/ktor/http/CacheControl.kt index b97062fa75e..42ad209273f 100644 --- a/ktor-http/common/src/io/ktor/http/CacheControl.kt +++ b/ktor-http/common/src/io/ktor/http/CacheControl.kt @@ -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 { diff --git a/ktor-http/common/src/io/ktor/http/Codecs.kt b/ktor-http/common/src/io/ktor/http/Codecs.kt index d06095e3636..9730c50b140 100644 --- a/ktor-http/common/src/io/ktor/http/Codecs.kt +++ b/ktor-http/common/src/io/ktor/http/Codecs.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.http import io.ktor.utils.io.charsets.* @@ -89,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 diff --git a/ktor-http/common/src/io/ktor/http/Parameters.kt b/ktor-http/common/src/io/ktor/http/Parameters.kt index 8e09f20d1a4..5107f9d1619 100644 --- a/ktor-http/common/src/io/ktor/http/Parameters.kt +++ b/ktor-http/common/src/io/ktor/http/Parameters.kt @@ -88,7 +88,10 @@ public operator fun Parameters.plus(other: Parameters): Parameters = when { caseInsensitiveName == other.caseInsensitiveName -> when { this.isEmpty() -> other other.isEmpty() -> this - else -> Parameters.build { appendAll(this@plus); appendAll(other) } + else -> Parameters.build { + appendAll(this@plus) + appendAll(other) + } } else -> { diff --git a/ktor-http/common/src/io/ktor/http/RangesSpecifier.kt b/ktor-http/common/src/io/ktor/http/RangesSpecifier.kt index 2d451900916..f4b04230586 100644 --- a/ktor-http/common/src/io/ktor/http/RangesSpecifier.kt +++ b/ktor-http/common/src/io/ktor/http/RangesSpecifier.kt @@ -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 diff --git a/ktor-http/common/src/io/ktor/http/URLBuilder.kt b/ktor-http/common/src/io/ktor/http/URLBuilder.kt index 8e73ed58c11..721c4c2671c 100644 --- a/ktor-http/common/src/io/ktor/http/URLBuilder.kt +++ b/ktor-http/common/src/io/ktor/http/URLBuilder.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.http @@ -44,7 +44,9 @@ public class URLBuilder( public var protocolOrNull: URLProtocol? = protocol public var protocol: URLProtocol get() = protocolOrNull ?: URLProtocol.HTTP - set(value) { protocolOrNull = value } + set(value) { + protocolOrNull = value + } public var encodedUser: String? = user?.encodeURLParameter() @@ -88,14 +90,13 @@ public class URLBuilder( /** * Build a URL string */ - // note: 256 should fit 99.5% of all urls according to http://www.supermind.org/blog/740/average-length-of-a-url-part-2 public fun buildString(): String { applyOrigin() - return appendTo(StringBuilder(256)).toString() + return appendTo(StringBuilder(INITIAL_CAPACITY)).toString() } override fun toString(): String { - return appendTo(StringBuilder(256)).toString() + return appendTo(StringBuilder(INITIAL_CAPACITY)).toString() } /** @@ -127,6 +128,12 @@ public class URLBuilder( // Required to write external extension function public companion object { private val originUrl = Url(origin) + + /** + * Initial capacity of StringBuilder. + * Note: 256 should fit 99.5% of all urls according to http://www.supermind.org/blog/740/average-length-of-a-url-part-2 + */ + private const val INITIAL_CAPACITY = 256 } } diff --git a/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt b/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt index 669b9c49ad1..59240ce4752 100644 --- a/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt +++ b/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.http @@ -14,7 +14,7 @@ class CodecTest { private val urlPath = "/wikipedia/commons/9/9c/University_of_Illinois_at_Urbana\u2013Champaign_logo.svg" private val surrogateSymbolUrlPath = "/path/🐕" - @Test /*(timeout = 1000L)*/ + @Test @Ignore fun testDecodeRandom() { val chars = "+%0123abc" diff --git a/ktor-http/common/test/io/ktor/tests/http/HttpStatusCodeTest.kt b/ktor-http/common/test/io/ktor/tests/http/HttpStatusCodeTest.kt index 46e047010a9..20c038baf35 100644 --- a/ktor-http/common/test/io/ktor/tests/http/HttpStatusCodeTest.kt +++ b/ktor-http/common/test/io/ktor/tests/http/HttpStatusCodeTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.http @@ -9,27 +9,27 @@ import kotlin.test.* class HttpStatusCodeTest { @Test - fun HttpStatusCodeAll() { + fun httpStatusCodeAll() { assertEquals(53, HttpStatusCode.allStatusCodes.size) } @Test - fun HttpStatusCodeFromValue() { + fun httpStatusCodeFromValue() { assertEquals(HttpStatusCode.NotFound, HttpStatusCode.fromValue(404)) } @Test - fun HttpStatusCodeConstructed() { + fun httpStatusCodeConstructed() { assertEquals(HttpStatusCode.NotFound, HttpStatusCode(404, "Not Found")) } @Test - fun HttpStatusCodeWithDescription() { + fun httpStatusCodeWithDescription() { assertEquals(HttpStatusCode.NotFound, HttpStatusCode.NotFound.description("Missing Resource")) } @Test - fun HttpStatusCodeToString() { + fun httpStatusCodeToString() { assertEquals("404 Not Found", HttpStatusCode.NotFound.toString()) } } diff --git a/ktor-http/jvm/src/io/ktor/http/content/BlockingBridge.kt b/ktor-http/jvm/src/io/ktor/http/content/BlockingBridge.kt index 72fff2e11c7..a72b46865ed 100644 --- a/ktor-http/jvm/src/io/ktor/http/content/BlockingBridge.kt +++ b/ktor-http/jvm/src/io/ktor/http/content/BlockingBridge.kt @@ -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 { @@ -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 } diff --git a/ktor-http/jvm/test/io/ktor/tests/http/URLBuilderTest.kt b/ktor-http/jvm/test/io/ktor/tests/http/URLBuilderTest.kt index 84744d3d8ba..41baf99221c 100644 --- a/ktor-http/jvm/test/io/ktor/tests/http/URLBuilderTest.kt +++ b/ktor-http/jvm/test/io/ktor/tests/http/URLBuilderTest.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.http diff --git a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt b/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt index 231b85cf487..cf773af077d 100644 --- a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt +++ b/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt @@ -166,7 +166,7 @@ public fun CoroutineScope.parseMultipart( private val CrLf = ByteString("\r\n".toByteArray()) -@OptIn(ExperimentalCoroutinesApi::class, InternalAPI::class) +@OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.parseMultipart( boundaryPrefixed: ByteString, input: ByteReadChannel, diff --git a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/HeadersJvmTest.kt b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/HeadersJvmTest.kt index feb6fda8a80..3381d42c37e 100644 --- a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/HeadersJvmTest.kt +++ b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/HeadersJvmTest.kt @@ -14,7 +14,6 @@ class HeadersJvmTest { private val ch = ByteChannel(true) private val builder = CharArrayBuilder() - @OptIn(InternalAPI::class) @AfterTest fun tearDown() { ch.close() diff --git a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt index a2d7ff24930..45f7a218091 100644 --- a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt +++ b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt @@ -25,7 +25,6 @@ class TrySkipDelimiterTest { assertTrue(ch.isClosedForRead) } - @OptIn(InternalAPI::class) @Test fun testSmokeWithOffsetShift(): Unit = runTest { ch.writeFully(byteArrayOf(9, 1, 2, 3)) @@ -38,7 +37,6 @@ class TrySkipDelimiterTest { assertTrue(ch.isClosedForRead) } - @OptIn(InternalAPI::class) @Test fun testEmpty(): Unit = runTest { ch.close() @@ -47,7 +45,6 @@ class TrySkipDelimiterTest { assertFalse(ch.skipDelimiterOrEof(delimiter)) } - @OptIn(InternalAPI::class) @Test fun testFull(): Unit = runTest { ch.writeFully(byteArrayOf(1, 2)) @@ -58,7 +55,6 @@ class TrySkipDelimiterTest { assertTrue(ch.isClosedForRead) } - @OptIn(InternalAPI::class) @Test fun testIncomplete(): Unit = runTest { ch.writeFully(byteArrayOf(1, 2)) @@ -70,7 +66,6 @@ class TrySkipDelimiterTest { } } - @OptIn(InternalAPI::class) @Test fun testOtherBytes(): Unit = runTest { ch.writeFully(byteArrayOf(7, 8)) diff --git a/ktor-io/androidNative/src/Charset.androidNative.kt b/ktor-io/androidNative/src/Charset.androidNative.kt index 6dea7dfa468..c345e25aa00 100644 --- a/ktor-io/androidNative/src/Charset.androidNative.kt +++ b/ktor-io/androidNative/src/Charset.androidNative.kt @@ -1,6 +1,7 @@ /* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* diff --git a/ktor-io/common/src/io/ktor/utils/io/core/ByteOrder.kt b/ktor-io/common/src/io/ktor/utils/io/core/ByteOrder.kt index f569ae262fd..4d5f749681d 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/ByteOrder.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/ByteOrder.kt @@ -5,7 +5,8 @@ package io.ktor.utils.io.core public expect enum class ByteOrder { - BIG_ENDIAN, LITTLE_ENDIAN; + BIG_ENDIAN, + LITTLE_ENDIAN; public companion object { public fun nativeOrder(): ByteOrder diff --git a/ktor-io/common/src/io/ktor/utils/io/core/BytePacketBuilder.kt b/ktor-io/common/src/io/ktor/utils/io/core/BytePacketBuilder.kt index b7210eb90e8..ea4e3d4e428 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/BytePacketBuilder.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/BytePacketBuilder.kt @@ -18,6 +18,7 @@ public typealias BytePacketBuilder = Sink @OptIn(InternalIoApi::class) public val Sink.size: Int get() = buffer.size.toInt() +@Suppress("FunctionName") public fun BytePacketBuilder(): Sink = kotlinx.io.Buffer() public fun Sink.append(value: CharSequence, startIndex: Int = 0, endIndex: Int = value.length) { diff --git a/ktor-io/js/src/io/ktor/utils/io/charsets/Charset.js.kt b/ktor-io/js/src/io/ktor/utils/io/charsets/Charset.js.kt index 08d371ef44f..12f67774c8f 100644 --- a/ktor-io/js/src/io/ktor/utils/io/charsets/Charset.js.kt +++ b/ktor-io/js/src/io/ktor/utils/io/charsets/Charset.js.kt @@ -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. @@ -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 } @@ -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 } diff --git a/ktor-io/js/src/io/ktor/utils/io/core/ByteOrderJS.kt b/ktor-io/js/src/io/ktor/utils/io/core/ByteOrderJS.kt index 8e201eedd13..016ba35a60f 100644 --- a/ktor-io/js/src/io/ktor/utils/io/core/ByteOrderJS.kt +++ b/ktor-io/js/src/io/ktor/utils/io/core/ByteOrderJS.kt @@ -2,13 +2,13 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.utils.io.core import org.khronos.webgl.* public actual enum class ByteOrder { - BIG_ENDIAN, LITTLE_ENDIAN; + BIG_ENDIAN, + LITTLE_ENDIAN; public actual companion object { private val native: ByteOrder diff --git a/ktor-io/linux/src/CharsetLinux.kt b/ktor-io/linux/src/CharsetLinux.kt index 083389a066c..075b2faa4fa 100644 --- a/ktor-io/linux/src/CharsetLinux.kt +++ b/ktor-io/linux/src/CharsetLinux.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* @@ -155,7 +156,6 @@ public actual fun CharsetDecoder.decode(input: Source, dst: Appendable, max: Int } } -@OptIn(ExperimentalForeignApi::class) internal actual fun CharsetEncoder.encodeToByteArrayImpl( input: CharSequence, fromIndex: Int, diff --git a/ktor-io/mingwX64/src/CharsetMingw.kt b/ktor-io/mingwX64/src/CharsetMingw.kt index 000554af04e..471d4bf09d0 100644 --- a/ktor-io/mingwX64/src/CharsetMingw.kt +++ b/ktor-io/mingwX64/src/CharsetMingw.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* @@ -155,7 +156,6 @@ public actual fun CharsetDecoder.decode(input: Source, dst: Appendable, max: Int } } -@OptIn(ExperimentalForeignApi::class) internal actual fun CharsetEncoder.encodeToByteArrayImpl( input: CharSequence, fromIndex: Int, diff --git a/ktor-io/posix/src/io/ktor/utils/io/core/ByteOrderNative.kt b/ktor-io/posix/src/io/ktor/utils/io/core/ByteOrderNative.kt index 15d5bf70511..56a23ed58a5 100644 --- a/ktor-io/posix/src/io/ktor/utils/io/core/ByteOrderNative.kt +++ b/ktor-io/posix/src/io/ktor/utils/io/core/ByteOrderNative.kt @@ -2,13 +2,13 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.utils.io.core import kotlin.experimental.* public actual enum class ByteOrder { - BIG_ENDIAN, LITTLE_ENDIAN; + BIG_ENDIAN, + LITTLE_ENDIAN; public actual companion object { @OptIn(ExperimentalNativeApi::class) diff --git a/ktor-io/posix/src/io/ktor/utils/io/locks/Synchronized.kt b/ktor-io/posix/src/io/ktor/utils/io/locks/Synchronized.kt index 023197000fe..a0c7850fe07 100644 --- a/ktor-io/posix/src/io/ktor/utils/io/locks/Synchronized.kt +++ b/ktor-io/posix/src/io/ktor/utils/io/locks/Synchronized.kt @@ -148,8 +148,9 @@ public actual open class SynchronizedObject { val currentThreadId = pthread_self() while (true) { val state = lock.value + @Suppress("ktlint:standard:max-line-length") require(currentThreadId == state.ownerThreadId) { - "Thin lock may be only released by the owner thread, expected: ${state.ownerThreadId}, real: $currentThreadId" // ktlint-disable max-line-length + "Thin lock may be only released by the owner thread, expected: ${state.ownerThreadId}, real: $currentThreadId" } when (state.status) { Status.THIN -> { diff --git a/ktor-io/wasmJs/src/io/ktor/utils/io/core/ByteOrder.wasmJs.kt b/ktor-io/wasmJs/src/io/ktor/utils/io/core/ByteOrder.wasmJs.kt index 091922de291..016ba35a60f 100644 --- a/ktor-io/wasmJs/src/io/ktor/utils/io/core/ByteOrder.wasmJs.kt +++ b/ktor-io/wasmJs/src/io/ktor/utils/io/core/ByteOrder.wasmJs.kt @@ -7,7 +7,8 @@ package io.ktor.utils.io.core import org.khronos.webgl.* public actual enum class ByteOrder { - BIG_ENDIAN, LITTLE_ENDIAN; + BIG_ENDIAN, + LITTLE_ENDIAN; public actual companion object { private val native: ByteOrder diff --git a/ktor-network/androidNative/src/io/ktor/network/util/SocketUtils.androidNative.kt b/ktor-network/androidNative/src/io/ktor/network/util/SocketUtils.androidNative.kt index 5fc38c42575..d9afe21a9ee 100644 --- a/ktor-network/androidNative/src/io/ktor/network/util/SocketUtils.androidNative.kt +++ b/ktor-network/androidNative/src/io/ktor/network/util/SocketUtils.androidNative.kt @@ -2,6 +2,8 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import io.ktor.network.interop.* diff --git a/ktor-network/androidNative32/src/SocketUtils.androidNative32.kt b/ktor-network/androidNative32/src/SocketUtils.androidNative32.kt index a513f2508b7..b78117d4237 100644 --- a/ktor-network/androidNative32/src/SocketUtils.androidNative32.kt +++ b/ktor-network/androidNative32/src/SocketUtils.androidNative32.kt @@ -2,13 +2,14 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* -import kotlinx.cinterop.ByteVar import platform.posix.* -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun ktor_recvfrom( __fd: Int, __buf: CValuesRef?, diff --git a/ktor-network/androidNative64/src/SocketUtils.androidNative64.kt b/ktor-network/androidNative64/src/SocketUtils.androidNative64.kt index 3bb52983ee4..eb229ebb639 100644 --- a/ktor-network/androidNative64/src/SocketUtils.androidNative64.kt +++ b/ktor-network/androidNative64/src/SocketUtils.androidNative64.kt @@ -2,14 +2,14 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* -import kotlinx.cinterop.ByteVar -import kotlinx.cinterop.convert import platform.posix.* -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun ktor_recvfrom( __fd: Int, __buf: CValuesRef?, diff --git a/ktor-network/darwin/src/io/ktor/network/util/SocketUtils.darwin.kt b/ktor-network/darwin/src/io/ktor/network/util/SocketUtils.darwin.kt index 84fafce9473..ecae8d694fe 100644 --- a/ktor-network/darwin/src/io/ktor/network/util/SocketUtils.darwin.kt +++ b/ktor-network/darwin/src/io/ktor/network/util/SocketUtils.darwin.kt @@ -1,6 +1,9 @@ /* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/ios/src/io/ktor/network/util/SocketUtilsIos.kt b/ktor-network/ios/src/io/ktor/network/util/SocketUtilsIos.kt index 56192cd3cb5..5a6a1e3caa3 100644 --- a/ktor-network/ios/src/io/ktor/network/util/SocketUtilsIos.kt +++ b/ktor-network/ios/src/io/ktor/network/util/SocketUtilsIos.kt @@ -1,6 +1,9 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/jvm/src/io/ktor/network/selector/JvmSelector.kt b/ktor-network/jvm/src/io/ktor/network/selector/JvmSelector.kt index 17f88b51970..9b9723de242 100644 --- a/ktor-network/jvm/src/io/ktor/network/selector/JvmSelector.kt +++ b/ktor-network/jvm/src/io/ktor/network/selector/JvmSelector.kt @@ -1,4 +1,7 @@ -// ktlint-disable filename +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.network.selector import kotlinx.coroutines.* diff --git a/ktor-network/jvm/src/io/ktor/network/selector/LockFreeMPSCQueue.kt b/ktor-network/jvm/src/io/ktor/network/selector/LockFreeMPSCQueue.kt index 56c6638738d..0d1e6093664 100644 --- a/ktor-network/jvm/src/io/ktor/network/selector/LockFreeMPSCQueue.kt +++ b/ktor-network/jvm/src/io/ktor/network/selector/LockFreeMPSCQueue.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.network.selector import kotlinx.atomicfu.* @@ -20,34 +21,34 @@ private typealias Core = LockFreeMPSCQueueCore * ``` */ internal class LockFreeMPSCQueue { - private val _cur = atomic(Core(Core.INITIAL_CAPACITY)) + private val curRef = atomic(Core(Core.INITIAL_CAPACITY)) // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) - val isEmpty: Boolean get() = _cur.value.isEmpty + val isEmpty: Boolean get() = curRef.value.isEmpty fun close() { - _cur.loop { cur -> + curRef.loop { cur -> if (cur.close()) return // closed this copy - _cur.compareAndSet(cur, cur.next()) // move to next + curRef.compareAndSet(cur, cur.next()) // move to next } } fun addLast(element: E): Boolean { - _cur.loop { cur -> + curRef.loop { cur -> when (cur.addLast(element)) { Core.ADD_SUCCESS -> return true Core.ADD_CLOSED -> return false - Core.ADD_FROZEN -> _cur.compareAndSet(cur, cur.next()) // move to next + Core.ADD_FROZEN -> curRef.compareAndSet(cur, cur.next()) // move to next } } } @Suppress("UNCHECKED_CAST") fun removeFirstOrNull(): E? { - _cur.loop { cur -> + curRef.loop { cur -> val result = cur.removeFirstOrNull() if (result !== Core.REMOVE_FROZEN) return result as E? - _cur.compareAndSet(cur, cur.next()) + curRef.compareAndSet(cur, cur.next()) } } } @@ -60,8 +61,8 @@ internal class LockFreeMPSCQueue { */ private class LockFreeMPSCQueueCore(private val capacity: Int) { private val mask = capacity - 1 - private val _next = atomic?>(null) - private val _state = atomic(0L) + private val nextRef = atomic?>(null) + private val stateRef = atomic(0L) private val array = AtomicReferenceArray(capacity) init { @@ -70,10 +71,10 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { } // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) - val isEmpty: Boolean get() = _state.value.withState { head, tail -> head == tail } + val isEmpty: Boolean get() = stateRef.value.withState { head, tail -> head == tail } fun close(): Boolean { - _state.update { state -> + stateRef.update { state -> if (state and CLOSED_MASK != 0L) return true // ok - already closed if (state and FROZEN_MASK != 0L) return false // frozen -- try next state or CLOSED_MASK // try set closed bit @@ -83,20 +84,20 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { // ADD_CLOSED | ADD_FROZEN | ADD_SUCCESS fun addLast(element: E): Int { - _state.loop { state -> + stateRef.loop { state -> if (state and (FROZEN_MASK or CLOSED_MASK) != 0L) return state.addFailReason() // cannot add state.withState { head, tail -> // there could be one REMOVE element beyond head that we cannot stump up, // so we check for full queue with an extra margin of one element if ((tail + 2) and mask == head and mask) return ADD_FROZEN // overfull, so do freeze & copy val newTail = (tail + 1) and MAX_CAPACITY_MASK - if (_state.compareAndSet(state, state.updateTail(newTail))) { + if (stateRef.compareAndSet(state, state.updateTail(newTail))) { // successfully added array[tail and mask] = element // could have been frozen & copied before this item was set -- correct it by filling placeholder var cur = this while (true) { - if (cur._state.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet + if (cur.stateRef.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet cur = cur.next().fillPlaceholder(tail, element) ?: break } return ADD_SUCCESS // added successfully @@ -129,7 +130,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { // SINGLE CONSUMER // REMOVE_FROZEN | null (EMPTY) | E (SUCCESS) fun removeFirstOrNull(): Any? { - _state.loop { state -> + stateRef.loop { state -> if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify state.withState { head, tail -> if ((tail and mask) == (head and mask)) return null // empty @@ -138,7 +139,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { if (element is Placeholder) return null // same story -- consider it not added yet // we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster val newHead = (head + 1) and MAX_CAPACITY_MASK - if (_state.compareAndSet(state, state.updateHead(newHead))) { + if (stateRef.compareAndSet(state, state.updateHead(newHead))) { array[head and mask] = null // now can safely put null (state was updated) return element // successfully removed in fast-path } @@ -153,14 +154,14 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { } private fun removeSlowPath(oldHead: Int, newHead: Int): Core? { - _state.loop { state -> + stateRef.loop { state -> state.withState { head, _ -> check(head == oldHead) { "This queue can have only one consumer" } if (state and FROZEN_MASK != 0L) { // state was already frozen, so removed element was copied to next return next() // continue to correct head in next } - if (_state.compareAndSet(state, state.updateHead(newHead))) { + if (stateRef.compareAndSet(state, state.updateHead(newHead))) { array[head and mask] = null // now can safely put null (state was updated) return null } @@ -171,15 +172,15 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { fun next(): LockFreeMPSCQueueCore = allocateOrGetNextCopy(markFrozen()) private fun markFrozen(): Long = - _state.updateAndGet { state -> + stateRef.updateAndGet { state -> if (state and FROZEN_MASK != 0L) return state // already marked state or FROZEN_MASK } private fun allocateOrGetNextCopy(state: Long): Core { - _next.loop { next -> + nextRef.loop { next -> if (next != null) return next // already allocated & copied - _next.compareAndSet(null, allocateNextCopy(state)) + nextRef.compareAndSet(null, allocateNextCopy(state)) } } @@ -192,7 +193,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { next.array[index and next.mask] = array[index and mask] ?: Placeholder(index) index++ } - next._state.value = state wo FROZEN_MASK + next.stateRef.value = state wo FROZEN_MASK } return next } diff --git a/ktor-network/jvm/src/io/ktor/network/selector/SelectableJvm.kt b/ktor-network/jvm/src/io/ktor/network/selector/SelectableJvm.kt index 6a43975defc..b76375228a9 100644 --- a/ktor-network/jvm/src/io/ktor/network/selector/SelectableJvm.kt +++ b/ktor-network/jvm/src/io/ktor/network/selector/SelectableJvm.kt @@ -1,4 +1,7 @@ -// ktlint-disable filename +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.network.selector import kotlinx.atomicfu.* diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/CIOReader.kt b/ktor-network/jvm/src/io/ktor/network/sockets/CIOReader.kt index 2a422544ad3..5868aeba1db 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/CIOReader.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/CIOReader.kt @@ -73,7 +73,6 @@ internal fun CoroutineScope.attachForReadingImpl( } } -@OptIn(InternalAPI::class) internal fun CoroutineScope.attachForReadingDirectImpl( channel: ByteChannel, nioChannel: ReadableByteChannel, diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/NIOSocketImpl.kt b/ktor-network/jvm/src/io/ktor/network/sockets/NIOSocketImpl.kt index 78f5152c306..9a2edbbc10c 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/NIOSocketImpl.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/NIOSocketImpl.kt @@ -139,7 +139,6 @@ internal abstract class NIOSocketImpl( private val AtomicReference.completedOrNotStarted: Boolean get() = get().let { it == null || it.isCompleted } - @OptIn(InternalCoroutinesApi::class) private val AtomicReference.exception: Throwable? get() = get()?.takeIf { it.isCancelled } ?.getCancellationException()?.cause // TODO it should be completable deferred or provide its own exception diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/SocketAddressJvm.kt b/ktor-network/jvm/src/io/ktor/network/sockets/SocketAddressJvm.kt index ae11b7bbf72..e7dd82ab464 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/SocketAddressJvm.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/SocketAddressJvm.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets @@ -56,7 +56,8 @@ public actual class InetSocketAddress internal constructor( } public actual class UnixSocketAddress internal constructor( - override val address: java.net.SocketAddress // actually: java.net.UnixDomainSocketAddress + // actually: java.net.UnixDomainSocketAddress + override val address: java.net.SocketAddress ) : SocketAddress() { init { diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/SocketOptionsPlatformCapabilities.kt b/ktor-network/jvm/src/io/ktor/network/sockets/SocketOptionsPlatformCapabilities.kt index fb6b6636be1..add1d239043 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/SocketOptionsPlatformCapabilities.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/SocketOptionsPlatformCapabilities.kt @@ -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" @@ -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 && @@ -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 && diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt b/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt index beb54cbb3ac..fd4984bda25 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt +++ b/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt @@ -43,7 +43,10 @@ public expect interface SelectorManager : CoroutineScope, Closeable { * Select interest kind. */ public expect enum class SelectInterest { - READ, WRITE, ACCEPT, CONNECT; + READ, + WRITE, + ACCEPT, + CONNECT; public companion object { public val AllInterests: Array diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt b/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt index bc80354e9b0..81c4a1306c1 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt +++ b/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt @@ -1,6 +1,7 @@ /* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.network.sockets import io.ktor.network.selector.* diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt b/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt index 539536086da..786882795bd 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt +++ b/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt @@ -9,7 +9,6 @@ internal const val INFINITE_TIMEOUT_MS = Long.MAX_VALUE /** * Socket options builder */ -@OptIn(ExperimentalUnsignedTypes::class) public sealed class SocketOptions( protected val customOptions: MutableMap ) { diff --git a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Hashes.kt b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Hashes.kt index 570edb438b4..e02853b133a 100644 --- a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Hashes.kt +++ b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Hashes.kt @@ -1,7 +1,9 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.tls import javax.crypto.* diff --git a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt index a10fe5caf7b..ce5a63d79c7 100644 --- a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt +++ b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt @@ -388,9 +388,10 @@ internal class TLSClientHandshake( if (hasHashAndSignInCommon) return@find false - info.authorities.isEmpty() || candidate.certificateChain - .map { X500Principal(it.issuerX500Principal.name) } - .any { it in info.authorities } + info.authorities.isEmpty() || + candidate.certificateChain + .map { X500Principal(it.issuerX500Principal.name) } + .any { it in info.authorities } } sendHandshakeRecord(TLSHandshakeType.Certificate) { diff --git a/ktor-network/ktor-network-tls/jvm/test/io/ktor/network/tls/ConnectionTest.kt b/ktor-network/ktor-network-tls/jvm/test/io/ktor/network/tls/ConnectionTest.kt index fd355b493f5..3cccdecd431 100644 --- a/ktor-network/ktor-network-tls/jvm/test/io/ktor/network/tls/ConnectionTest.kt +++ b/ktor-network/ktor-network-tls/jvm/test/io/ktor/network/tls/ConnectionTest.kt @@ -2,7 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable experimental:argument-list-wrapping package io.ktor.network.tls import io.ktor.junit.coroutines.* diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt b/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt index d1a700860fe..d170233d516 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt +++ b/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls.extensions @@ -8,16 +8,13 @@ import io.ktor.network.tls.* import io.ktor.utils.io.core.* import kotlinx.io.* -/** - * See also: [https://www.iana.org/assignments/tls-parameters/tls-parameters.txt] - */ +// See also: https://www.iana.org/assignments/tls-parameters/tls-parameters.txt /** * Hash algorithms * @property code numeric hash algorithm code * @property openSSLName is a name used in openssl for this algorithm */ - public enum class HashAlgorithm(public val code: Byte, public val openSSLName: String, public val macName: String) { NONE(0, "", ""), MD5(1, "MD5", "HmacMD5"), @@ -43,7 +40,6 @@ public enum class HashAlgorithm(public val code: Byte, public val openSSLName: S * Signature algorithms * @property code numeric algorithm codes */ - public enum class SignatureAlgorithm(public val code: Byte) { ANON(0), RSA(1), @@ -69,7 +65,6 @@ public enum class SignatureAlgorithm(public val code: Byte) { * @property sign algorithm. * @property oid [object identifier](https://en.wikipedia.org/wiki/Object_identifier). */ - public data class HashAndSign(val hash: HashAlgorithm, val sign: SignatureAlgorithm, val oid: OID? = null) { /** * String representation of this algorithms pair @@ -79,7 +74,7 @@ public data class HashAndSign(val hash: HashAlgorithm, val sign: SignatureAlgori public companion object } -@Suppress("CONFLICTING_OVERLOADS") +@Suppress("CONFLICTING_OVERLOADS", "ktlint:standard:function-naming") internal fun HashAndSign(hashValue: Byte, signValue: Byte, oidValue: String? = null): HashAndSign? { val hash = HashAlgorithm.byCode(hashValue) val sign = SignatureAlgorithm.byCode(signValue) ?: return null @@ -91,7 +86,6 @@ internal fun HashAndSign(hashValue: Byte, signValue: Byte, oidValue: String? = n /** * List of supported combinations of hash and signature algorithms */ - public val SupportedSignatureAlgorithms: List = listOf( HashAndSign(HashAlgorithm.SHA384, SignatureAlgorithm.ECDSA, OID.ECDSAwithSHA384Encryption), HashAndSign(HashAlgorithm.SHA256, SignatureAlgorithm.ECDSA, OID.ECDSAwithSHA256Encryption), diff --git a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt index 08d306311be..5dbca80f59a 100644 --- a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt +++ b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls.certificates @@ -8,8 +8,6 @@ import io.ktor.network.tls.* import io.ktor.network.tls.extensions.* import io.ktor.utils.io.core.* import kotlinx.io.* -import kotlinx.io.Sink -import kotlinx.io.writeUByte import java.io.* import java.math.* import java.net.* @@ -115,7 +113,9 @@ internal fun generateX509Certificate( } public enum class KeyType { - CA, Server, Client + CA, + Server, + Client, } /** diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt b/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt index f3bf682429c..3b7954fd388 100644 --- a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt +++ b/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls diff --git a/ktor-network/linux/src/io/ktor/network/util/SocketUtils.linux.kt b/ktor-network/linux/src/io/ktor/network/util/SocketUtils.linux.kt index 4830261db76..32542e5571b 100644 --- a/ktor-network/linux/src/io/ktor/network/util/SocketUtils.linux.kt +++ b/ktor-network/linux/src/io/ktor/network/util/SocketUtils.linux.kt @@ -2,10 +2,13 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* -import platform.linux.* +import platform.linux.inet_ntop +import platform.linux.sockaddr_un import platform.posix.* @OptIn(ExperimentalForeignApi::class) @@ -39,7 +42,7 @@ internal actual fun pack_sockaddr_un( } } -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun ktor_recvfrom( __fd: Int, __buf: CValuesRef?, diff --git a/ktor-network/macos/src/io/ktor/network/util/SocketUtilsMacos.kt b/ktor-network/macos/src/io/ktor/network/util/SocketUtilsMacos.kt index a3c439ee97d..2e1004d6730 100644 --- a/ktor-network/macos/src/io/ktor/network/util/SocketUtilsMacos.kt +++ b/ktor-network/macos/src/io/ktor/network/util/SocketUtilsMacos.kt @@ -1,6 +1,9 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/nix/src/io/ktor/network/selector/SelectUtilsNix.kt b/ktor-network/nix/src/io/ktor/network/selector/SelectUtilsNix.kt index 0b4874a47f1..6c4bafa3293 100644 --- a/ktor-network/nix/src/io/ktor/network/selector/SelectUtilsNix.kt +++ b/ktor-network/nix/src/io/ktor/network/selector/SelectUtilsNix.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.network.selector import io.ktor.network.interop.* diff --git a/ktor-network/nix/src/io/ktor/network/util/SocketUtils.nix.kt b/ktor-network/nix/src/io/ktor/network/util/SocketUtils.nix.kt index fbce018be44..4730c749b7c 100644 --- a/ktor-network/nix/src/io/ktor/network/util/SocketUtils.nix.kt +++ b/ktor-network/nix/src/io/ktor/network/util/SocketUtils.nix.kt @@ -2,6 +2,8 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/posix/src/io/ktor/network/selector/SelectUtils.kt b/ktor-network/posix/src/io/ktor/network/selector/SelectUtils.kt index 6cc52efe37e..65961afcdf3 100644 --- a/ktor-network/posix/src/io/ktor/network/selector/SelectUtils.kt +++ b/ktor-network/posix/src/io/ktor/network/selector/SelectUtils.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.network.selector import kotlinx.coroutines.* diff --git a/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt b/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt index 55746637530..55b1ed24050 100644 --- a/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt +++ b/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.selector @@ -40,7 +40,10 @@ public actual interface SelectorManager : CoroutineScope, Closeable { */ @Suppress("KDocMissingDocumentation", "NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING") public actual enum class SelectInterest { - READ, WRITE, ACCEPT, CONNECT; + READ, + WRITE, + ACCEPT, + CONNECT; public actual companion object { public actual val AllInterests: Array diff --git a/ktor-network/posix/src/io/ktor/network/selector/WorkerSelectorManager.kt b/ktor-network/posix/src/io/ktor/network/selector/WorkerSelectorManager.kt index fe7c2cf4360..7f36cbac0e2 100644 --- a/ktor-network/posix/src/io/ktor/network/selector/WorkerSelectorManager.kt +++ b/ktor-network/posix/src/io/ktor/network/selector/WorkerSelectorManager.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.network.selector import kotlinx.coroutines.* diff --git a/ktor-network/posix/src/io/ktor/network/sockets/CIOReader.kt b/ktor-network/posix/src/io/ktor/network/sockets/CIOReader.kt index a1f7bf8fc0d..1a2d4611a92 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/CIOReader.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/CIOReader.kt @@ -12,7 +12,7 @@ import kotlinx.cinterop.* import kotlinx.coroutines.* import kotlinx.io.IOException -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal fun CoroutineScope.attachForReadingImpl( userChannel: ByteChannel, descriptor: Int, diff --git a/ktor-network/posix/src/io/ktor/network/sockets/CIOWriter.kt b/ktor-network/posix/src/io/ktor/network/sockets/CIOWriter.kt index 1f6c3cc1b8a..8ba0b224924 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/CIOWriter.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/CIOWriter.kt @@ -13,7 +13,7 @@ import kotlinx.coroutines.* import kotlinx.io.IOException import kotlin.math.* -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal fun CoroutineScope.attachForWritingImpl( userChannel: ByteChannel, descriptor: Int, diff --git a/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt index ec9c0f4e3bb..3b8613cb2cf 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt @@ -13,7 +13,7 @@ import platform.posix.* private const val DEFAULT_BACKLOG_SIZE = 50 -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual suspend fun connect( selector: SelectorManager, remoteAddress: SocketAddress, @@ -78,7 +78,7 @@ internal actual suspend fun connect( throw IOException("Failed to connect to $remoteAddress.", lastException) } -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun bind( selector: SelectorManager, localAddress: SocketAddress?, diff --git a/ktor-network/posix/src/io/ktor/network/sockets/DatagramSocketNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/DatagramSocketNative.kt index 77dd5379cbb..bc243e99d32 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/DatagramSocketNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/DatagramSocketNative.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets @@ -23,12 +23,12 @@ internal class DatagramSocketNative( private val remote: SocketAddress?, parent: CoroutineContext = EmptyCoroutineContext ) : BoundDatagramSocket, ConnectedDatagramSocket, CoroutineScope { - private val _context: CompletableJob = Job(parent[Job]) + private val context: CompletableJob = Job(parent[Job]) - override val coroutineContext: CoroutineContext = parent + Dispatchers.Unconfined + _context + override val coroutineContext: CoroutineContext = parent + Dispatchers.Unconfined + context override val socketContext: Job - get() = _context + get() = context override val localAddress: SocketAddress get() = getLocalAddress(descriptor).toSocketAddress() @@ -61,8 +61,8 @@ internal class DatagramSocketNative( override fun close() { receiver.cancel() - _context.complete() - _context.invokeOnCompletion { + context.complete() + context.invokeOnCompletion { ktor_shutdown(descriptor, ShutdownCommands.Both) // Descriptor is closed by the selector manager selector.notifyClosed(selectable) @@ -78,7 +78,7 @@ internal class DatagramSocketNative( } } - @OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) + @OptIn(ExperimentalForeignApi::class) private fun tryReadDatagram(): Datagram? = memScoped { val clientAddress = alloc() val clientAddressLength: UIntVarOf = alloc() diff --git a/ktor-network/posix/src/io/ktor/network/sockets/TCPSocketNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/TCPSocketNative.kt index f4bad145d32..50895a2a291 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/TCPSocketNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/TCPSocketNative.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets @@ -18,12 +18,12 @@ internal class TCPSocketNative( override val localAddress: SocketAddress, parent: CoroutineContext = EmptyCoroutineContext ) : Socket, CoroutineScope { - private val _context: CompletableJob = Job(parent[Job]) + private val context: CompletableJob = Job(parent[Job]) - override val coroutineContext: CoroutineContext = parent + Dispatchers.Unconfined + _context + override val coroutineContext: CoroutineContext = parent + Dispatchers.Unconfined + context override val socketContext: Job - get() = _context + get() = context override fun attachForReading(channel: ByteChannel): WriterJob = attachForReadingImpl(channel, descriptor, selectable, selector) @@ -32,8 +32,8 @@ internal class TCPSocketNative( attachForWritingImpl(channel, descriptor, selectable, selector) override fun close() { - _context.complete() - _context.invokeOnCompletion { + context.complete() + context.invokeOnCompletion { ktor_shutdown(descriptor, ShutdownCommands.Both) // Descriptor is closed by the selector manager selector.notifyClosed(selectable) diff --git a/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt index eb4fd26ec59..d483f258015 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt @@ -9,7 +9,7 @@ import io.ktor.network.util.* import kotlinx.cinterop.* import platform.posix.* -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun connectUDP( selector: SelectorManager, remoteAddress: SocketAddress, @@ -50,7 +50,7 @@ internal actual fun connectUDP( } } -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal actual fun bindUDP( selector: SelectorManager, localAddress: SocketAddress?, diff --git a/ktor-network/posix/src/io/ktor/network/util/SocketAddressUtils.kt b/ktor-network/posix/src/io/ktor/network/util/SocketAddressUtils.kt index 28865d12f7b..f6691205ee5 100644 --- a/ktor-network/posix/src/io/ktor/network/util/SocketAddressUtils.kt +++ b/ktor-network/posix/src/io/ktor/network/util/SocketAddressUtils.kt @@ -5,15 +5,16 @@ package io.ktor.network.util import io.ktor.network.sockets.* -import kotlinx.cinterop.* -import platform.posix.* +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.convert +import platform.posix.AF_UNIX internal val SocketAddress.address: NativeSocketAddress get() { val explicitAddress = resolve().firstOrNull() return explicitAddress ?: error("Failed to resolve address for $this") } -@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class) internal fun SocketAddress.resolve(): List = when (this) { is InetSocketAddress -> getAddressInfo(hostname, port) is UnixSocketAddress -> listOf(NativeUnixSocketAddress(AF_UNIX.convert(), path)) diff --git a/ktor-network/posix/src/io/ktor/network/util/SocketUtils.kt b/ktor-network/posix/src/io/ktor/network/util/SocketUtils.kt index afe694a670b..b62ac1c2b99 100644 --- a/ktor-network/posix/src/io/ktor/network/util/SocketUtils.kt +++ b/ktor-network/posix/src/io/ktor/network/util/SocketUtils.kt @@ -1,7 +1,9 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import io.ktor.utils.io.bits.* diff --git a/ktor-network/tvos/src/io/ktor/network/util/SocketUtilsTvos.kt b/ktor-network/tvos/src/io/ktor/network/util/SocketUtilsTvos.kt index 33725ad7923..1290cf499eb 100644 --- a/ktor-network/tvos/src/io/ktor/network/util/SocketUtilsTvos.kt +++ b/ktor-network/tvos/src/io/ktor/network/util/SocketUtilsTvos.kt @@ -1,6 +1,9 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/watchos/src/io/ktor/network/util/SocketUtilsWatchos.kt b/ktor-network/watchos/src/io/ktor/network/util/SocketUtilsWatchos.kt index 97f84b0a1a8..73925d11c41 100644 --- a/ktor-network/watchos/src/io/ktor/network/util/SocketUtilsWatchos.kt +++ b/ktor-network/watchos/src/io/ktor/network/util/SocketUtilsWatchos.kt @@ -1,6 +1,9 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-network/windows/src/io/ktor/network/util/SocketUtilsWindows.kt b/ktor-network/windows/src/io/ktor/network/util/SocketUtilsWindows.kt index 01babff7ac9..df65f333fbd 100644 --- a/ktor-network/windows/src/io/ktor/network/util/SocketUtilsWindows.kt +++ b/ktor-network/windows/src/io/ktor/network/util/SocketUtilsWindows.kt @@ -2,6 +2,8 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("FunctionName") + package io.ktor.network.util import kotlinx.cinterop.* diff --git a/ktor-server/common/src/Stub.kt b/ktor-server/common/src/Stub.kt index 1525c247cbe..d0706de3a1a 100644 --- a/ktor-server/common/src/Stub.kt +++ b/ktor-server/common/src/Stub.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server internal fun stub() { diff --git a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt index 925c6e7cfac..e8d7b991d39 100644 --- a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt +++ b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.cio @@ -38,7 +38,10 @@ class IntegrationTest { s.invokeOnCompletion { t -> if (t != null) { server.completeExceptionally(t) - } else server.complete(@OptIn(ExperimentalCoroutinesApi::class) s.getCompleted()) + } else { + @OptIn(ExperimentalCoroutinesApi::class) + server.complete(s.getCompleted()) + } } j.invokeOnCompletion { diff --git a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/ServerPipelineTest.kt b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/ServerPipelineTest.kt index acada941772..12dc6cfe489 100644 --- a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/ServerPipelineTest.kt +++ b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/ServerPipelineTest.kt @@ -25,7 +25,6 @@ import kotlin.time.Duration.Companion.milliseconds @OptIn(InternalAPI::class) class ServerPipelineTest : CoroutineScope { - @OptIn(ExperimentalCoroutinesApi::class) private val dispatcher = Dispatchers.IO.limitedParallelism(8) private val job: CompletableJob = SupervisorJob() diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt b/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt index 678d9dabd11..b5e3a23375c 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt +++ b/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.cio.backend @@ -12,11 +12,10 @@ import io.ktor.util.cio.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* -import io.ktor.utils.io.errors.* import kotlinx.coroutines.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.* -import kotlinx.io.IOException +import kotlinx.io.* import kotlin.time.* /** @@ -64,7 +63,8 @@ public fun CoroutineScope.startServerConnectionPipeline( throw io } catch (cancelled: CancellationException) { throw cancelled - } catch (parseFailed: Throwable) { // try to write 400 Bad Request + } catch (parseFailed: Throwable) { + // try to write 400 Bad Request respondBadRequest(actorChannel) break // end pipeline loop } @@ -176,14 +176,14 @@ public fun CoroutineScope.startServerConnectionPipeline( if (isLastHttpRequest(version, connectionOptions)) break } - } catch (cause: IOException) { // already handled + } catch (cause: IOException) { + // already handled coroutineContext.cancel() } finally { actorChannel.close() } } -@OptIn(InternalAPI::class) private suspend fun respondBadRequest(actorChannel: Channel) { val bc = ByteChannel() if (actorChannel.trySend(bc).isSuccess) { diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt b/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt index 32ee17291db..c2072804580 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt +++ b/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.cio diff --git a/ktor-server/ktor-server-config-yaml/jvm/src/io/ktor/server/config/yaml/YamlConfigJvm.kt b/ktor-server/ktor-server-config-yaml/jvm/src/io/ktor/server/config/yaml/YamlConfigJvm.kt index a86aaf08ff5..cb2b8f7945b 100644 --- a/ktor-server/ktor-server-config-yaml/jvm/src/io/ktor/server/config/yaml/YamlConfigJvm.kt +++ b/ktor-server/ktor-server-config-yaml/jvm/src/io/ktor/server/config/yaml/YamlConfigJvm.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.config.yaml @@ -13,6 +13,7 @@ import java.io.* * On JVM, loads a configuration from application resources, if exist; otherwise, reads a configuration from a file. * On Native, always reads a configuration from a file. */ +@Suppress("ktlint:standard:function-naming") public actual fun YamlConfig(path: String?): YamlConfig? { val resolvedPath = when { path == null -> DEFAULT_YAML_FILENAME diff --git a/ktor-server/ktor-server-config-yaml/jvmAndPosix/src/io/ktor/server/config/yaml/YamlConfig.kt b/ktor-server/ktor-server-config-yaml/jvmAndPosix/src/io/ktor/server/config/yaml/YamlConfig.kt index 15e38de624c..33106c618b3 100644 --- a/ktor-server/ktor-server-config-yaml/jvmAndPosix/src/io/ktor/server/config/yaml/YamlConfig.kt +++ b/ktor-server/ktor-server-config-yaml/jvmAndPosix/src/io/ktor/server/config/yaml/YamlConfig.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.config.yaml import io.ktor.server.config.* @@ -27,6 +28,7 @@ public class YamlConfigLoader : ConfigLoader { * On JVM, loads a configuration from application resources, if exists; otherwise, reads a configuration from a file. * On Native, always reads a configuration from a file. */ +@Suppress("ktlint:standard:function-naming") public expect fun YamlConfig(path: String?): YamlConfig? /** diff --git a/ktor-server/ktor-server-config-yaml/posix/src/io/ktor/server/config/yaml/YamlConfigNix.kt b/ktor-server/ktor-server-config-yaml/posix/src/io/ktor/server/config/yaml/YamlConfigNix.kt index 642eeb3f657..a8216697bef 100644 --- a/ktor-server/ktor-server-config-yaml/posix/src/io/ktor/server/config/yaml/YamlConfigNix.kt +++ b/ktor-server/ktor-server-config-yaml/posix/src/io/ktor/server/config/yaml/YamlConfigNix.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.config.yaml @@ -16,7 +16,7 @@ private fun init() { addConfigLoader(YamlConfigLoader()) } -@Suppress("DEPRECATION") +@Suppress("DEPRECATION", "unused") @OptIn(ExperimentalStdlibApi::class) @EagerInitialization private val initHook = init() @@ -26,6 +26,7 @@ private val initHook = init() * On JVM, loads a configuration from application resources, if exist; otherwise, reads a configuration from a file. * On Native, always reads a configuration from a file. */ +@Suppress("ktlint:standard:function-naming") public actual fun YamlConfig(path: String?): YamlConfig? { val resolvedPath = when { path != null && path.endsWith(".yaml") -> path diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/CommonApplicationEnvironment.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/CommonApplicationEnvironment.kt index 7660479dc70..f2fb3fd3805 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/CommonApplicationEnvironment.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/CommonApplicationEnvironment.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.server.application diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt index 606b1c85d63..641478b9c1f 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.application import io.ktor.server.response.* diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/BaseApplicationResponse.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/BaseApplicationResponse.kt index c5eb0e69d2c..b5c25dc2698 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/BaseApplicationResponse.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/BaseApplicationResponse.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine @@ -10,7 +9,6 @@ import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.engine.internal.* import io.ktor.server.http.* -import io.ktor.server.plugins.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.util.cio.* @@ -21,7 +19,7 @@ import kotlinx.coroutines.* public abstract class BaseApplicationResponse( final override val call: PipelineCall ) : PipelineResponse { - private var _status: HttpStatusCode? = null + private var status: HttpStatusCode? = null override val isCommitted: Boolean get() = responded @@ -33,9 +31,9 @@ public abstract class BaseApplicationResponse( ResponseCookies(this) } - override fun status(): HttpStatusCode? = _status + override fun status(): HttpStatusCode? = status override fun status(value: HttpStatusCode) { - _status = value + status = value setStatus(value) } diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt index 36138c1f71c..8ff29daec65 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine @@ -78,7 +78,8 @@ public fun CoroutineScope.embeddedServer( // ktlint-disable max-line-length +@Suppress("ktlint:standard:max-line-length") +public fun CoroutineScope.embeddedServer( factory: ApplicationEngineFactory, port: Int = 80, host: String = "0.0.0.0", @@ -104,7 +105,8 @@ public fun CoroutineScope.embeddedServer( // ktlint-disable max-line-length +@Suppress("ktlint:standard:max-line-length") +public fun CoroutineScope.embeddedServer( factory: ApplicationEngineFactory, vararg connectors: EngineConnectorConfig = arrayOf(), watchPaths: List = listOf(WORKING_DIRECTORY_PATH), diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/routing/RoutingResolveContext.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/routing/RoutingResolveContext.kt index 3f638fcc923..8d26667ca37 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/routing/RoutingResolveContext.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/routing/RoutingResolveContext.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.routing @@ -187,7 +187,9 @@ public class RoutingResolveContext( val partQuality = if (part.quality == RouteSelectorEvaluation.qualityTransparent) { RouteSelectorEvaluation.qualityConstant - } else part.quality + } else { + part.quality + } quality = minOf(quality, partQuality) } diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/util/Paths.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/util/Paths.kt index 045a252c3a4..29d79819c7c 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/util/Paths.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/util/Paths.kt @@ -41,7 +41,9 @@ private fun List.filterComponentsImpl(startIndex: Int): List { private fun MutableList.processAndReplaceComponent(component: String) { if (component.isEmpty() || - component == "." || component == "~" || component.toUpperCasePreservingASCIIRules() in ReservedWords + component == "." || + component == "~" || + component.toUpperCasePreservingASCIIRules() in ReservedWords ) { return } diff --git a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/application/ApplicationEnvironment.jsAndWasmShared.kt b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/application/ApplicationEnvironment.jsAndWasmShared.kt index bac01c336c8..15ec46cad12 100644 --- a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/application/ApplicationEnvironment.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/application/ApplicationEnvironment.jsAndWasmShared.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.application diff --git a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/config/ConfigLoaders.jsAndWasmShared.kt b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/config/ConfigLoaders.jsAndWasmShared.kt index 7760458e9e5..f250d3e803f 100644 --- a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/config/ConfigLoaders.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/config/ConfigLoaders.jsAndWasmShared.kt @@ -20,7 +20,6 @@ public actual val configLoaders: List private val _configLoaders: MutableList = mutableListOf() -@OptIn(InternalAPI::class) public fun addConfigLoader(loader: ConfigLoader) { _configLoaders.add(loader) } diff --git a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/ApplicationEngineEnvironment.jsAndWasmShared.kt b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/ApplicationEngineEnvironment.jsAndWasmShared.kt index e72c097406e..e9f704e6b81 100644 --- a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/ApplicationEngineEnvironment.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/ApplicationEngineEnvironment.jsAndWasmShared.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/ApplicationEnvironmentJvm.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/ApplicationEnvironmentJvm.kt index d6d022d4788..58512371801 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/ApplicationEnvironmentJvm.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/ApplicationEnvironmentJvm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine @@ -10,7 +9,6 @@ import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.utils.io.* import org.slf4j.* -import kotlin.coroutines.* /** * Builder for configuring the environment of the Ktor application. diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/BlockingBridge.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/BlockingBridge.kt deleted file mode 100644 index 55a851dac59..00000000000 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/BlockingBridge.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.server.engine - -import java.lang.reflect.* - -private val isParkingAllowedFunction: Method? by lazy { - try { - Class.forName("io.ktor.utils.io.jvm.javaio.PollersKt") - .getMethod("isParkingAllowed") - } catch (cause: Throwable) { - null - } -} - -internal fun safeToRunInPlace(): Boolean { - val isParkingAllowed = isParkingAllowedFunction - return isParkingAllowed != null && try { - isParkingAllowed.invoke(null) == true - } catch (cause: Throwable) { - false - } -} diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt index 0e8b31c045d..477c55764b0 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine @@ -44,7 +44,7 @@ actual constructor( public actual val engineConfig: TConfiguration = engineFactory.configuration(engineConfigBlock) private val applicationInstanceLock = ReentrantReadWriteLock() private var recreateInstance: Boolean = false - private var _applicationClassLoader: ClassLoader? = null + private var applicationClassLoader: ClassLoader? = null private var packageWatchKeys = emptyList() private val configuredWatchPath = environment.config.propertyOrNull("ktor.deployment.watch")?.getList().orEmpty() @@ -56,7 +56,7 @@ actual constructor( private val modulesNames: List = configModulesNames - private var _applicationInstance: Application? = Application( + private var applicationInstance: Application? = Application( environment, rootConfig.developmentMode, rootConfig.rootPath, @@ -88,13 +88,13 @@ actual constructor( applicationInstanceLock.write { destroyApplication() val (application, classLoader) = createApplication() - _applicationInstance = application - _applicationClassLoader = classLoader + applicationInstance = application + applicationClassLoader = classLoader } } private fun currentApplication(): Application = applicationInstanceLock.read { - val currentApplication = _applicationInstance ?: error("EmbeddedServer was stopped") + val currentApplication = applicationInstance ?: error("EmbeddedServer was stopped") if (!rootConfig.developmentMode) { return@read currentApplication @@ -125,11 +125,11 @@ actual constructor( applicationInstanceLock.write { destroyApplication() val (application, classLoader) = createApplication() - _applicationInstance = application - _applicationClassLoader = classLoader + applicationInstance = application + applicationClassLoader = classLoader } - return@read _applicationInstance ?: error("EmbeddedServer was stopped") + return@read applicationInstance ?: error("EmbeddedServer was stopped") } private fun createApplication(): Pair { @@ -179,7 +179,8 @@ actual constructor( ).mapNotNullTo(HashSet()) { it.protectionDomain.codeSource.location } val watchUrls = allUrls.filter { url -> - url !in coreUrls && watchPatterns.any { pattern -> checkUrlMatches(url, pattern) } && + url !in coreUrls && + watchPatterns.any { pattern -> checkUrlMatches(url, pattern) } && !(url.path ?: "").startsWith(jre) } @@ -199,16 +200,16 @@ actual constructor( } private fun destroyApplication() { - val currentApplication = _applicationInstance - val applicationClassLoader = _applicationClassLoader - _applicationInstance = null - _applicationClassLoader = null + val currentApplication = applicationInstance + val currentApplicationClassLoader = applicationClassLoader + applicationInstance = null + applicationClassLoader = null if (currentApplication != null) { safeRaiseEvent(ApplicationStopping, currentApplication) try { currentApplication.dispose() - (applicationClassLoader as? OverridingClassLoader)?.close() + (currentApplicationClassLoader as? OverridingClassLoader)?.close() } catch (e: Throwable) { environment.log.error("Failed to destroy application instance.", e) } @@ -277,8 +278,8 @@ actual constructor( throw cause } - _applicationInstance = application - _applicationClassLoader = classLoader + applicationInstance = application + applicationClassLoader = classLoader } CoroutineScope(application.coroutineContext).launch { @@ -313,7 +314,7 @@ actual constructor( } private fun instantiateAndConfigureApplication(currentClassLoader: ClassLoader): Application { - val newInstance = if (recreateInstance || _applicationInstance == null) { + val newInstance = if (recreateInstance || applicationInstance == null) { Application( environment, rootConfig.developmentMode, @@ -324,7 +325,7 @@ actual constructor( ) } else { recreateInstance = true - _applicationInstance!! + applicationInstance!! } safeRaiseEvent(ApplicationStarting, newInstance) diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/LocalFileContent.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/LocalFileContent.kt index c441d452572..abf59447551 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/LocalFileContent.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/LocalFileContent.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.http.content @@ -53,6 +53,7 @@ public fun LocalFileContent( /** * Creates an instance of [LocalPathContent] for a path designated by [relativePath] in a [baseDir] */ +@Suppress("FunctionName") @Deprecated( "Use LocalPathContent instead", ReplaceWith("LocalPathContent(baseDir, relativePath, contentType)", "io.ktor.server.http.content.LocalPathContent") diff --git a/ktor-server/ktor-server-core/posix/src/io/ktor/server/application/NixApplicationEnvironment.kt b/ktor-server/ktor-server-core/posix/src/io/ktor/server/application/NixApplicationEnvironment.kt index bac01c336c8..15ec46cad12 100644 --- a/ktor-server/ktor-server-core/posix/src/io/ktor/server/application/NixApplicationEnvironment.kt +++ b/ktor-server/ktor-server-core/posix/src/io/ktor/server/application/NixApplicationEnvironment.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.application diff --git a/ktor-server/ktor-server-core/posix/src/io/ktor/server/config/ConfigLoadersNix.kt b/ktor-server/ktor-server-core/posix/src/io/ktor/server/config/ConfigLoadersNix.kt index 7760458e9e5..f250d3e803f 100644 --- a/ktor-server/ktor-server-core/posix/src/io/ktor/server/config/ConfigLoadersNix.kt +++ b/ktor-server/ktor-server-core/posix/src/io/ktor/server/config/ConfigLoadersNix.kt @@ -20,7 +20,6 @@ public actual val configLoaders: List private val _configLoaders: MutableList = mutableListOf() -@OptIn(InternalAPI::class) public fun addConfigLoader(loader: ConfigLoader) { _configLoaders.add(loader) } diff --git a/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/ApplicationEngineEnvironmentNix.kt b/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/ApplicationEngineEnvironmentNix.kt index 34f065be23e..e9f704e6b81 100644 --- a/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/ApplicationEngineEnvironmentNix.kt +++ b/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/ApplicationEngineEnvironmentNix.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine @@ -10,7 +9,6 @@ import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.util.logging.* import io.ktor.utils.io.* -import kotlin.coroutines.* /** * Engine environment configuration builder diff --git a/ktor-server/ktor-server-host-common/common/src/Stub.kt b/ktor-server/ktor-server-host-common/common/src/Stub.kt index 0d2c79738f9..c48ad0f3564 100644 --- a/ktor-server/ktor-server-host-common/common/src/Stub.kt +++ b/ktor-server/ktor-server-host-common/common/src/Stub.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.host.common internal fun stub() { diff --git a/ktor-server/ktor-server-jetty-jakarta/jvm/src/io/ktor/server/jetty/jakarta/Embedded.kt b/ktor-server/ktor-server-jetty-jakarta/jvm/src/io/ktor/server/jetty/jakarta/Embedded.kt index c5f6f87d851..32b8f0003d4 100644 --- a/ktor-server/ktor-server-jetty-jakarta/jvm/src/io/ktor/server/jetty/jakarta/Embedded.kt +++ b/ktor-server/ktor-server-jetty-jakarta/jvm/src/io/ktor/server/jetty/jakarta/Embedded.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.jetty.jakarta diff --git a/ktor-server/ktor-server-jetty/jvm/src/io/ktor/server/jetty/Embedded.kt b/ktor-server/ktor-server-jetty/jvm/src/io/ktor/server/jetty/Embedded.kt index 4471028735d..cb50a95e4b9 100644 --- a/ktor-server/ktor-server-jetty/jvm/src/io/ktor/server/jetty/Embedded.kt +++ b/ktor-server/ktor-server-jetty/jvm/src/io/ktor/server/jetty/Embedded.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.jetty diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt index 54af222a316..ef6e390f842 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.netty @@ -33,7 +33,9 @@ public suspend fun Future.suspendAwait(): T { private val wrappingErrorHandler = { t: Throwable, c: Continuation<*> -> if (t is IOException) { c.resumeWithException(ChannelWriteException("Write operation future failed", t)) - } else c.resumeWithException(t) + } else { + c.resumeWithException(t) + } } /** diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/Embedded.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/Embedded.kt index 7568d9cc53b..84d91913ec7 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/Embedded.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/Embedded.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.netty diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt index 0efe027fc05..21ac50dd28e 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.netty @@ -20,6 +20,8 @@ internal class NettyDirectEncoder : MessageToByteEncoder() { Unpooled.EMPTY_BUFFER } else if (preferDirect) { ctx.alloc().ioBuffer(size) - } else ctx.alloc().heapBuffer(size) + } else { + ctx.alloc().heapBuffer(size) + } } } diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/RequestBodyHandler.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/RequestBodyHandler.kt index 6e72b84dd99..11fdfcdd4d5 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/RequestBodyHandler.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/RequestBodyHandler.kt @@ -151,7 +151,7 @@ internal class RequestBodyHandler( } } - @OptIn(ExperimentalCoroutinesApi::class, InternalAPI::class) + @OptIn(ExperimentalCoroutinesApi::class) private fun consumeAndReleaseQueue() { while (!queue.isEmpty) { val e = try { diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1ApplicationResponse.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1ApplicationResponse.kt index 71552b6f244..9b73ff6f438 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1ApplicationResponse.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1ApplicationResponse.kt @@ -76,7 +76,6 @@ internal class NettyHttp1ApplicationResponse( return responseMessage } - @OptIn(InternalAPI::class) override suspend fun respondUpgrade(upgrade: OutgoingContent.ProtocolUpgrade) { val nettyContext = context val nettyChannel = nettyContext.channel() diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1Handler.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1Handler.kt index 2eac80f304b..2aafd3368ef 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1Handler.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1Handler.kt @@ -130,7 +130,8 @@ internal class NettyHttp1Handler( val requestBodyChannel = when { message is LastHttpContent && !message.content().isReadable -> null message.method() === HttpMethod.GET && - !HttpUtil.isContentLengthSet(message) && !HttpUtil.isTransferEncodingChunked(message) -> { + !HttpUtil.isContentLengthSet(message) && + !HttpUtil.isTransferEncodingChunked(message) -> { skipEmpty = true null } diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http2/NettyHttp2ApplicationRequest.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http2/NettyHttp2ApplicationRequest.kt index 698cea7a159..06a6f145b68 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http2/NettyHttp2ApplicationRequest.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http2/NettyHttp2ApplicationRequest.kt @@ -16,7 +16,6 @@ import kotlinx.coroutines.channels.* import java.net.* import kotlin.coroutines.* -@OptIn(InternalAPI::class) internal class NettyHttp2ApplicationRequest( call: PipelineCall, coroutineContext: CoroutineContext, diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt b/ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt index 308d45cf290..c34f0ca18c2 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt @@ -69,7 +69,10 @@ class JWTAuthTest { jwt(name = "first") { realm = "realm1" verifier(issuer, audience, algorithm) - validate { validated.add("1"); currentPrincipal(it) } + validate { + validated.add("1") + currentPrincipal(it) + } challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom1", Charsets.UTF_8))) } @@ -77,7 +80,10 @@ class JWTAuthTest { jwt(name = "second") { realm = "realm2" verifier(issuer, audience, algorithm) - validate { validated.add("2"); currentPrincipal(it) } + validate { + validated.add("2") + currentPrincipal(it) + } challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom2", Charsets.UTF_8))) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/AuthenticationContext.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/AuthenticationContext.kt index 6bdff4d5aab..4f47f8edfdc 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/AuthenticationContext.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/AuthenticationContext.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth @@ -17,8 +17,9 @@ public class AuthenticationContext(call: ApplicationCall) { public var call: ApplicationCall = call private set - private val _errors = HashMap() + private val errors = HashMap() + @Suppress("PropertyName") internal val _principal: CombinedPrincipal = CombinedPrincipal() /** @@ -36,19 +37,19 @@ public class AuthenticationContext(call: ApplicationCall) { * All registered errors during auth procedure (only [AuthenticationFailedCause.Error]). */ public val allErrors: List - get() = _errors.values.filterIsInstance() + get() = errors.values.filterIsInstance() /** * All authentication failures during auth procedure including missing or invalid credentials. */ public val allFailures: List - get() = _errors.values.toList() + get() = errors.values.toList() /** * Appends an error to the errors list. Overwrites if already registered for the same [key]. */ public fun error(key: Any, cause: AuthenticationFailedCause) { - _errors[key] = cause + errors[key] = cause } /** diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/OAuthCommon.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/OAuthCommon.kt index 017b8de3488..4a5e22c5b4c 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/OAuthCommon.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/OAuthCommon.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth @@ -14,7 +14,8 @@ import io.ktor.util.* */ public enum class OAuthVersion { - V10a, V20 + V10a, + V20, } /** diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/Principal.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/Principal.kt index 9bfe75a99c0..240a5be8963 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/Principal.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/Principal.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth @@ -31,7 +31,9 @@ internal class CombinedPrincipal { .firstOrNull { (name, principal) -> if (provider != null) { name == provider && klass.isInstance(principal) - } else klass.isInstance(principal) + } else { + klass.isInstance(principal) + } }?.second as? T } diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/SessionAuth.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/SessionAuth.kt index e9941e3fc97..8ad18b78764 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/SessionAuth.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/src/io/ktor/server/auth/SessionAuth.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth @@ -38,7 +38,9 @@ public class SessionAuthenticationProvider private constructor( val cause = if (session == null) { AuthenticationFailedCause.NoCredentials - } else AuthenticationFailedCause.InvalidCredentials + } else { + AuthenticationFailedCause.InvalidCredentials + } @Suppress("NAME_SHADOWING") context.challenge(SessionAuthChallengeKey, cause) { challenge, call -> diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/OAuth2Test.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/OAuth2Test.kt index 16a387b771a..340c50a6cd0 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/OAuth2Test.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/OAuth2Test.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.auth @@ -349,7 +349,7 @@ class OAuth2Test { call.authentication.allFailures.all { it is OAuth2RedirectError && it.error == "access_denied" } - } // ktlint-disable max-line-length + } } } val call = noRedirectsClient().get( diff --git a/ktor-server/ktor-server-plugins/ktor-server-body-limit/common/test/io/ktor/server/plugins/bodylimit/RequestBodyLimitTest.kt b/ktor-server/ktor-server-plugins/ktor-server-body-limit/common/test/io/ktor/server/plugins/bodylimit/RequestBodyLimitTest.kt index d27d23a840e..25a173465dd 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-body-limit/common/test/io/ktor/server/plugins/bodylimit/RequestBodyLimitTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-body-limit/common/test/io/ktor/server/plugins/bodylimit/RequestBodyLimitTest.kt @@ -1,6 +1,7 @@ /* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.plugins.bodylimit import io.ktor.client.request.* diff --git a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/CallLoggingConfig.kt b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/CallLoggingConfig.kt index 87100810ccb..354858456b8 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/CallLoggingConfig.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/CallLoggingConfig.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.calllogging @@ -135,5 +135,7 @@ public class CallLoggingConfig { private fun colored(value: Any, color: Ansi.Color): String = if (isColorsEnabled) { Ansi.ansi().fg(color).a(value).reset().toString() - } else value.toString() // ignore color + } else { + value.toString() // ignore color + } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/MDCHook.kt b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/MDCHook.kt index ddb745cf0ab..35d9310a375 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/MDCHook.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/calllogging/MDCHook.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.calllogging @@ -9,6 +9,7 @@ import io.ktor.server.response.* import io.ktor.util.* import io.ktor.util.pipeline.* +@Suppress("FunctionName") internal fun MDCHook(phase: PipelinePhase) = object : Hook Unit) -> Unit> { override fun install( pipeline: ApplicationCallPipeline, diff --git a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/calllogging/CallLoggingTest.kt b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/calllogging/CallLoggingTest.kt index 36d8d67cf55..f2873d553ba 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/calllogging/CallLoggingTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/calllogging/CallLoggingTest.kt @@ -520,9 +520,10 @@ class CallLoggingTest { client.get("/").apply { assertEquals(HttpStatusCode.BadRequest, status) + @Suppress("ktlint:standard:max-line-length") assertContains( messages, - "DEBUG: Unhandled: GET - /. Exception class io.ktor.server.plugins.BadRequestException: Message of exception" // ktlint-disable max-line-length + "DEBUG: Unhandled: GET - /. Exception class io.ktor.server.plugins.BadRequestException: Message of exception" ) } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Config.kt b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Config.kt index 6bc4326a4c0..9a52c269aa6 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Config.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Config.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.compression @@ -49,7 +49,9 @@ public data class CompressionEncoderConfig( public class CompressionConfig : ConditionsHolderBuilder { public enum class Mode(internal val request: Boolean, internal val response: Boolean) { - CompressResponse(false, true), DecompressRequest(true, false), All(true, true) + CompressResponse(false, true), + DecompressRequest(true, false), + All(true, true), } /** diff --git a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/src/io/ktor/server/plugins/contentnegotiation/ContentNegotiation.kt b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/src/io/ktor/server/plugins/contentnegotiation/ContentNegotiation.kt index e7b66cc593a..0ce0729692f 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/src/io/ktor/server/plugins/contentnegotiation/ContentNegotiation.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/src/io/ktor/server/plugins/contentnegotiation/ContentNegotiation.kt @@ -59,9 +59,11 @@ public val ContentNegotiation: RouteScopedPlugin = cre * Detects a suitable charset for an application call by using the `Accept` header or fallbacks to [defaultCharset]. */ public fun ApplicationCall.suitableCharset(defaultCharset: Charset = Charsets.UTF_8): Charset { - for ((charset, _) in request.acceptCharsetItems()) when { - charset == "*" -> return defaultCharset - Charsets.isSupported(charset) -> return Charsets.forName(charset) + for ((charset, _) in request.acceptCharsetItems()) { + when { + charset == "*" -> return defaultCharset + Charsets.isSupported(charset) -> return Charsets.forName(charset) + } } return defaultCharset } diff --git a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/test/RequestConverterTest.kt b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/test/RequestConverterTest.kt index 35d9a102d7c..c6867223d3a 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/test/RequestConverterTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/common/test/RequestConverterTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.contentnegotiation @@ -78,8 +78,9 @@ class RequestConverterTest { }.bodyAsText() try { + @Suppress("ktlint:standard:max-line-length") assertEquals( - "Cannot transform this request's content to io.ktor.server.plugins.contentnegotiation.NonSerializableClass", // ktlint-disable max-line-length + "Cannot transform this request's content to io.ktor.server.plugins.contentnegotiation.NonSerializableClass", responseFoo ) } catch (cause: Throwable) { diff --git a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvm/test/ContentNegotiationJvmTest.kt b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvm/test/ContentNegotiationJvmTest.kt index d5030193b62..4cbcf2de77b 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvm/test/ContentNegotiationJvmTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvm/test/ContentNegotiationJvmTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.plugins.contentnegotiation import io.ktor.client.request.* diff --git a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORS.kt b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORS.kt index 9eecb1d38cc..dc6765585d0 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORS.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORS.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.cors @@ -155,7 +155,9 @@ internal fun PluginBuilder.buildPlugin() { } private enum class OriginCheckResult { - OK, SkipCORS, Failed + OK, + SkipCORS, + Failed, } private fun checkOrigin( diff --git a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSConfig.kt b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSConfig.kt index d213cbb237d..ec8c2e0a4af 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSConfig.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSConfig.kt @@ -185,7 +185,8 @@ public class CORSConfig { private fun wildcardInFrontOfDomain(host: String): Boolean { val indexOfWildcard = host.indexOf(wildcardWithDot) - return wildcardWithDot in host && !host.endsWith(wildcardWithDot) && + return wildcardWithDot in host && + !host.endsWith(wildcardWithDot) && (indexOfWildcard <= 0 || host.substringBefore(wildcardWithDot).endsWith("://")) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSUtils.kt b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSUtils.kt index ed012be71f1..1b5d8d068f1 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSUtils.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/CORSUtils.kt @@ -51,9 +51,11 @@ internal fun corsCheckOrigins( originPredicates: List<(String) -> Boolean>, ): Boolean { val normalizedOrigin = normalizeOrigin(origin) - return allowsAnyHost || normalizedOrigin in hostsNormalized || hostsWithWildcard.any { (prefix, suffix) -> - normalizedOrigin.startsWith(prefix) && normalizedOrigin.endsWith(suffix) - } || originPredicates.any { it(origin) } + return allowsAnyHost || + normalizedOrigin in hostsNormalized || + hostsWithWildcard + .any { (prefix, suffix) -> normalizedOrigin.startsWith(prefix) && normalizedOrigin.endsWith(suffix) } || + originPredicates.any { it(origin) } } internal fun corsCheckRequestHeaders( @@ -86,9 +88,9 @@ internal fun isValidOrigin(origin: String): Boolean { val protoDelimiter = origin.indexOf("://") if (protoDelimiter <= 0) return false - val protoValid = origin[0].isLetter() && origin.subSequence(0, protoDelimiter).all { ch -> - ch.isLetter() || ch.isDigit() || ch == '-' || ch == '+' || ch == '.' - } + val protoValid = origin[0].isLetter() && + origin.subSequence(0, protoDelimiter) + .all { ch -> ch.isLetter() || ch.isDigit() || ch == '-' || ch == '+' || ch == '.' } if (!protoValid) return false diff --git a/ktor-server/ktor-server-plugins/ktor-server-default-headers/api/ktor-server-default-headers.api b/ktor-server/ktor-server-plugins/ktor-server-default-headers/api/ktor-server-default-headers.api index 5aacfc55abb..ac86b82f87b 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-default-headers/api/ktor-server-default-headers.api +++ b/ktor-server/ktor-server-plugins/ktor-server-default-headers/api/ktor-server-default-headers.api @@ -1,7 +1,9 @@ public final class io/ktor/server/plugins/defaultheaders/DefaultHeadersConfig { public fun ()V + public final fun getCachedDateText$ktor_server_default_headers ()Ljava/lang/String; public final fun getClock ()Lio/ktor/server/plugins/defaultheaders/DefaultHeadersConfig$Clock; public final fun header (Ljava/lang/String;Ljava/lang/String;)V + public final fun setCachedDateText$ktor_server_default_headers (Ljava/lang/String;)V public final fun setClock (Lio/ktor/server/plugins/defaultheaders/DefaultHeadersConfig$Clock;)V } diff --git a/ktor-server/ktor-server-plugins/ktor-server-default-headers/common/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt b/ktor-server/ktor-server-plugins/ktor-server-default-headers/common/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt index 19f7abd6ee7..747b4c5d9b0 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-default-headers/common/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-default-headers/common/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.server.plugins.defaultheaders @@ -10,7 +10,7 @@ import io.ktor.server.plugins.defaultheaders.DefaultHeadersConfig.* import io.ktor.server.response.* import io.ktor.util.date.* import io.ktor.utils.io.* -import kotlinx.atomicfu.* +import kotlinx.atomicfu.atomic /** * A configuration for the [DefaultHeaders] plugin. @@ -43,13 +43,7 @@ public class DefaultHeadersConfig { public fun now(): Long } - private val _cachedDateText = atomic("") - - internal var cachedDateText: String - get() = _cachedDateText.value - set(value) { - _cachedDateText.value = value - } + internal var cachedDateText: String by atomic("") } /** diff --git a/ktor-server/ktor-server-plugins/ktor-server-double-receive/common/src/io/ktor/server/plugins/doublereceive/ByteArrayCache.kt b/ktor-server/ktor-server-plugins/ktor-server-double-receive/common/src/io/ktor/server/plugins/doublereceive/ByteArrayCache.kt index 169bf3e32c6..f93f92c70cc 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-double-receive/common/src/io/ktor/server/plugins/doublereceive/ByteArrayCache.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-double-receive/common/src/io/ktor/server/plugins/doublereceive/ByteArrayCache.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.doublereceive diff --git a/ktor-server/ktor-server-plugins/ktor-server-double-receive/jsAndWasmShared/src/io/ktor/server/plugins/doublereceive/FileCache.jsAndWasmShared.kt b/ktor-server/ktor-server-plugins/ktor-server-double-receive/jsAndWasmShared/src/io/ktor/server/plugins/doublereceive/FileCache.jsAndWasmShared.kt index 4648d18e5f2..e78d3b14e28 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-double-receive/jsAndWasmShared/src/io/ktor/server/plugins/doublereceive/FileCache.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-double-receive/jsAndWasmShared/src/io/ktor/server/plugins/doublereceive/FileCache.jsAndWasmShared.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.doublereceive diff --git a/ktor-server/ktor-server-plugins/ktor-server-double-receive/jvm/src/io/ktor/server/plugins/doublereceive/FileCacheJvm.kt b/ktor-server/ktor-server-plugins/ktor-server-double-receive/jvm/src/io/ktor/server/plugins/doublereceive/FileCacheJvm.kt index 30b9a1ffa7a..0783e8fd0c4 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-double-receive/jvm/src/io/ktor/server/plugins/doublereceive/FileCacheJvm.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-double-receive/jvm/src/io/ktor/server/plugins/doublereceive/FileCacheJvm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.doublereceive diff --git a/ktor-server/ktor-server-plugins/ktor-server-double-receive/posix/src/io/ktor/server/plugins/doublereceive/FileCacheNix.kt b/ktor-server/ktor-server-plugins/ktor-server-double-receive/posix/src/io/ktor/server/plugins/doublereceive/FileCacheNix.kt index 4648d18e5f2..e78d3b14e28 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-double-receive/posix/src/io/ktor/server/plugins/doublereceive/FileCacheNix.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-double-receive/posix/src/io/ktor/server/plugins/doublereceive/FileCacheNix.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.doublereceive diff --git a/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/common/src/io/ktor/server/plugins/forwardedheaders/XForwardedHeaders.kt b/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/common/src/io/ktor/server/plugins/forwardedheaders/XForwardedHeaders.kt index 69192929313..259e35475f1 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/common/src/io/ktor/server/plugins/forwardedheaders/XForwardedHeaders.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/common/src/io/ktor/server/plugins/forwardedheaders/XForwardedHeaders.kt @@ -102,7 +102,8 @@ public class XForwardedHeadersConfig { var proxiesCount = 0 while ( hosts.lastIndex >= proxiesCount && - forValues != null && forValues.lastIndex >= proxiesCount && + forValues != null && + forValues.lastIndex >= proxiesCount && hosts[hosts.size - proxiesCount - 1].trim() == forValues[forValues.size - proxiesCount - 1].trim() ) { proxiesCount++ diff --git a/ktor-server/ktor-server-plugins/ktor-server-http-redirect/common/src/io/ktor/server/plugins/httpsredirect/HttpsRedirect.kt b/ktor-server/ktor-server-plugins/ktor-server-http-redirect/common/src/io/ktor/server/plugins/httpsredirect/HttpsRedirect.kt index 231d083261d..10c5a060a9f 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-http-redirect/common/src/io/ktor/server/plugins/httpsredirect/HttpsRedirect.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-http-redirect/common/src/io/ktor/server/plugins/httpsredirect/HttpsRedirect.kt @@ -83,7 +83,10 @@ public val HttpsRedirect: ApplicationPlugin = createApplica if (call.request.origin.scheme == "http" && pluginConfig.excludePredicates.none { predicate -> predicate(call) } ) { - val redirectUrl = call.url { protocol = URLProtocol.HTTPS; port = pluginConfig.sslPort } + val redirectUrl = call.url { + protocol = URLProtocol.HTTPS + port = pluginConfig.sslPort + } if (!call.response.isCommitted) { call.respondRedirect(redirectUrl, pluginConfig.permanentRedirect) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-request-validation/common/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt b/ktor-server/ktor-server-plugins/ktor-server-request-validation/common/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt index a3b0f129442..f001df1c323 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-request-validation/common/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-request-validation/common/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.requestvalidation @@ -23,12 +23,16 @@ class RequestValidationTest { validate { if (!it.startsWith("+")) { ValidationResult.Invalid(listOf("$it should start with \"+\"")) - } else ValidationResult.Valid + } else { + ValidationResult.Valid + } } validate { if (!it.endsWith("!")) { ValidationResult.Invalid(listOf("$it should end with \"!\"")) - } else ValidationResult.Valid + } else { + ValidationResult.Valid + } } } install(StatusPages) { @@ -96,7 +100,9 @@ class RequestValidationTest { val intValue = it.decodeToString(0, 0 + it.size).toInt() if (intValue < 0) { ValidationResult.Invalid("Value is negative") - } else ValidationResult.Valid + } else { + ValidationResult.Valid + } } } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-resources/common/test/io/ktor/tests/resources/ResourcesTest.kt b/ktor-server/ktor-server-plugins/ktor-server-resources/common/test/io/ktor/tests/resources/ResourcesTest.kt index e54e1e4cc30..0ed0acd64a4 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-resources/common/test/io/ktor/tests/resources/ResourcesTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-resources/common/test/io/ktor/tests/resources/ResourcesTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.resources @@ -413,7 +413,9 @@ class ResourcesTest { } enum class resourceEnum { - A, B, C + A, + B, + C, } @Resource("/") diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionData.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionData.kt index c7a5b912f6a..f431b146132 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionData.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionData.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.sessions @@ -161,7 +161,7 @@ internal suspend fun SessionProviderData.sendSessionData(call: Appl } incoming && oldValue == null -> { - /* Deleted session should be cleared off */ + // Deleted session should be cleared off provider.transport.clear(call) provider.tracker.clear(call) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionTransportCookie.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionTransportCookie.kt index 38003006731..ed6ee613ac9 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionTransportCookie.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionTransportCookie.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.sessions import io.ktor.http.* diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionsBuilder.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionsBuilder.kt index 43afaf5f6a5..c3a746ec0cd 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionsBuilder.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/src/io/ktor/server/sessions/SessionsBuilder.kt @@ -325,7 +325,9 @@ internal constructor( * Specifies a serializer used to serialize session data. */ public var serializer: SessionSerializer - set(value) { _serializer = value } + set(value) { + _serializer = value + } get() = _serializer ?: defaultSerializer private val _transformers = mutableListOf() diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/test/io/ktor/server/sessions/CacheTest.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/test/io/ktor/server/sessions/CacheTest.kt index bbb1e9a00db..6e398b65f4a 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/common/test/io/ktor/server/sessions/CacheTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/common/test/io/ktor/server/sessions/CacheTest.kt @@ -4,8 +4,10 @@ package io.ktor.server.sessions -import kotlinx.coroutines.* -import kotlinx.coroutines.test.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest import kotlin.test.* class CacheTest { @@ -13,7 +15,10 @@ class CacheTest { fun testBaseSimpleCase() = runTest { var counter = 0 - val cache = BaseCache { counter++; it.toString() } + val cache = BaseCache { + counter++ + it.toString() + } assertEquals("1", cache.getOrCompute(1)) assertEquals(1, counter) @@ -30,7 +35,10 @@ class CacheTest { val latch = Job() var ref = "" - val cache = BaseCache { if (it == 0) latch.join(); it.toString() } + val cache = BaseCache { + if (it == 0) latch.join() + it.toString() + } assertEquals("1", cache.getOrCompute(1)) val th = launch(Dispatchers.Default) { @@ -47,14 +55,17 @@ class CacheTest { @Test fun testPeek() = runTest { - val cache = BaseCache { fail(""); } + val cache = BaseCache { fail("") } assertNull(cache.peek(1)) } @Test fun testInvalidate() = runTest { var counter = 0 - val cache = BaseCache { counter++; it.toString() } + val cache = BaseCache { + counter++ + it.toString() + } assertEquals("1", cache.getOrCompute(1)) assertEquals(1, counter) @@ -78,7 +89,10 @@ class CacheTest { class ExpectedException : Exception() var counter = 0 - val cache = BaseCache { counter++; throw ExpectedException() } + val cache = BaseCache { + counter++ + throw ExpectedException() + } assertFailsWith { cache.getOrCompute(1) diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/CacheJvm.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/CacheJvm.kt index 95eebfdef95..856286ea7fb 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/CacheJvm.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/CacheJvm.kt @@ -20,8 +20,16 @@ internal open class ReferenceCache( val wrapFunction: (K, V, ReferenceQueue) -> R ) : Cache where R : Reference, R : CacheReference { private val queue = ReferenceQueue() - private val container = BaseCache { key: K -> forkThreadIfNeeded(); wrapFunction(key, calc(key), queue) } - private val workerThread by lazy { Thread(ReferenceWorker(container, queue)).apply { isDaemon = true; start() } } + private val container = BaseCache { key: K -> + forkThreadIfNeeded() + wrapFunction(key, calc(key), queue) + } + private val workerThread by lazy { + Thread(ReferenceWorker(container, queue)).apply { + isDaemon = true + start() + } + } override suspend fun getOrCompute(key: K): V { val ref = container.getOrCompute(key) @@ -100,7 +108,10 @@ internal class BaseTimeoutCache( private val map = WeakHashMap>() private val workerThread by lazy { - Thread(TimeoutWorker(this, lock, cond, items)).apply { isDaemon = true; start() } + Thread(TimeoutWorker(this, lock, cond, items)).apply { + isDaemon = true + start() + } } override suspend fun getOrCompute(key: K): V { diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt index 2b07c2f9299..75127ceac4f 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt @@ -1,8 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable experimental:argument-list-wrapping package io.ktor.server.sessions import io.ktor.http.* @@ -207,7 +206,7 @@ internal class SessionSerializerReflection( .filterAssignable(type) .firstHasNoArgConstructor() ?.callNoArgConstructor() - ?.withUnsafe { addAll(value.map { coerceType(contentType, it) }); this } + ?.withUnsafe { apply { addAll(value.map { coerceType(contentType, it) }) } } ?: throw IllegalArgumentException("Couldn't coerce type ${value::class.java} to $type") } } @@ -227,7 +226,7 @@ internal class SessionSerializerReflection( .filterAssignable(type) .firstHasNoArgConstructor() ?.callNoArgConstructor() - ?.withUnsafe { addAll(value.map { coerceType(contentType, it) }); this } + ?.withUnsafe { apply { addAll(value.map { coerceType(contentType, it) }) } } ?: throw IllegalArgumentException("Couldn't coerce type ${value::class.java} to $type") } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt index 3750b30c057..44626b51c86 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt @@ -18,7 +18,10 @@ class CacheTest { val timeout = BaseTimeoutCache( 1000L, true, - BaseCache { counter.incrementAndGet(); it.toString() } + BaseCache { + counter.incrementAndGet() + it.toString() + } ) assertEquals("1", timeout.getOrCompute(1)) @@ -33,7 +36,10 @@ class CacheTest { val timeout = BaseTimeoutCache( 10L, true, - BaseCache { counter.incrementAndGet(); it.toString() } + BaseCache { + counter.incrementAndGet() + it.toString() + } ) assertEquals("1", timeout.getOrCompute(1)) diff --git a/ktor-server/ktor-server-plugins/ktor-server-websockets/common/test/io/ktor/tests/websocket/RawWebSocketTest.kt b/ktor-server/ktor-server-plugins/ktor-server-websockets/common/test/io/ktor/tests/websocket/RawWebSocketTest.kt index 21c4d4991bd..558102d089a 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-websockets/common/test/io/ktor/tests/websocket/RawWebSocketTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-websockets/common/test/io/ktor/tests/websocket/RawWebSocketTest.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.tests.websocket @@ -36,7 +36,7 @@ class RawWebSocketTest { } @AfterTest - fun _verifyErrors() { + fun verifyErrors() { if (errors.isEmpty()) return val error = IllegalStateException( diff --git a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/AsyncServlet.kt b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/AsyncServlet.kt index 10da3669163..aa0b5a815d8 100644 --- a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/AsyncServlet.kt +++ b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/AsyncServlet.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.servlet.jakarta @@ -64,7 +64,9 @@ public class AsyncServletApplicationRequest( if (!upgraded) { val contentLength = servletRequest.contentLength servletReader(servletRequest.inputStream, contentLength).channel - } else ByteReadChannel.Empty + } else { + ByteReadChannel.Empty + } } override val engineReceiveChannel: ByteReadChannel get() = inputStreamChannel diff --git a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletReader.kt b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletReader.kt index 0588c8b1c2e..593b0354ad0 100644 --- a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletReader.kt +++ b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletReader.kt @@ -24,7 +24,6 @@ private class ServletReader(val input: ServletInputStream, val contentLength: In val channel = ByteChannel() private val events = Channel(2) - @OptIn(InternalAPI::class) suspend fun run() { val buffer = ArrayPool.borrow() try { @@ -51,7 +50,6 @@ private class ServletReader(val input: ServletInputStream, val contentLength: In } } - @OptIn(InternalAPI::class) @Suppress("BlockingMethodInNonBlockingContext") private suspend fun loop(buffer: ByteArray) { var bodySize = 0 diff --git a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/AsyncServlet.kt b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/AsyncServlet.kt index de5daf34bfa..df6447c9713 100644 --- a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/AsyncServlet.kt +++ b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/AsyncServlet.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.server.servlet @@ -64,7 +64,9 @@ public class AsyncServletApplicationRequest( if (!upgraded) { val contentLength = servletRequest.contentLength servletReader(servletRequest.inputStream, contentLength).channel - } else ByteReadChannel.Empty + } else { + ByteReadChannel.Empty + } } override val engineReceiveChannel: ByteReadChannel get() = inputStreamChannel diff --git a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletReader.kt b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletReader.kt index 44fd6f04d10..af4e70c8127 100644 --- a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletReader.kt +++ b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletReader.kt @@ -24,7 +24,6 @@ private class ServletReader(val input: ServletInputStream, val contentLength: In val channel = ByteChannel() private val events = Channel(2) - @OptIn(InternalAPI::class) suspend fun run() { val buffer = ArrayPool.borrow() try { @@ -52,7 +51,6 @@ private class ServletReader(val input: ServletInputStream, val contentLength: In } } - @OptIn(InternalAPI::class) @Suppress("BlockingMethodInNonBlockingContext") private suspend fun loop(buffer: ByteArray) { var bodySize = 0 diff --git a/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt b/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt index fe9b632b017..c688ed37db0 100644 --- a/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt @@ -68,7 +68,7 @@ actual constructor( parent: CoroutineContext = EmptyCoroutineContext, module: Application.() -> Unit ): EmbeddedServer { - val _port = this.port + val savedPort = this.port val environment = applicationEnvironment { val delegate = KtorSimpleLogger("io.ktor.test") this.log = log ?: object : Logger by delegate { @@ -89,7 +89,7 @@ actual constructor( } return embeddedServer(applicationEngineFactory, properties) { - connector { port = _port } + connector { port = savedPort } shutdownGracePeriod = 1000 shutdownTimeout = 1000 } @@ -110,7 +110,7 @@ actual constructor( starting.join() @OptIn(ExperimentalCoroutinesApi::class) starting.getCompletionExceptionOrNull()?.let { listOf(it) } ?: emptyList() - } catch (t: Throwable) { // InterruptedException? + } catch (t: Throwable) { starting.cancel() listOf(t) } diff --git a/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/BaseTestJvm.kt b/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/BaseTestJvm.kt index 629eab0cb76..d85d15afb82 100644 --- a/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/BaseTestJvm.kt +++ b/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/BaseTestJvm.kt @@ -2,7 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.server.test.base import io.ktor.junit.* diff --git a/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/EngineTestBaseJvm.kt b/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/EngineTestBaseJvm.kt index 34e9a8bb26c..9660a308c25 100644 --- a/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/EngineTestBaseJvm.kt +++ b/ktor-server/ktor-server-test-base/jvm/src/io/ktor/server/test/base/EngineTestBaseJvm.kt @@ -2,7 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.server.test.base import io.ktor.client.* @@ -44,7 +43,6 @@ actual abstract class EngineTestBase< ) : BaseTest(), CoroutineScope { private val testJob = Job() - @OptIn(ExperimentalCoroutinesApi::class) protected val testDispatcher = Dispatchers.IO.limitedParallelism(32) protected val isUnderDebugger: Boolean = @@ -114,7 +112,7 @@ actual abstract class EngineTestBase< parent: CoroutineContext = EmptyCoroutineContext, module: Application.() -> Unit ): EmbeddedServer { - val _port = this.port + val savedPort = this.port val environment = applicationEnvironment { val delegate = LoggerFactory.getLogger("io.ktor.test") this.log = log ?: object : Logger by delegate { @@ -140,7 +138,7 @@ actual abstract class EngineTestBase< shutdownGracePeriod = 1000 shutdownTimeout = 1000 - connector { port = _port } + connector { port = savedPort } if (enableSsl) { sslConnector(keyStore, "mykey", { "changeit".toCharArray() }, { "changeit".toCharArray() }) { this.port = sslPort @@ -219,7 +217,7 @@ actual abstract class EngineTestBase< starting.join() @OptIn(ExperimentalCoroutinesApi::class) starting.getCompletionExceptionOrNull()?.let { listOf(it) } ?: emptyList() - } catch (t: Throwable) { // InterruptedException? + } catch (t: Throwable) { starting.cancel() listOf(t) } diff --git a/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt b/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt index b575aa151b8..6e8967fe3ce 100644 --- a/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt +++ b/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt @@ -79,7 +79,7 @@ actual constructor( parent: CoroutineContext = EmptyCoroutineContext, module: Application.() -> Unit ): EmbeddedServer { - val _port = this.port + val savedPort = this.port val environment = applicationEnvironment { val delegate = KtorSimpleLogger("io.ktor.test") this.log = log ?: object : Logger by delegate { @@ -100,7 +100,7 @@ actual constructor( } return embeddedServer(applicationEngineFactory, properties) { - connector { port = _port } + connector { port = savedPort } shutdownGracePeriod = 1000 shutdownTimeout = 1000 } @@ -121,7 +121,7 @@ actual constructor( starting.join() @OptIn(ExperimentalCoroutinesApi::class) starting.getCompletionExceptionOrNull()?.let { listOf(it) } ?: emptyList() - } catch (t: Throwable) { // InterruptedException? + } catch (t: Throwable) { starting.cancel() listOf(t) } diff --git a/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/TestApplication.kt b/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/TestApplication.kt index 600d44455fb..8dceb97158f 100644 --- a/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/TestApplication.kt +++ b/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/TestApplication.kt @@ -62,7 +62,10 @@ public class TestApplication internal constructor( ) : ClientProvider by clientProvider { internal enum class State { - Created, Starting, Started, Stopped + Created, + Starting, + Started, + Stopped, } private val state = atomic(State.Created) @@ -202,7 +205,10 @@ public open class TestApplicationBuilder { public fun engine(block: TestApplicationEngine.Configuration.() -> Unit) { checkNotBuilt() val oldBuilder = engineConfig - engineConfig = { oldBuilder(); block() } + engineConfig = { + oldBuilder() + block() + } } /** @@ -213,7 +219,10 @@ public open class TestApplicationBuilder { public fun serverConfig(block: ServerConfigBuilder.() -> Unit) { checkNotBuilt() val oldBuilder = applicationProperties - applicationProperties = { oldBuilder(); block() } + applicationProperties = { + oldBuilder() + block() + } } /** @@ -224,7 +233,10 @@ public open class TestApplicationBuilder { public fun environment(block: ApplicationEnvironmentBuilder.() -> Unit) { checkNotBuilt() val oldBuilder = environmentBuilder - environmentBuilder = { oldBuilder(); block() } + environmentBuilder = { + oldBuilder() + block() + } } /** diff --git a/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/client/TestHttpClientEngineBridge.jsAndWasmShared.kt b/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/client/TestHttpClientEngineBridge.jsAndWasmShared.kt index ddd907c0e1e..17d1d11bf97 100644 --- a/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/client/TestHttpClientEngineBridge.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/client/TestHttpClientEngineBridge.jsAndWasmShared.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing.client diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt index 8a0234194a3..29ef02c0d07 100644 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt +++ b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing.client @@ -33,7 +33,9 @@ internal class TestEngineWebsocketSession( outgoing.invokeOnClose { if (it != null) { socketJob.completeExceptionally(it) - } else socketJob.complete() + } else { + socketJob.complete() + } } socketJob.join() } diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeJvm.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeJvm.kt index 17f266f4f9a..7ff3be1d161 100644 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeJvm.kt +++ b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeJvm.kt @@ -2,7 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.server.testing.client import io.ktor.client.engine.* diff --git a/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeNix.kt b/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeNix.kt index b64c2a948f1..69a9964c3b9 100644 --- a/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeNix.kt +++ b/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/client/TestHttpClientEngineBridgeNix.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing.client diff --git a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt index d7e1469c61d..01c2e74bf27 100644 --- a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt +++ b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt @@ -314,7 +314,6 @@ abstract class HttpServerJvmTestSuite() @@ -497,9 +496,13 @@ abstract class HttpServerJvmTestSuite) = responses.filterNot { line -> - line.startsWith("Date") || line.startsWith("Server") || - line.startsWith("Content-") || line.toIntOrNull() != null || - line.isBlank() || line.startsWith("Connection") || line.startsWith("Keep-Alive") + line.startsWith("Date") || + line.startsWith("Server") || + line.startsWith("Content-") || + line.toIntOrNull() != null || + line.isBlank() || + line.startsWith("Connection") || + line.startsWith("Keep-Alive") } .map { it.trim() } .joinToString(separator = "\n") diff --git a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt index fafa55381d4..aac0cab8d0e 100644 --- a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt +++ b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt @@ -506,7 +506,7 @@ abstract class SustainabilityTestSuite val server = createServer(log = logger) { intercept(phase) { diff --git a/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt b/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt index 920a0f382a7..30249e5b72e 100644 --- a/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt +++ b/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt @@ -684,15 +684,17 @@ abstract class WebSocketEngineSuite continue@loop - is Frame.Close -> { - assertEquals(closeCode, frame.readReason()?.code) - if (replyCloseFrame) socket.close() - break@loop - } + while (true) { + when (val frame = input.readFrame(Long.MAX_VALUE, 0)) { + is Frame.Ping -> continue@loop + is Frame.Close -> { + assertEquals(closeCode, frame.readReason()?.code) + if (replyCloseFrame) socket.close() + break@loop + } - else -> fail("Unexpected frame $frame: \n${hex(frame.data)}") + else -> fail("Unexpected frame $frame: \n${hex(frame.data)}") + } } } @@ -730,10 +732,12 @@ abstract class WebSocketEngineSuite return sb.toString() - 0x0d -> {} - else -> sb.append(rc.toChar()) + while (true) { + when (val rc = readByte().toInt()) { + -1, 0x0a -> return sb.toString() + 0x0d -> {} + else -> sb.append(rc.toChar()) + } } } diff --git a/ktor-server/ktor-server-tests/common/src/Stub.kt b/ktor-server/ktor-server-tests/common/src/Stub.kt index b48bfaacd20..0ff3ed10564 100644 --- a/ktor-server/ktor-server-tests/common/src/Stub.kt +++ b/ktor-server/ktor-server-tests/common/src/Stub.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.server.tests internal fun stub() { diff --git a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ApplicationRequestContentTest.kt b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ApplicationRequestContentTest.kt index 1de839e7cfa..65c9ab6b758 100644 --- a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ApplicationRequestContentTest.kt +++ b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ApplicationRequestContentTest.kt @@ -211,7 +211,6 @@ class ApplicationRequestContentTest { } } - @OptIn(ExperimentalStdlibApi::class) @Test fun testDoubleReceiveChannels() = testApplication { install(DoubleReceive) diff --git a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/RespondFunctionsTest.kt b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/RespondFunctionsTest.kt index 9ba80165c9e..827d7c24f2b 100644 --- a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/RespondFunctionsTest.kt +++ b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/RespondFunctionsTest.kt @@ -29,7 +29,10 @@ class RespondFunctionsTest { call.respondBytes { ByteArray(10) { it.toByte() } } } get("/bytes-writer") { - call.respondBytesWriter(contentLength = 2) { writeByte(1); writeByte(2) } + call.respondBytesWriter(contentLength = 2) { + writeByte(1) + writeByte(2) + } } } diff --git a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ServerURLBuilderTest.kt b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ServerURLBuilderTest.kt index 1e97913873d..f1de95d6929 100644 --- a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ServerURLBuilderTest.kt +++ b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/http/ServerURLBuilderTest.kt @@ -10,8 +10,10 @@ import io.ktor.server.application.* import io.ktor.server.plugins.forwardedheaders.* import io.ktor.server.testing.* import io.ktor.server.util.* -import kotlin.test.* +import kotlin.test.Test +import kotlin.test.assertEquals +@Suppress("ktlint:standard:statement-wrapping") class ServerURLBuilderTest { @Test diff --git a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/plugins/ConditionalHeadersTests.kt b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/plugins/ConditionalHeadersTests.kt index 00b500ed172..08b2dad2b39 100644 --- a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/plugins/ConditionalHeadersTests.kt +++ b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/plugins/ConditionalHeadersTests.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.plugins diff --git a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/routing/RoutingResolveTest.kt b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/routing/RoutingResolveTest.kt index eb1432b0b1d..34a8c6e3342 100644 --- a/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/routing/RoutingResolveTest.kt +++ b/ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/routing/RoutingResolveTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.routing @@ -7,7 +7,7 @@ package io.ktor.tests.server.routing import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* -import io.ktor.server.application.Application +import io.ktor.server.application.* import io.ktor.server.plugins.* import io.ktor.server.response.* import io.ktor.server.routing.* @@ -171,7 +171,7 @@ class RoutingResolveTest { } @Test - fun routing_with_foo() = testRouting() { root -> + fun routing_with_foo() = testRouting { root -> val fooEntry = root.handle(PathSegmentConstantRouteSelector("foo")) on("resolving /foo") { diff --git a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/ApplicationRequestContentTestJvm.kt b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/ApplicationRequestContentTestJvm.kt index b2b47d6f9f3..a75f2b33dcd 100644 --- a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/ApplicationRequestContentTestJvm.kt +++ b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/ApplicationRequestContentTestJvm.kt @@ -2,7 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -// ktlint-disable filename package io.ktor.server.http import io.ktor.client.request.* diff --git a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/MultipartServerTest.kt b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/MultipartServerTest.kt index 4200e9f7081..7bd70cc92ca 100644 --- a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/MultipartServerTest.kt +++ b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/MultipartServerTest.kt @@ -55,8 +55,9 @@ class MultipartServerTest { val partData = InputProvider(size = null) { Buffer().apply { - for (i in 0 until TEST_FILE_SIZE) + for (i in 0 until TEST_FILE_SIZE) { writeByte(i.toByte()) + } } } val timeTaken = measureTime { diff --git a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/RespondFunctionsJvmTest.kt b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/RespondFunctionsJvmTest.kt index c5d9217724c..89524de95bd 100644 --- a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/RespondFunctionsJvmTest.kt +++ b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/RespondFunctionsJvmTest.kt @@ -19,10 +19,16 @@ class RespondFunctionsJvmTest { fun testRespondBytes() = testApplication { routing { get("/output-stream") { - call.respondOutputStream(contentLength = 2) { write(1); write(2) } + call.respondOutputStream(contentLength = 2) { + write(1) + write(2) + } } get("/text-writer") { - call.respondTextWriter(contentLength = 2) { write(1); write(2) } + call.respondTextWriter(contentLength = 2) { + write(1) + write(2) + } } } diff --git a/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/Embedded.kt b/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/Embedded.kt index 9cf99f151bb..0f418a11c38 100644 --- a/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/Embedded.kt +++ b/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/Embedded.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.tomcat.jakarta diff --git a/ktor-server/ktor-server-tomcat/jvm/src/io/ktor/server/tomcat/Embedded.kt b/ktor-server/ktor-server-tomcat/jvm/src/io/ktor/server/tomcat/Embedded.kt index 9325996582c..d6c2b3b1e3e 100644 --- a/ktor-server/ktor-server-tomcat/jvm/src/io/ktor/server/tomcat/Embedded.kt +++ b/ktor-server/ktor-server-tomcat/jvm/src/io/ktor/server/tomcat/Embedded.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.tomcat diff --git a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/ErrorCollector.kt b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/ErrorCollector.kt index a699d48fc0d..e83fd31f82e 100644 --- a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/ErrorCollector.kt +++ b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/ErrorCollector.kt @@ -42,8 +42,9 @@ class ErrorCollector : TestExecutionExceptionHandler, ParameterResolver, AfterEa currentErrors.isEmpty() -> {} currentErrors.size == 1 -> throw currentErrors.single() else -> { - for (e in currentErrors) + for (e in currentErrors) { e.printStackTrace() + } throw MultipleFailureException(currentErrors) } diff --git a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/coroutines/CoroutinesTimeoutExtension.kt b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/coroutines/CoroutinesTimeoutExtension.kt index a8e0f9fe43a..2e3a3c9f3e7 100644 --- a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/coroutines/CoroutinesTimeoutExtension.kt +++ b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/coroutines/CoroutinesTimeoutExtension.kt @@ -2,6 +2,7 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:Suppress("ktlint") @file:OptIn(ExperimentalCoroutinesApi::class) package io.ktor.junit.coroutines @@ -20,8 +21,6 @@ import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean -/* ktlint-disable */ - //---------------------------------------------------------------------------------------------------------------------- // The implementation was copied from kotlinx.coroutines with Java 8 compatibility fixes // TODO: Remove as soon as https://github.com/Kotlin/kotlinx.coroutines/issues/4278 is fixed @@ -361,7 +360,8 @@ internal class CoroutinesTimeoutExtension internal constructor( ): T = runWithTimeoutDumpingCoroutines( methodName, testTimeoutMs, cancelOnTimeout, - { CoroutinesTimeoutException(testTimeoutMs) }, { invocation.proceed() }) + { CoroutinesTimeoutException(testTimeoutMs) }, { invocation.proceed() } + ) } @@ -440,5 +440,3 @@ private fun Throwable.attachStacktraceFrom(thread: Thread) { val stackTrace = thread.stackTrace this.stackTrace = stackTrace } - -/* ktlint-disable */ diff --git a/ktor-shared/ktor-serialization/common/src/ContentConverter.kt b/ktor-shared/ktor-serialization/common/src/ContentConverter.kt index e3bec258d9a..ee28a7eb330 100644 --- a/ktor-shared/ktor-serialization/common/src/ContentConverter.kt +++ b/ktor-shared/ktor-serialization/common/src/ContentConverter.kt @@ -62,9 +62,11 @@ public fun Headers.suitableCharset(defaultCharset: Charset = Charsets.UTF_8): Ch * Detect suitable charset for an application call by `Accept` header or fallback to null */ public fun Headers.suitableCharsetOrNull(defaultCharset: Charset = Charsets.UTF_8): Charset? { - for ((charset, _) in parseAndSortHeader(get(HttpHeaders.AcceptCharset))) when { - charset == "*" -> return defaultCharset - Charsets.isSupported(charset) -> return Charsets.forName(charset) + for ((charset, _) in parseAndSortHeader(get(HttpHeaders.AcceptCharset))) { + when { + charset == "*" -> return defaultCharset + Charsets.isSupported(charset) -> return Charsets.forName(charset) + } } return null } diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborContextualSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborContextualSerializationTest.kt index ba9e7d46055..f2760963682 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborContextualSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborContextualSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborSerializationTest.kt index ed059822c28..fd2c51964a9 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/common/test/CborSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborClientKotlinxSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborClientKotlinxSerializationTest.kt index 307a4975d3a..a1fb262589b 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborClientKotlinxSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborClientKotlinxSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.cbor import io.ktor.client.plugins.contentnegotiation.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborServerKotlinxSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborServerKotlinxSerializationTest.kt index 39fd578d103..d88f0f4e301 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborServerKotlinxSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborServerKotlinxSerializationTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.serialization.kotlinx.test.cbor import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonContextualSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonContextualSerializationTest.kt index 63be74d9ced..e331e6d60f6 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonContextualSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonContextualSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonSerializationTest.kt index 1029795ec13..0b008a008b9 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.client.engine.mock.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationJsonJvmTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationJsonJvmTest.kt index 579a737fa43..c230339c4aa 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationJsonJvmTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationJsonJvmTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.client.call.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationTest.kt index e23918fc38a..7ef2684c450 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonClientKotlinxSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.client.plugins.contentnegotiation.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonServerKotlinxSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonServerKotlinxSerializationTest.kt index 7170edbf1dd..f46595cc22b 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonServerKotlinxSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/jvm/test/JsonServerKotlinxSerializationTest.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.serialization.kotlinx.test.json import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractContextualSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractContextualSerializationTest.kt index 11ac94f6221..1059dd3f274 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractContextualSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractContextualSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test import io.ktor.http.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractSerializationTest.kt index b570adf533e..39cd3128748 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/common/src/AbstractSerializationTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test import io.ktor.http.* @@ -135,7 +136,7 @@ public abstract class AbstractSerializationTest { } } - @OptIn(DelicateCoroutinesApi::class, InternalAPI::class) + @OptIn(DelicateCoroutinesApi::class) protected suspend inline fun ContentConverter.testSerialize(data: T): ByteArray { return when ( val content = diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/jvm/src/AbstractServerSerializationKotlinxTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/jvm/src/AbstractServerSerializationKotlinxTest.kt index 4b9c6d696b2..67b0dd4e3d9 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/jvm/src/AbstractServerSerializationKotlinxTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-tests/jvm/src/AbstractServerSerializationKotlinxTest.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.kotlinx.test import io.ktor.serialization.test.* diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/posix/src/io/ktor/serialization/kotlinx/ExtensionsNative.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/posix/src/io/ktor/serialization/kotlinx/ExtensionsNative.kt index 61275cedfeb..955bd03ae3c 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/posix/src/io/ktor/serialization/kotlinx/ExtensionsNative.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/posix/src/io/ktor/serialization/kotlinx/ExtensionsNative.kt @@ -6,6 +6,7 @@ package io.ktor.serialization.kotlinx import io.ktor.utils.io.* +@Suppress("ObjectPropertyName") private val _providers: MutableList = mutableListOf() internal actual val providers: List = _providers diff --git a/ktor-shared/ktor-serialization/ktor-serialization-tests/jvm/src/AbstractServerSerializationTest.kt b/ktor-shared/ktor-serialization/ktor-serialization-tests/jvm/src/AbstractServerSerializationTest.kt index 511d3548b32..9233683cbd4 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-tests/jvm/src/AbstractServerSerializationTest.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-tests/jvm/src/AbstractServerSerializationTest.kt @@ -1,6 +1,7 @@ /* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.serialization.test import io.ktor.client.request.* diff --git a/ktor-shared/ktor-websockets/common/src/io/ktor/websocket/RawWebSocketCommon.kt b/ktor-shared/ktor-websockets/common/src/io/ktor/websocket/RawWebSocketCommon.kt index e9287386727..24d8d214d28 100644 --- a/ktor-shared/ktor-websockets/common/src/io/ktor/websocket/RawWebSocketCommon.kt +++ b/ktor-shared/ktor-websockets/common/src/io/ktor/websocket/RawWebSocketCommon.kt @@ -33,7 +33,7 @@ public expect fun RawWebSocket( coroutineContext: CoroutineContext ): WebSocketSession -@OptIn(ExperimentalCoroutinesApi::class, InternalAPI::class) +@OptIn(InternalAPI::class) internal class RawWebSocketCommon( private val input: ByteReadChannel, private val output: ByteWriteChannel, @@ -55,18 +55,20 @@ internal class RawWebSocketCommon( private val writerJob = launch(context = CoroutineName("ws-writer"), start = CoroutineStart.ATOMIC) { try { - mainLoop@ while (true) when (val message = _outgoing.receive()) { - is Frame -> { - output.writeFrame(message, masking) - output.flush() - if (message is Frame.Close) break@mainLoop + mainLoop@ while (true) { + when (val message = _outgoing.receive()) { + is Frame -> { + output.writeFrame(message, masking) + output.flush() + if (message is Frame.Close) break@mainLoop + } + + is FlushRequest -> { + message.complete() + } + + else -> throw IllegalArgumentException("unknown message $message") } - - is FlushRequest -> { - message.complete() - } - - else -> throw IllegalArgumentException("unknown message $message") } _outgoing.close() } catch (cause: ChannelWriteException) { @@ -79,9 +81,11 @@ internal class RawWebSocketCommon( output.flushAndClose() } - while (true) when (val message = _outgoing.tryReceive().getOrNull() ?: break) { - is FlushRequest -> message.complete() - else -> {} + while (true) { + when (val message = _outgoing.tryReceive().getOrNull() ?: break) { + is FlushRequest -> message.complete() + else -> {} + } } } diff --git a/ktor-shared/ktor-websockets/jsAndWasmShared/src/io/ktor/websocket/FrameJs.kt b/ktor-shared/ktor-websockets/jsAndWasmShared/src/io/ktor/websocket/FrameJs.kt index 151ce6b0e81..dd40a1e5ec7 100644 --- a/ktor-shared/ktor-websockets/jsAndWasmShared/src/io/ktor/websocket/FrameJs.kt +++ b/ktor-shared/ktor-websockets/jsAndWasmShared/src/io/ktor/websocket/FrameJs.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket diff --git a/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketReader.kt b/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketReader.kt index 681e3cca740..2e7d11b75d8 100644 --- a/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketReader.kt +++ b/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketReader.kt @@ -34,7 +34,6 @@ public class WebSocketReader( private val queue = Channel(8) - @OptIn(ExperimentalCoroutinesApi::class) private val readerJob = launch(CoroutineName("ws-reader"), start = CoroutineStart.ATOMIC) { val buffer = pool.borrow() try { diff --git a/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketWriter.kt b/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketWriter.kt index cb54e8d4f37..4671eec6931 100644 --- a/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketWriter.kt +++ b/ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/WebSocketWriter.kt @@ -35,7 +35,6 @@ public class WebSocketWriter( */ public val outgoing: SendChannel get() = queue - @OptIn(ExperimentalCoroutinesApi::class) private val writeLoopJob = launch(context = CoroutineName("ws-writer"), start = CoroutineStart.ATOMIC) { pool.useInstance { writeLoop(it) } } diff --git a/ktor-shared/ktor-websockets/posix/src/io/ktor/websocket/FrameNative.kt b/ktor-shared/ktor-websockets/posix/src/io/ktor/websocket/FrameNative.kt index 0ba4945ca75..fbbe55569ac 100644 --- a/ktor-shared/ktor-websockets/posix/src/io/ktor/websocket/FrameNative.kt +++ b/ktor-shared/ktor-websockets/posix/src/io/ktor/websocket/FrameNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket diff --git a/ktor-test-dispatcher/common/src/TestCommon.kt b/ktor-test-dispatcher/common/src/TestCommon.kt index 9f7ffedc5ec..f7d63b7c8fd 100644 --- a/ktor-test-dispatcher/common/src/TestCommon.kt +++ b/ktor-test-dispatcher/common/src/TestCommon.kt @@ -30,7 +30,6 @@ public expect fun testSuspend( // kotlinx.coroutines.test.runTest uses `virtual` time by default, which is not what we want sometimes // probably in almost all places it should be fine to use virtual time // and change dispatcher in those places where needed -@OptIn(ExperimentalCoroutinesApi::class) public fun runTestWithRealTime( context: CoroutineContext = EmptyCoroutineContext, timeout: Duration = 60.seconds, diff --git a/ktor-test-dispatcher/js/src/TestJs.kt b/ktor-test-dispatcher/js/src/TestJs.kt index 3326f331558..f5d9470c119 100644 --- a/ktor-test-dispatcher/js/src/TestJs.kt +++ b/ktor-test-dispatcher/js/src/TestJs.kt @@ -13,7 +13,6 @@ import kotlin.time.Duration.Companion.milliseconds /** * Test runner for js suspend tests. */ -@OptIn(DelicateCoroutinesApi::class) public actual fun testSuspend( context: CoroutineContext, timeoutMillis: Long, diff --git a/ktor-test-dispatcher/wasmJs/src/TestWasm.kt b/ktor-test-dispatcher/wasmJs/src/TestWasm.kt index 8ddf414d844..3d749100c99 100644 --- a/ktor-test-dispatcher/wasmJs/src/TestWasm.kt +++ b/ktor-test-dispatcher/wasmJs/src/TestWasm.kt @@ -12,7 +12,6 @@ import kotlin.time.* /** * Test runner for js suspend tests. */ -@OptIn(DelicateCoroutinesApi::class) public actual fun testSuspend( context: CoroutineContext, timeoutMillis: Long, diff --git a/ktor-utils/common/src/io/ktor/util/ByteChannels.kt b/ktor-utils/common/src/io/ktor/util/ByteChannels.kt index 75a6db8bbc5..781945e4f05 100644 --- a/ktor-utils/common/src/io/ktor/util/ByteChannels.kt +++ b/ktor-utils/common/src/io/ktor/util/ByteChannels.kt @@ -15,7 +15,6 @@ private const val CHUNK_BUFFER_SIZE = 4096L * Split source [ByteReadChannel] into 2 new ones. * Cancel of one channel in split (input or both outputs) cancels other channels. */ -@OptIn(InternalAPI::class) public fun ByteReadChannel.split(coroutineScope: CoroutineScope): Pair { val first = ByteChannel(autoFlush = true) val second = ByteChannel(autoFlush = true) diff --git a/ktor-utils/common/src/io/ktor/util/CaseInsensitiveSet.kt b/ktor-utils/common/src/io/ktor/util/CaseInsensitiveSet.kt index bd1c4058bf1..8c1da1e7ac2 100644 --- a/ktor-utils/common/src/io/ktor/util/CaseInsensitiveSet.kt +++ b/ktor-utils/common/src/io/ktor/util/CaseInsensitiveSet.kt @@ -1,6 +1,7 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + package io.ktor.util import io.ktor.utils.io.* diff --git a/ktor-utils/common/src/io/ktor/util/StringValues.kt b/ktor-utils/common/src/io/ktor/util/StringValues.kt index 6d35802e65d..7d625196f5d 100644 --- a/ktor-utils/common/src/io/ktor/util/StringValues.kt +++ b/ktor-utils/common/src/io/ktor/util/StringValues.kt @@ -280,7 +280,10 @@ public open class StringValuesBuilderImpl( } private fun ensureListForKey(name: String): MutableList { - return values[name] ?: mutableListOf().also { validateName(name); values[name] = it } + return values[name] ?: mutableListOf().also { + validateName(name) + values[name] = it + } } } diff --git a/ktor-utils/common/src/io/ktor/util/date/Date.kt b/ktor-utils/common/src/io/ktor/util/date/Date.kt index 2d789cead0a..885b8fd076b 100644 --- a/ktor-utils/common/src/io/ktor/util/date/Date.kt +++ b/ktor-utils/common/src/io/ktor/util/date/Date.kt @@ -7,10 +7,7 @@ package io.ktor.util.date import kotlinx.serialization.* import kotlin.time.* -/** - * According to: - * http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html - */ +// According to: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html /** * Day of week diff --git a/ktor-utils/common/src/io/ktor/util/internal/LockFreeLinkedList.kt b/ktor-utils/common/src/io/ktor/util/internal/LockFreeLinkedList.kt index 311e211b4e2..edd2a6c3b7c 100644 --- a/ktor-utils/common/src/io/ktor/util/internal/LockFreeLinkedList.kt +++ b/ktor-utils/common/src/io/ktor/util/internal/LockFreeLinkedList.kt @@ -4,8 +4,9 @@ package io.ktor.util.internal -import kotlinx.atomicfu.* -import kotlin.jvm.* +import kotlinx.atomicfu.atomic +import kotlinx.atomicfu.loop +import kotlin.jvm.JvmField /* * Copied from kotlinx.coroutines @@ -74,16 +75,16 @@ private val NO_DECISION: Any = Symbol("NO_DECISION") * @suppress **This is unstable API and it is subject to change.** */ public abstract class AtomicOp : OpDescriptor() { - private val _consensus = atomic(NO_DECISION) + private val consensus = atomic(NO_DECISION) - public val isDecided: Boolean get() = _consensus.value !== NO_DECISION + public val isDecided: Boolean get() = consensus.value !== NO_DECISION public fun tryDecide(decision: Any?): Boolean { check(decision !== NO_DECISION) - return _consensus.compareAndSet(NO_DECISION, decision) + return consensus.compareAndSet(NO_DECISION, decision) } - private fun decide(decision: Any?): Any? = if (tryDecide(decision)) decision else _consensus.value + private fun decide(decision: Any?): Any? = if (tryDecide(decision)) decision else consensus.value public abstract fun prepare(affected: T): Any? // `null` if Ok, or failure reason @@ -92,8 +93,8 @@ public abstract class AtomicOp : OpDescriptor() { // returns `null` on success @Suppress("UNCHECKED_CAST") public final override fun perform(affected: Any?): Any? { - // make decision on status - var decision = this._consensus.value + // make a decision on status + var decision = consensus.value if (decision === NO_DECISION) { decision = decide(prepare(affected as T)) } @@ -142,10 +143,10 @@ public open class LockFreeLinkedListNode { private val _prev = atomic(this) // lazily cached removed ref to this - private val _removedRef = atomic(null) + private val removedRef = atomic(null) private fun removed(): Removed = - _removedRef.value ?: Removed(this).also { _removedRef.lazySet(it) } + removedRef.value ?: Removed(this).also { removedRef.lazySet(it) } @PublishedApi internal abstract class CondAddOp( @@ -250,13 +251,22 @@ public open class LockFreeLinkedListNode { } } + /** + * Adds the specified [node] at the end of the list atomically if the previous node matches the given [predicate]. + * + * @param node the node to be added + * @param predicate a function that evaluates the previous node + * @param condition an atomic condition that must be `true` for the node to be added + * @return `true` if the node was added, `false` otherwise + */ public inline fun addLastIfPrevAndIf( node: Node, - predicate: (Node) -> Boolean, // prev node predicate - crossinline condition: () -> Boolean // atomically checked condition + predicate: (Node) -> Boolean, + crossinline condition: () -> Boolean, ): Boolean { val condAdd = makeCondAddOp(node, condition) - while (true) { // lock-free loop on prev.next + // lock-free loop on prev.next + while (true) { val prev = prev as Node // sentinel node is never removed, so prev is always defined if (!predicate(prev)) return false when (prev.tryCondAddNext(node, this, condAdd)) { @@ -578,8 +588,8 @@ public open class LockFreeLinkedListNode { final override fun complete(op: AtomicOp<*>, failure: Any?) { val success = failure == null - val affectedNode = affectedNode ?: run { check(!success); return } - val originalNext = originalNext ?: run { check(!success); return } + val affectedNode = affectedNode ?: return check(!success) + val originalNext = originalNext ?: return check(!success) val update = if (success) updatedNext(affectedNode, originalNext) else originalNext if (affectedNode._next.compareAndSet(op, update)) { if (success) finishOnSuccess(affectedNode, originalNext) diff --git a/ktor-utils/common/src/io/ktor/util/pipeline/Pipeline.kt b/ktor-utils/common/src/io/ktor/util/pipeline/Pipeline.kt index 1617d932e2b..a03265f5637 100644 --- a/ktor-utils/common/src/io/ktor/util/pipeline/Pipeline.kt +++ b/ktor-utils/common/src/io/ktor/util/pipeline/Pipeline.kt @@ -59,14 +59,7 @@ public open class Pipeline( public val isEmpty: Boolean get() = interceptorsQuantity == 0 - private val _interceptors: AtomicRef>?> = - atomic(null) - - private var interceptors: List>? - get() = _interceptors.value - set(value) { - _interceptors.value = value - } + private var interceptors: List>? by atomic(null) private var interceptorsListShared: Boolean = false diff --git a/ktor-utils/common/test/io/ktor/util/ChannelTest.kt b/ktor-utils/common/test/io/ktor/util/ChannelTest.kt index 1eccc15a610..29c5f4c8d15 100644 --- a/ktor-utils/common/test/io/ktor/util/ChannelTest.kt +++ b/ktor-utils/common/test/io/ktor/util/ChannelTest.kt @@ -119,7 +119,7 @@ class ChannelTest { } } - @OptIn(DelicateCoroutinesApi::class, InternalAPI::class) + @OptIn(DelicateCoroutinesApi::class) @Test fun testCopyToBothCancelSecondReader() = testSuspend { val data = ByteArray(16 * 1024 * 1024) { it.toByte() } diff --git a/ktor-utils/common/test/io/ktor/util/PipelineContractsTest.kt b/ktor-utils/common/test/io/ktor/util/PipelineContractsTest.kt index 19cada92422..8f717cffb6d 100644 --- a/ktor-utils/common/test/io/ktor/util/PipelineContractsTest.kt +++ b/ktor-utils/common/test/io/ktor/util/PipelineContractsTest.kt @@ -19,8 +19,14 @@ class PipelineContractsTest { private val phase1 = PipelinePhase("A") private val phase2 = PipelinePhase("B") - private val interceptor1: PipelineInterceptor = { v = 1; checkList.add("1") } - private val interceptor2: PipelineInterceptor = { v = 2; checkList.add("2") } + private val interceptor1: PipelineInterceptor = { + v = 1 + checkList.add("1") + } + private val interceptor2: PipelineInterceptor = { + v = 2 + checkList.add("2") + } @Test fun testMergeEmpty() { diff --git a/ktor-utils/js/src/io/ktor/util/PlatformUtils.js.kt b/ktor-utils/js/src/io/ktor/util/PlatformUtils.js.kt index 55644611118..7ddcdb1518b 100644 --- a/ktor-utils/js/src/io/ktor/util/PlatformUtils.js.kt +++ b/ktor-utils/js/src/io/ktor/util/PlatformUtils.js.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.util diff --git a/ktor-utils/js/src/io/ktor/util/date/DateJs.kt b/ktor-utils/js/src/io/ktor/util/date/DateJs.kt index 5036aa47356..15530a93039 100644 --- a/ktor-utils/js/src/io/ktor/util/date/DateJs.kt +++ b/ktor-utils/js/src/io/ktor/util/date/DateJs.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.date @@ -16,7 +16,7 @@ public actual fun GMTDate(timestamp: Long?): GMTDate { if (date.getTime().isNaN()) throw InvalidTimestampException(timestamp!!) with(date) { - /* from SUNDAY 0 -> MONDAY 0 */ + // from SUNDAY 0 -> MONDAY 0 val dayOfWeek = WeekDay.from((getUTCDay() + 6) % 7) val month = Month.from(getUTCMonth()) diff --git a/ktor-utils/jsAndWasmShared/src/io/ktor/util/CryptoJs.kt b/ktor-utils/jsAndWasmShared/src/io/ktor/util/CryptoJs.kt index 9460e953f3e..144934773e3 100644 --- a/ktor-utils/jsAndWasmShared/src/io/ktor/util/CryptoJs.kt +++ b/ktor-utils/jsAndWasmShared/src/io/ktor/util/CryptoJs.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.util @@ -40,6 +40,7 @@ public actual fun Digest(name: String): Digest = object : Digest { // Variable is renamed to `_crypto` so it wouldn't clash with existing `crypto` variable. // JS IR backend doesn't reserve names accessed inside js("") calls +@Suppress("ObjectPropertyName") private val _crypto: Crypto = js("(globalThis ? globalThis.crypto : (window.crypto || window.msCrypto))") private external class Crypto { diff --git a/ktor-utils/jsAndWasmShared/src/io/ktor/util/PlatformUtilsJs.kt b/ktor-utils/jsAndWasmShared/src/io/ktor/util/PlatformUtilsJs.kt index 9f1f57d862d..871652d0c4b 100644 --- a/ktor-utils/jsAndWasmShared/src/io/ktor/util/PlatformUtilsJs.kt +++ b/ktor-utils/jsAndWasmShared/src/io/ktor/util/PlatformUtilsJs.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.util diff --git a/ktor-utils/jsAndWasmShared/src/io/ktor/util/collections/ConcurrentMapJs.kt b/ktor-utils/jsAndWasmShared/src/io/ktor/util/collections/ConcurrentMapJs.kt index e27709fca72..ab18a4f3928 100644 --- a/ktor-utils/jsAndWasmShared/src/io/ktor/util/collections/ConcurrentMapJs.kt +++ b/ktor-utils/jsAndWasmShared/src/io/ktor/util/collections/ConcurrentMapJs.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.collections diff --git a/ktor-utils/jsAndWasmShared/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJs.kt b/ktor-utils/jsAndWasmShared/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJs.kt index 37f3662e8bc..614a2d07d8c 100644 --- a/ktor-utils/jsAndWasmShared/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJs.kt +++ b/ktor-utils/jsAndWasmShared/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJs.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.debug diff --git a/ktor-utils/jsAndWasmShared/src/io/ktor/util/logging/LoggerJs.kt b/ktor-utils/jsAndWasmShared/src/io/ktor/util/logging/LoggerJs.kt index 8ab1f6a5b32..43c72d4f78a 100644 --- a/ktor-utils/jsAndWasmShared/src/io/ktor/util/logging/LoggerJs.kt +++ b/ktor-utils/jsAndWasmShared/src/io/ktor/util/logging/LoggerJs.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.logging diff --git a/ktor-utils/jvm/src/io/ktor/util/collections/ConcurrentMapJvm.kt b/ktor-utils/jvm/src/io/ktor/util/collections/ConcurrentMapJvm.kt index 7d1733836c6..be5b2ae05ed 100644 --- a/ktor-utils/jvm/src/io/ktor/util/collections/ConcurrentMapJvm.kt +++ b/ktor-utils/jvm/src/io/ktor/util/collections/ConcurrentMapJvm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.collections diff --git a/ktor-utils/jvm/src/io/ktor/util/converters/ConversionServiceJvm.kt b/ktor-utils/jvm/src/io/ktor/util/converters/ConversionServiceJvm.kt index 1d177855f95..6f2a218758b 100644 --- a/ktor-utils/jvm/src/io/ktor/util/converters/ConversionServiceJvm.kt +++ b/ktor-utils/jvm/src/io/ktor/util/converters/ConversionServiceJvm.kt @@ -8,7 +8,6 @@ import java.math.* import java.util.* import kotlin.reflect.* -@OptIn(ExperimentalStdlibApi::class) internal actual fun platformDefaultFromValues(value: String, klass: KClass<*>): Any? { val converted = convertSimpleTypes(value, klass) if (converted != null) { diff --git a/ktor-utils/jvm/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJvm.kt b/ktor-utils/jvm/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJvm.kt index 13e668d6e20..04514410310 100644 --- a/ktor-utils/jvm/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJvm.kt +++ b/ktor-utils/jvm/src/io/ktor/util/debug/IntellijIdeaDebugDetectorJvm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.debug diff --git a/ktor-utils/jvm/src/io/ktor/util/logging/LoggerJvm.kt b/ktor-utils/jvm/src/io/ktor/util/logging/LoggerJvm.kt index 1c1f8c7e5bf..d3eed5767e6 100644 --- a/ktor-utils/jvm/src/io/ktor/util/logging/LoggerJvm.kt +++ b/ktor-utils/jvm/src/io/ktor/util/logging/LoggerJvm.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.logging diff --git a/ktor-utils/jvm/test/io/ktor/tests/utils/CacheTest.kt b/ktor-utils/jvm/test/io/ktor/tests/utils/CacheTest.kt index 30b2a17486d..5e3f469d3a1 100644 --- a/ktor-utils/jvm/test/io/ktor/tests/utils/CacheTest.kt +++ b/ktor-utils/jvm/test/io/ktor/tests/utils/CacheTest.kt @@ -7,15 +7,23 @@ package io.ktor.tests.utils import io.ktor.util.* import java.util.* import java.util.concurrent.atomic.AtomicInteger -import kotlin.concurrent.* -import kotlin.test.* +import kotlin.concurrent.thread +import kotlin.test.Test +import kotlin.test.assertEquals class CacheTest { @Test fun testGet() { val counter = AtomicInteger(0) - val cache = LRUCache({ counter.incrementAndGet(); it }, {}, 2) + val cache = LRUCache( + supplier = { + counter.incrementAndGet() + it + }, + close = {}, + maxSize = 2, + ) for (i in 0 until 10) { assertEquals(i, cache[i]) @@ -28,7 +36,14 @@ class CacheTest { fun testClose() { val counter = AtomicInteger(0) val lastRemoved = AtomicInteger(-1) - val cache = LRUCache({ counter.incrementAndGet(); it }, { lastRemoved.set(it) }, 2) + val cache = LRUCache( + supplier = { + counter.incrementAndGet() + it + }, + close = { lastRemoved.set(it) }, + maxSize = 2, + ) for (i in 0 until 10) { assertEquals(i, cache[i]) @@ -47,7 +62,14 @@ class CacheTest { val created = AtomicInteger(0) val closed = AtomicInteger(0) - val cache = LRUCache({ created.incrementAndGet(); it }, { closed.incrementAndGet() }, 2) + val cache = LRUCache( + supplier = { + created.incrementAndGet() + it + }, + close = { closed.incrementAndGet() }, + maxSize = 2, + ) (1..100).map { thread { @@ -68,7 +90,14 @@ class CacheTest { fun testWithoutCaching() { val counter = AtomicInteger(0) val lastRemoved = AtomicInteger(-1) - val cache = LRUCache({ counter.incrementAndGet(); it }, { lastRemoved.set(it) }, 0) + val cache = LRUCache( + supplier = { + counter.incrementAndGet() + it + }, + close = { lastRemoved.set(it) }, + maxSize = 0, + ) for (i in 0 until 10) { assertEquals(i, cache[i]) diff --git a/ktor-utils/nix/src/io/ktor/util/CryptoPosix.kt b/ktor-utils/nix/src/io/ktor/util/CryptoPosix.kt index b48538c2ea9..0cba705e08a 100644 --- a/ktor-utils/nix/src/io/ktor/util/CryptoPosix.kt +++ b/ktor-utils/nix/src/io/ktor/util/CryptoPosix.kt @@ -7,7 +7,7 @@ package io.ktor.util import kotlinx.cinterop.* import platform.posix.* -@OptIn(ExperimentalUnsignedTypes::class, UnsafeNumber::class, ExperimentalForeignApi::class) +@OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) internal actual fun secureRandom(bytes: ByteArray) { val fd = fopen("/dev/urandom", "rb") ?: return val size = bytes.size diff --git a/ktor-utils/posix/src/io/ktor/util/PlatformUtilsNative.kt b/ktor-utils/posix/src/io/ktor/util/PlatformUtilsNative.kt index d715059313b..c3972f89d26 100644 --- a/ktor-utils/posix/src/io/ktor/util/PlatformUtilsNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/PlatformUtilsNative.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.util diff --git a/ktor-utils/posix/src/io/ktor/util/collections/ConcurrentMapNative.kt b/ktor-utils/posix/src/io/ktor/util/collections/ConcurrentMapNative.kt index f1275c5c38d..daa781ce2de 100644 --- a/ktor-utils/posix/src/io/ktor/util/collections/ConcurrentMapNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/collections/ConcurrentMapNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.collections diff --git a/ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt b/ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt index c4f9f317b6e..ca8d4de7995 100644 --- a/ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt @@ -1,6 +1,7 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + package io.ktor.util.collections import io.ktor.utils.io.* @@ -21,18 +22,18 @@ private typealias Core = LockFreeMPSCQueueCore */ @InternalAPI public class LockFreeMPSCQueue { - private val _cur = atomic(Core(Core.INITIAL_CAPACITY)) + private val curRef = atomic(Core(Core.INITIAL_CAPACITY)) private val closed = atomic(0) // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) - public val isEmpty: Boolean get() = _cur.value.isEmpty + public val isEmpty: Boolean get() = curRef.value.isEmpty public val isClosed: Boolean get() = closed.value == 1 public fun close() { try { - _cur.loop { cur -> + curRef.loop { cur -> if (cur.close()) return // closed this copy - _cur.compareAndSet(cur, cur.next()) // move to next + curRef.compareAndSet(cur, cur.next()) // move to next } } finally { if (!closed.compareAndSet(0, 1)) return @@ -40,21 +41,21 @@ public class LockFreeMPSCQueue { } public fun addLast(element: E): Boolean { - _cur.loop { cur -> + curRef.loop { cur -> when (cur.addLast(element)) { Core.ADD_SUCCESS -> return true Core.ADD_CLOSED -> return false - Core.ADD_FROZEN -> _cur.compareAndSet(cur, cur.next()) // move to next + Core.ADD_FROZEN -> curRef.compareAndSet(cur, cur.next()) // move to next } } } @Suppress("UNCHECKED_CAST") public fun removeFirstOrNull(): E? { - _cur.loop { cur -> + curRef.loop { cur -> val result = cur.removeFirstOrNull() if (result !== Core.REMOVE_FROZEN) return result as E? - _cur.compareAndSet(cur, cur.next()) + curRef.compareAndSet(cur, cur.next()) } } } @@ -67,8 +68,8 @@ public class LockFreeMPSCQueue { */ private class LockFreeMPSCQueueCore(private val capacity: Int) { private val mask = capacity - 1 - private val _next = atomic?>(null) - private val _state = atomic(0L) + private val nextRef = atomic?>(null) + private val stateRef = atomic(0L) private val array = atomicArrayOfNulls(capacity) private fun setArrayValueHelper(index: Int, value: Any?) { @@ -81,10 +82,10 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { } // Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false) - val isEmpty: Boolean get() = _state.value.withState { head, tail -> head == tail } + val isEmpty: Boolean get() = stateRef.value.withState { head, tail -> head == tail } fun close(): Boolean { - _state.update { state -> + stateRef.update { state -> if (state and CLOSED_MASK != 0L) return true // ok - already closed if (state and FROZEN_MASK != 0L) return false // frozen -- try next state or CLOSED_MASK // try set closed bit @@ -94,20 +95,20 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { // ADD_CLOSED | ADD_FROZEN | ADD_SUCCESS fun addLast(element: E): Int { - _state.loop { state -> + stateRef.loop { state -> if (state and (FROZEN_MASK or CLOSED_MASK) != 0L) return state.addFailReason() // cannot add state.withState { head, tail -> // there could be one REMOVE element beyond head that we cannot stump up, // so we check for full queue with an extra margin of one element if ((tail + 2) and mask == head and mask) return ADD_FROZEN // overfull, so do freeze & copy val newTail = (tail + 1) and MAX_CAPACITY_MASK - if (_state.compareAndSet(state, state.updateTail(newTail))) { + if (stateRef.compareAndSet(state, state.updateTail(newTail))) { // successfully added array[tail and mask].value = element // could have been frozen & copied before this item was set -- correct it by filling placeholder var cur = this while (true) { - if (cur._state.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet + if (cur.stateRef.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet cur = cur.next().fillPlaceholder(tail, element) ?: break } return ADD_SUCCESS // added successfully @@ -140,7 +141,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { // SINGLE CONSUMER // REMOVE_FROZEN | null (EMPTY) | E (SUCCESS) fun removeFirstOrNull(): Any? { - _state.loop { state -> + stateRef.loop { state -> if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify state.withState { head, tail -> if ((tail and mask) == (head and mask)) return null // empty @@ -149,7 +150,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { if (element is Placeholder) return null // same story -- consider it not added yet // we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster val newHead = (head + 1) and MAX_CAPACITY_MASK - if (_state.compareAndSet(state, state.updateHead(newHead))) { + if (stateRef.compareAndSet(state, state.updateHead(newHead))) { array[head and mask].value = null // now can safely put null (state was updated) return element // successfully removed in fast-path } @@ -164,14 +165,14 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { } private fun removeSlowPath(oldHead: Int, newHead: Int): Core? { - _state.loop { state -> + stateRef.loop { state -> state.withState { head, _ -> check(head == oldHead) { "This queue can have only one consumer" } if (state and FROZEN_MASK != 0L) { // state was already frozen, so removed element was copied to next return next() // continue to correct head in next } - if (_state.compareAndSet(state, state.updateHead(newHead))) { + if (stateRef.compareAndSet(state, state.updateHead(newHead))) { array[head and mask].value = null // now can safely put null (state was updated) return null } @@ -182,15 +183,15 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { fun next(): LockFreeMPSCQueueCore = allocateOrGetNextCopy(markFrozen()) private fun markFrozen(): Long = - _state.updateAndGet { state -> + stateRef.updateAndGet { state -> if (state and FROZEN_MASK != 0L) return state // already marked state or FROZEN_MASK } private fun allocateOrGetNextCopy(state: Long): Core { - _next.loop { next -> + nextRef.loop { next -> if (next != null) return next // already allocated & copied - _next.compareAndSet(null, allocateNextCopy(state)) + nextRef.compareAndSet(null, allocateNextCopy(state)) } } @@ -204,7 +205,7 @@ private class LockFreeMPSCQueueCore(private val capacity: Int) { next.setArrayValueHelper(index and next.mask, value ?: Placeholder(index)) index++ } - next._state.value = state wo FROZEN_MASK + next.stateRef.value = state wo FROZEN_MASK } return next } diff --git a/ktor-utils/posix/src/io/ktor/util/debug/IntellijIdeaDebugDetectorNative.kt b/ktor-utils/posix/src/io/ktor/util/debug/IntellijIdeaDebugDetectorNative.kt index 37f3662e8bc..614a2d07d8c 100644 --- a/ktor-utils/posix/src/io/ktor/util/debug/IntellijIdeaDebugDetectorNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/debug/IntellijIdeaDebugDetectorNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.debug diff --git a/ktor-utils/posix/src/io/ktor/util/logging/LogLevelNative.kt b/ktor-utils/posix/src/io/ktor/util/logging/LogLevelNative.kt index 10c118b2592..e44d7a148f0 100644 --- a/ktor-utils/posix/src/io/ktor/util/logging/LogLevelNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/logging/LogLevelNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.logging diff --git a/ktor-utils/posix/src/io/ktor/util/logging/LoggerNative.kt b/ktor-utils/posix/src/io/ktor/util/logging/LoggerNative.kt index f75af04ea94..2a55b061d33 100644 --- a/ktor-utils/posix/src/io/ktor/util/logging/LoggerNative.kt +++ b/ktor-utils/posix/src/io/ktor/util/logging/LoggerNative.kt @@ -1,6 +1,5 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.logging diff --git a/ktor-utils/wasmJs/src/io/ktor/util/PlatformUtils.wasmJs.kt b/ktor-utils/wasmJs/src/io/ktor/util/PlatformUtils.wasmJs.kt index 247758eb317..9a9b00cd917 100644 --- a/ktor-utils/wasmJs/src/io/ktor/util/PlatformUtils.wasmJs.kt +++ b/ktor-utils/wasmJs/src/io/ktor/util/PlatformUtils.wasmJs.kt @@ -1,7 +1,6 @@ -// ktlint-disable filename /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.util diff --git a/ktor-utils/wasmJs/src/io/ktor/util/date/Date.kt b/ktor-utils/wasmJs/src/io/ktor/util/date/Date.kt index 0e522334124..25dc5097ee0 100644 --- a/ktor-utils/wasmJs/src/io/ktor/util/date/Date.kt +++ b/ktor-utils/wasmJs/src/io/ktor/util/date/Date.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.date @@ -27,6 +27,7 @@ internal external class Date() { fun getUTCSeconds(): Int companion object { + @Suppress("FunctionName") fun UTC(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Double } } diff --git a/ktor-utils/wasmJs/src/io/ktor/util/date/DateWasm.kt b/ktor-utils/wasmJs/src/io/ktor/util/date/DateWasm.kt index d1fb131ba1f..582ce8b9409 100644 --- a/ktor-utils/wasmJs/src/io/ktor/util/date/DateWasm.kt +++ b/ktor-utils/wasmJs/src/io/ktor/util/date/DateWasm.kt @@ -1,11 +1,9 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.date -import kotlin.js.* - /** * Create new gmt date from the [timestamp]. * @param timestamp is a number of epoch milliseconds (it is `now` by default). @@ -16,7 +14,7 @@ public actual fun GMTDate(timestamp: Long?): GMTDate { if (date.getTime().isNaN()) throw InvalidTimestampException(timestamp!!) with(date) { - /* from SUNDAY 0 -> MONDAY 0 */ + // from SUNDAY 0 -> MONDAY 0 val dayOfWeek = WeekDay.from((getUTCDay() + 6) % 7) val month = Month.from(getUTCMonth())