ronantakizawa/codereview-bench huggingface dataset:
Repository: ktorio/ktor
File: ktor-server/ktor-server-plugins/ktor-server-metrics-micrometer/jvm/src/io/ktor/server/metrics/micrometer/MicrometerMetrics.kt (Kotlin)

Code before:
                call.attributes.put(measureKey, CallMeasure(Timer.start(registry)))
            }
        }

        on(ResponseSent) { call ->
            call.attributes.getOrNull(measureKey)?.let { measure ->
                active?.decrementAndGet()
                measure.timer.stop(
                    Timer.builder(metricName)
                        .addDefaultTags(call, measure.throwable)
                        .apply { pluginConfig.timerBuilder(this, call, measure.throwable) }
                        .register(registry)
                )
            }
        }

        on(CallFailed) { call, cause ->
            call.attributes.getOrNull(measureKey)?.throwable = cause
            throw cause
        }

        application.monitor.subscribe(RoutingRoot.RoutingCallStarted) { call ->
            call.attributes.getOrNull(measureKey)?.let { measure ->
                measure.route = call.route.let { route ->
                    pluginConfig.transformRoute(route)
                }
            }
        }
    }

private data class CallMeasure(
    val timer: Timer.Sample,
    var route: String? = null,
    var throwable: Throwable? = null
)


Review comment (suggestion):
Minor. Let's drop `.let { ... }` here
```suggestion
                measure.route = pluginConfig.transformRoute(call.route)
```

Code after:
                call.attributes.put(measureKey, CallMeasure(Timer.start(registry)))
            }
        }

        on(ResponseSent) { call ->
            call.attributes.getOrNull(measureKey)?.let { measure ->
                active?.decrementAndGet()
                measure.timer.stop(
                    Timer.builder(metricName)
                        .addDefaultTags(call, measure.throwable)
                        .apply { pluginConfig.timerBuilder(this, call, measure.throwable) }
                        .register(registry)
                )
            }
        }

        on(CallFailed) { call, cause ->
            call.attributes.getOrNull(measureKey)?.throwable = cause
            throw cause
        }

        application.monitor.subscribe(RoutingRoot.RoutingCallStarted) { call ->
            call.attributes.getOrNull(measureKey)?.let { measure ->
                measure.route = pluginConfig.transformRoute(call.route)
            }
        }
    }

private data class CallMeasure(
    val timer: Timer.Sample,
    var route: String? = null,
    var throwable: Throwable? = null
)
Repository: ktorio/ktor
File: ktor-network/common/test/io/ktor/network/sockets/tests/TCPSocketTest.kt (Kotlin)

Code before:
                .bind("127.0.0.1", port)
            if (port == 0) {
                port = socket.port
            }
            socket.close()
            socket.awaitClosed()
        }
    }

    @Test
    fun testAutoFlush() = testSockets { selector ->
        val tcp = aSocket(selector).tcp()
        val server: ServerSocket = tcp.bind("127.0.0.1", port = 0)

        val serverConnectionPromise = async {
            server.accept()
        }

        val clientConnection = tcp.connect("127.0.0.1", port = server.port)
        val serverConnection = serverConnectionPromise.await()
        val serverInput = serverConnection.openReadChannel()

        val writeChannel = clientConnection.openWriteChannel(autoFlush = true)
        writeChannel.writeStringUtf8("Hello, world\n")
        delay(100) //wait for read to be available
        assertTrue(serverInput.availableForRead > 0)
        val message = serverInput.readUTF8Line()
        assertEquals("Hello, world", message)

        val countedWriteChannel = CountedByteWriteChannel(writeChannel)
        countedWriteChannel.writeStringUtf8("Hello again\n")
        delay(100) //wait for read to be available
        assertTrue(serverInput.availableForRead > 0)
        val message2 = serverInput.readUTF8Line()
        assertEquals("Hello again", message2)
    }
}


Review comment (suggestion):
We can avoid delays here by reading the line and letting it suspend.

```suggestion
        val message = serverInput.readUTF8Line()
        assertEquals("Hello, world", message)
```

Code after:
                .bind("127.0.0.1", port)
            if (port == 0) {
                port = socket.port
            }
            socket.close()
            socket.awaitClosed()
        }
    }

    @Test
    fun testAutoFlush() = testSockets { selector ->
        val tcp = aSocket(selector).tcp()
        val server: ServerSocket = tcp.bind("127.0.0.1", port = 0)

        val serverConnectionPromise = async {
            server.accept()
        }

        val clientConnection = tcp.connect("127.0.0.1", port = server.port)
        val serverConnection = serverConnectionPromise.await()
        val serverInput = serverConnection.openReadChannel()

        val writeChannel = clientConnection.openWriteChannel(autoFlush = true)
        writeChannel.writeStringUtf8("Hello, world\n")
        val message = serverInput.readUTF8Line()
        assertEquals("Hello, world", message)

        val countedWriteChannel = CountedByteWriteChannel(writeChannel)
        countedWriteChannel.writeStringUtf8("Hello again\n")
        val message2 = serverInput.readUTF8Line()
        assertEquals("Hello again", message2)
    }
}
Repository: ktorio/ktor
File: ktor-io/common/src/io/ktor/utils/io/ByteWriteChannel.kt (Kotlin)

Code before:
/*
 * 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

import io.ktor.utils.io.core.*
import kotlinx.io.*

/**
 * Channel for asynchronous writing of sequences of bytes.
 * This is a **single-writer channel**.
 *
 * Operations on this channel cannot be invoked concurrently, unless explicitly specified otherwise
 * in the description. Exceptions are [close] and [flush].
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.utils.io.ByteWriteChannel)
 */
public interface ByteWriteChannel {

    public val autoFlush: Boolean?

    public val isClosedForWrite: Boolean

    public val closedCause: Throwable?

    @InternalAPI
    public val writeBuffer: Sink

    public suspend fun flush()

    public suspend fun flushAndClose()

    public fun cancel(cause: Throwable?)
}

@Deprecated(
    "Async close is deprecated. Please consider replacing it with flushAndClose or cancel ",
    ReplaceWith("flushAndClose()"),
    level = DeprecationLevel.WARNING
)
public fun ByteWriteChannel.close() {
    ::flushAndClose.fireAndForget()
}

public fun ByteChannel.cancel() {

Review comment (suggestion):
Might as well use:

```
public val autoFlush: Boolean get() = false
```

A default of false seems correct in this case.

Code after:
/*
 * 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

import io.ktor.utils.io.core.*
import kotlinx.io.*

/**
 * Channel for asynchronous writing of sequences of bytes.
 * This is a **single-writer channel**.
 *
 * Operations on this channel cannot be invoked concurrently, unless explicitly specified otherwise
 * in the description. Exceptions are [close] and [flush].
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.utils.io.ByteWriteChannel)
 */
public interface ByteWriteChannel {

    public val autoFlush: Boolean
        get() = false

    public val isClosedForWrite: Boolean

    public val closedCause: Throwable?

    @InternalAPI
    public val writeBuffer: Sink

    public suspend fun flush()

    public suspend fun flushAndClose()

    public fun cancel(cause: Throwable?)
}

@Deprecated(
    "Async close is deprecated. Please consider replacing it with flushAndClose or cancel ",
    ReplaceWith("flushAndClose()"),
    level = DeprecationLevel.WARNING
)
public fun ByteWriteChannel.close() {
    ::flushAndClose.fireAndForget()
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/observer/DelegatedCall.kt (Kotlin)

Code before:
        "withResponse { content }",
        "io.ktor.client.call.withResponse"
    )
)
public fun HttpClientCall.wrapWithContent(content: ByteReadChannel): HttpClientCall = withResponse { content }

/**
 * Wrap existing [HttpClientCall] with new content produced by the given [block].
 * The [block] will be called each time the response content is requested.
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.plugins.observer.wrapWithContent)
 */
@Deprecated(
    "Use 'withResponse' instead.",
    ReplaceWith(
        "withResponse { block() }",
        "io.ktor.client.call.withResponse"
    )
)
public fun HttpClientCall.wrapWithContent(block: () -> ByteReadChannel): HttpClientCall = withResponse { block() }

/**
 * Wrap existing [HttpClientCall] with new response [content] and [headers].
 *
 * **Warning:** The content of the returned call response is non-replayable, so it can be consumed only once.
 * Consider using `wrapWithContent` with lambda instead.
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.plugins.observer.wrap)
 */
@Deprecated(
    "Use 'withResponse' instead.",
    ReplaceWith(
        "withResponse(headers) { content }",
        "io.ktor.client.call.withResponse"
    )
)
public fun HttpClientCall.wrap(content: ByteReadChannel, headers: Headers): HttpClientCall =
    withResponse(headers) { content }


Review comment (suggestion):
Oh no. I've noticed another typo here. It should be:
```suggestion
 * **Warning:** The content of the returned call response is non-replayable, so it can be consumed only once.
 * Consider using [withResponse].
```

Code after:
        "replaceResponse { content }",
        "io.ktor.client.call.replaceResponse"
    )
)
public fun HttpClientCall.wrapWithContent(content: ByteReadChannel): HttpClientCall = replaceResponse { content }

/**
 * Wrap existing [HttpClientCall] with new content produced by the given [block].
 * The [block] will be called each time the response content is requested.
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.plugins.observer.wrapWithContent)
 */
@Deprecated(
    "Use 'replaceResponse' instead.",
    ReplaceWith(
        "replaceResponse { block() }",
        "io.ktor.client.call.replaceResponse"
    )
)
public fun HttpClientCall.wrapWithContent(block: () -> ByteReadChannel): HttpClientCall = replaceResponse { block() }

/**
 * Wrap existing [HttpClientCall] with new response [content] and [headers].
 *
 * **Warning:** The content of the returned call response is non-replayable, so it can be consumed only once.
 * Consider using `replaceResponse` instead.
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.plugins.observer.wrap)
 */
@Deprecated(
    "Use 'replaceResponse' instead.",
    ReplaceWith(
        "replaceResponse(headers) { content }",
        "io.ktor.client.call.replaceResponse"
    )
)
public fun HttpClientCall.wrap(content: ByteReadChannel, headers: Headers): HttpClientCall =
    replaceResponse(headers) { content }
Repository: ktorio/ktor
File: ktor-server/ktor-server-plugins/ktor-server-i18n/jvm/src/io/ktor/i18n/I18n.kt (Kotlin)

Code before:
        }
    }
}

/**
 * Get the current accepted [locale](java.util.Locale) specified in the HTTP request
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.i18n.locale)
 */
public val ApplicationCall.locale: Locale get() = attributes[LOCALE]

/**
 * Translate a message key to an accepted language specified in HTTP request
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.i18n.i18n)
 */
public fun ApplicationCall.i18n(@PropertyKey(resourceBundle = BUNDLE_KEY) key: String): String {
    val value = attributes[RESOURCE_BUNDLE].getString(key)

    I18N_LOGGER.debug {
        "translating to $locale: $key=$value"
    }
    return value
}

internal const val BUNDLE_KEY = "messages/messages"


Review comment (suggestion):
This value is very uncommon and not recognized by IntelliJ, because Java prefers a class name and not a slash: https://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String,%20java.util.Locale,%20java.lang.ClassLoader,%20java.util.ResourceBundle.Control)

IMHO we should change the key to messages only. While we could make it configurable, IDE support requires a compile time constant.

Code after:
        }
    }
}

/**
 * Get the current accepted [locale](java.util.Locale) specified in the HTTP request
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.i18n.locale)
 */
public val ApplicationCall.locale: Locale get() = attributes[LOCALE]

/**
 * Translate a message key to an accepted language specified in HTTP request
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.i18n.i18n)
 */
public fun ApplicationCall.i18n(@PropertyKey(resourceBundle = BUNDLE_KEY) key: String): String {
    val value = attributes[RESOURCE_BUNDLE].getString(key)

    I18N_LOGGER.debug {
        "translating to $locale: $key=$value"
    }
    return value
}

internal const val BUNDLE_KEY = "messages.messages"
Repository: ktorio/ktor
File: ktor-server/ktor-server-plugins/ktor-server-i18n/build.gradle.kts (Kotlin)

Code before:
/*
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

description = "I18n support to Ktor"

plugins {
    id("ktorbuild.project.server-plugin")
}


Review comment (suggestion):
@coderabbitai, remember that syntax `jvmTest.dependencies { ... }` is preferred over `jvmTest { dependencies { ... } }` as it gives the level of nesting lower by one.

Code after:
/*
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

description = "I18n support to Ktor"

plugins {
    id("ktorbuild.project.server-plugin")
}

kotlin {
    sourceSets {
        jvmTest {
            dependencies {
                implementation(project(":ktor-server:ktor-server-plugins:ktor-server-status-pages"))
            }
        }
    }
}
Repository: ktorio/ktor
File: ktor-http/common/src/io/ktor/http/URLBuilder.kt (Kotlin)

Code before:
private fun <A : Appendable> URLBuilder.appendTo(out: A): A {
    out.append(protocol.name)

    when (protocol.name) {
        "file" -> {
            out.appendFile(host, encodedPath)
            return out
        }

        "mailto" -> {
            out.appendMailto(encodedUserAndPassword, host)
            return out
        }

        "about" -> {
            out.appendAbout(host)
            return out
        }

        "tel" -> {
            out.appendTel(host)
            return out
        }

        "data" -> {
            out.appendAbout(host) // We use the same append format as about URLs
            return out
        }
    }

    out.append("://")
    out.append(authority)

    out.appendUrlFullPath(encodedPath, encodedParameters, trailingQuery)

    if (encodedFragment.isNotEmpty()) {
        out.append('#')
        out.append(encodedFragment)
    }

    return out
}

private fun Appendable.appendMailto(encodedUser: String, host: String) {
    append(":")
    append(encodedUser)
    append(host)
}

private fun Appendable.appendFile(host: String, encodedPath: String) {
    append("://")

Review comment (suggestion):
I think we could rename `appendAbout` into something more general and remove `appendTel`

Code after:
private fun <A : Appendable> URLBuilder.appendTo(out: A): A {
    out.append(protocol.name)

    when (protocol.name) {
        "file" -> {
            out.appendFile(host, encodedPath)
            return out
        }

        "mailto" -> {
            out.appendMailto(encodedUserAndPassword, host)
            return out
        }

        "about" -> {
            out.appendPayload(host)
            return out
        }

        "tel" -> {
            out.appendPayload(host)
            return out
        }

        "data" -> {
            out.appendPayload(host)
            return out
        }
    }

    out.append("://")
    out.append(authority)

    out.appendUrlFullPath(encodedPath, encodedParameters, trailingQuery)

    if (encodedFragment.isNotEmpty()) {
        out.append('#')
        out.append(encodedFragment)
    }

    return out
}

private fun Appendable.appendMailto(encodedUser: String, host: String) {
    append(":")
    append(encodedUser)
    append(host)
}

private fun Appendable.appendFile(host: String, encodedPath: String) {
    append("://")
Repository: ktorio/ktor
File: ktor-http/common/src/io/ktor/http/URLBuilder.kt (Kotlin)

Code before:
private fun <A : Appendable> URLBuilder.appendTo(out: A): A {
    out.append(protocol.name)

    when (protocol.name) {
        "file" -> {
            out.appendFile(host, encodedPath)
            return out
        }

        "mailto" -> {
            out.appendMailto(encodedUserAndPassword, host)
            return out
        }

        "about" -> {
            out.appendPayload(host)
            return out
        }

        "tel" -> {
            out.appendPayload(host)
            return out
        }

        "data" -> {
            out.appendPayload(host) // We use the same append format as about URLs
            return out
        }
    }

    out.append("://")
    out.append(authority)

    out.appendUrlFullPath(encodedPath, encodedParameters, trailingQuery)

    if (encodedFragment.isNotEmpty()) {
        out.append('#')
        out.append(encodedFragment)
    }

    return out
}

private fun Appendable.appendMailto(encodedUser: String, host: String) {
    append(":")
    append(encodedUser)
    append(host)
}

private fun Appendable.appendFile(host: String, encodedPath: String) {
    append("://")

Review comment (suggestion):
Minor. The comment seems redundant now.
```suggestion
            out.appendPayload(host)
```

Code after:
private fun <A : Appendable> URLBuilder.appendTo(out: A): A {
    out.append(protocol.name)

    when (protocol.name) {
        "file" -> {
            out.appendFile(host, encodedPath)
            return out
        }

        "mailto" -> {
            out.appendMailto(encodedUserAndPassword, host)
            return out
        }

        "about" -> {
            out.appendPayload(host)
            return out
        }

        "tel" -> {
            out.appendPayload(host)
            return out
        }

        "data" -> {
            out.appendPayload(host)
            return out
        }
    }

    out.append("://")
    out.append(authority)

    out.appendUrlFullPath(encodedPath, encodedParameters, trailingQuery)

    if (encodedFragment.isNotEmpty()) {
        out.append('#')
        out.append(encodedFragment)
    }

    return out
}

private fun Appendable.appendMailto(encodedUser: String, host: String) {
    append(":")
    append(encodedUser)
    append(host)
}

private fun Appendable.appendFile(host: String, encodedPath: String) {
    append("://")
Repository: ktorio/ktor
File: ktor-network/posix/src/io/ktor/network/sockets/SocketAddress.nonJvm.posix.kt (Kotlin)

Code before:
/*
 * Copyright 2014-2025 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.util.NativeIPv4SocketAddress
import io.ktor.network.util.NativeIPv6SocketAddress
import io.ktor.network.util.resolve

internal actual fun InetSocketAddress.platformResolveAddress(): ByteArray? {
    return this.resolve().firstOrNull()?.let {
        when (it) {
            is NativeIPv4SocketAddress -> {
                try {
                    val octets = it.ipString.split('.', limit = 4).map { o ->
                        o.toUByte().toByte()
                    }

                    List(4) { i ->
                        octets.getOrElse(i) { 0 }
                    }.toByteArray()
                } catch (_: Throwable) {
                    null
                }
            }
            is NativeIPv6SocketAddress -> {
                try {
                    val groups = it.ipString.split(':', limit = 8)
                    val emptyGroups = 8 - groups.count { g -> g.isNotEmpty() }

                    val bytes = groups.flatMap { g ->
                        if (g.isEmpty()) {
                            List(emptyGroups * 2) { 0 }
                        } else {
                            val int = g.toInt(16)
                            listOf((int shr 8).toByte(), int.toByte())
                        }
                    }
                    List(16) { i -> bytes.getOrElse(i) { 0 } }.toByteArray()
                } catch (_: Throwable) {
                    null
                }
            }
            else -> null
        }
    }

Review comment (suggestion):
You can skip creating intermediate list here:
```kotlin
ByteArray(4) { index ->
    octets.getOrElse(index) { 0 }
}
```

Code after:
/*
 * Copyright 2014-2025 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.util.NativeIPv4SocketAddress
import io.ktor.network.util.NativeIPv6SocketAddress
import io.ktor.network.util.parseIPv4String
import io.ktor.network.util.parseIPv6String
import io.ktor.network.util.resolve

internal actual fun InetSocketAddress.platformResolveAddress(): ByteArray? {
    return this.resolve().firstOrNull()?.let {
        when (it) {
            is NativeIPv4SocketAddress -> parseIPv4String(it.ipString)
            is NativeIPv6SocketAddress -> parseIPv6String(it.ipString)
            else -> null
        }
    }
}