Browse Source

New benchmark: Vert.x Web with Kotlin coroutines (#7011)

* Copy the Vert.x Web project from /frameworks/Java/vertx-web to /frameworks/Kotlin/vertx-web-kotlin-coroutines

* Update README.md for vertx-web-kotlin-coroutines

* Initially complete the vertx-web-kotlin-coroutines project

Unnecessary `await` calls at the end of coroutines are temporarily commented out. I shall test further how much impact they have on performance.

* Add back the trailing `await`s and use `checkedCoroutineHandler` for all handlers for consistency, as they have no observable impact on performance

* Replace the `get` operators inappropriately used in routes with `get` functions
Shreck Ye 3 years ago
parent
commit
32981b5b53
22 changed files with 963 additions and 0 deletions
  1. 5 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/README.md
  2. 45 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/benchmark_config.json
  3. 72 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/build.gradle.kts
  4. 30 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/config.toml
  5. 1 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle.properties
  6. BIN
      frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle/wrapper/gradle-wrapper.jar
  7. 5 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle/wrapper/gradle-wrapper.properties
  8. 234 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/gradlew
  9. 89 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/gradlew.bat
  10. 1 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/settings.gradle.kts
  11. 9 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/conf/config.json
  12. 3 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/conf/vertx.json
  13. 287 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/App.kt
  14. 34 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/Helper.kt
  15. 13 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/Try.kt
  16. 13 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/Fortune.kt
  17. 3 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/Message.kt
  18. 13 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/World.kt
  19. 21 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/resources/templates/Fortunes.rocker.html
  20. 15 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/resources/templates/fortunes.hbs
  21. 36 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/vertx-web-kotlin-coroutines-postgres.dockerfile
  22. 34 0
      frameworks/Kotlin/vertx-web-kotlin-coroutines/vertx-web-kotlin-coroutines.dockerfile

+ 5 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/README.md

@@ -0,0 +1,5 @@
+# Vert.x Web With Kotlin Coroutines Benchmarking Test
+
+This is the Vert.x Web With Kotlin Coroutines portion of a [benchmarking test suite](../) comparing a variety of web development platforms.
+
+This project is adapted from the [Vert.x Web portion](/frameworks/Java/vertx-web), with consistent dependency versions, code converted into Kotlin, and all future compositions adapted into coroutine calls, mainly to see how much overhead Kotlin coroutines introduce. See that project for more details.

+ 45 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/benchmark_config.json

@@ -0,0 +1,45 @@
+{
+  "framework": "vertx-web-kotlin-coroutines",
+  "tests": [{
+    "default": {
+      "json_url": "/json",
+      "plaintext_url": "/plaintext",
+      "port": 8080,
+      "approach": "Realistic",
+      "classification": "Micro",
+      "database": "None",
+      "framework": "vertx-web",
+      "language": "Kotlin",
+      "flavor": "None",
+      "orm": "Raw",
+      "platform": "Vert.x",
+      "webserver": "None",
+      "os": "Linux",
+      "database_os": "Linux",
+      "display_name": "vertx-web-kotlin-coroutines",
+      "notes": "",
+      "versus": "vertx-web"
+    },
+    "postgres": {
+      "db_url": "/db",
+      "query_url": "/queries?queries=",
+      "fortune_url": "/fortunes",
+      "update_url": "/update?queries=",
+      "port": 8080,
+      "approach": "Realistic",
+      "classification": "Micro",
+      "database": "Postgres",
+      "framework": "vertx-web",
+      "language": "Kotlin",
+      "flavor": "None",
+      "orm": "Raw",
+      "platform": "Vert.x",
+      "webserver": "None",
+      "os": "Linux",
+      "database_os": "Linux",
+      "display_name": "vertx-web-kotlin-coroutines-postgres",
+      "notes": "",
+      "versus": "vertx-web-postgres"
+    }
+  }]
+}

+ 72 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/build.gradle.kts

@@ -0,0 +1,72 @@
+import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
+plugins {
+    kotlin("jvm") version "1.6.10"
+    application
+    id("nu.studer.rocker") version "3.0.4"
+    id("com.github.johnrengelman.shadow") version "7.1.2"
+}
+
+group = "io.vertx"
+version = "4.1.5"
+
+repositories {
+    mavenCentral()
+}
+
+dependencies {
+    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0")
+    implementation(platform("io.vertx:vertx-stack-depchain:$version"))
+    implementation("io.vertx:vertx-core")
+    implementation("com.fasterxml.jackson.module:jackson-module-blackbird:2.12.4")
+    implementation("io.vertx:vertx-web")
+    implementation("io.vertx:vertx-pg-client")
+    implementation("io.vertx:vertx-web-templ-rocker")
+    implementation("io.netty", "netty-transport-native-epoll", classifier = "linux-x86_64")
+    implementation("io.vertx:vertx-lang-kotlin")
+    implementation("io.vertx:vertx-lang-kotlin-coroutines")
+}
+
+rocker {
+    configurations {
+        create("main") {
+            templateDir.set(file("src/main/resources"))
+            optimize.set(true)
+            javaVersion.set("1.8")
+        }
+    }
+}
+
+tasks.withType<KotlinCompile> {
+    kotlinOptions.jvmTarget = "11"
+}
+
+
+// content below copied from the project generated by the app generator
+
+val mainVerticleName = "io.vertx.benchmark.App"
+val launcherClassName = "io.vertx.core.Launcher"
+application {
+    mainClass.set(launcherClassName)
+}
+
+tasks.withType<ShadowJar> {
+    archiveClassifier.set("fat")
+    manifest {
+        attributes(mapOf("Main-Verticle" to mainVerticleName))
+    }
+    mergeServiceFiles()
+}
+
+val watchForChange = "src/**/*"
+val doOnChange = "${projectDir}/gradlew classes"
+tasks.withType<JavaExec> {
+    args = listOf(
+        "run",
+        mainVerticleName,
+        "--redeploy=$watchForChange",
+        "--launcher-class=$launcherClassName",
+        "--on-redeploy=$doOnChange"
+    )
+}

+ 30 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/config.toml

@@ -0,0 +1,30 @@
+[framework]
+name = "vertx-web-kotlin-coroutines"
+
+[main]
+urls.plaintext = "/plaintext"
+urls.json = "/json"
+approach = "Realistic"
+classification = "Micro"
+database = "None"
+database_os = "Linux"
+os = "Linux"
+orm = "Raw"
+platform = "Vert.x"
+webserver = "None"
+versus = "vertx-web"
+
+[postgres]
+urls.db = "/db"
+urls.query = "/queries?queries="
+urls.update = "/update?queries="
+urls.fortune = "/fortunes"
+approach = "Realistic"
+classification = "Micro"
+database = "Postgres"
+database_os = "Linux"
+os = "Linux"
+orm = "Raw"
+platform = "Vert.x"
+webserver = "None"
+versus = "vertx-web-postgres"

+ 1 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle.properties

@@ -0,0 +1 @@
+kotlin.code.style=official

BIN
frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle/wrapper/gradle-wrapper.jar


+ 5 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists

+ 234 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/gradlew

@@ -0,0 +1,234 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+#   Gradle start up script for POSIX generated by Gradle.
+#
+#   Important for running:
+#
+#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+#       noncompliant, but you have some other compliant shell such as ksh or
+#       bash, then to run this script, type that shell name before the whole
+#       command line, like:
+#
+#           ksh Gradle
+#
+#       Busybox and similar reduced shells will NOT work, because this script
+#       requires all of these POSIX shell features:
+#         * functions;
+#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+#         * compound commands having a testable exit status, especially «case»;
+#         * various built-in commands including «command», «set», and «ulimit».
+#
+#   Important for patching:
+#
+#   (2) This script targets any POSIX shell, so it avoids extensions provided
+#       by Bash, Ksh, etc; in particular arrays are avoided.
+#
+#       The "traditional" practice of packing multiple parameters into a
+#       space-separated string is a well documented source of bugs and security
+#       problems, so this is (mostly) avoided, by progressively accumulating
+#       options in "$@", and eventually passing that to Java.
+#
+#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+#       see the in-line comments for details.
+#
+#       There are tweaks for specific operating systems such as AIX, CygWin,
+#       Darwin, MinGW, and NonStop.
+#
+#   (3) This script is generated from the Groovy template
+#       https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+#       within the Gradle project.
+#
+#       You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
+    [ -h "$app_path" ]
+do
+    ls=$( ls -ld "$app_path" )
+    link=${ls#*' -> '}
+    case $link in             #(
+      /*)   app_path=$link ;; #(
+      *)    app_path=$APP_HOME$link ;;
+    esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+    echo "$*"
+} >&2
+
+die () {
+    echo
+    echo "$*"
+    echo
+    exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in                #(
+  CYGWIN* )         cygwin=true  ;; #(
+  Darwin* )         darwin=true  ;; #(
+  MSYS* | MINGW* )  msys=true    ;; #(
+  NONSTOP* )        nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD=$JAVA_HOME/jre/sh/java
+    else
+        JAVACMD=$JAVA_HOME/bin/java
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD=java
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+    case $MAX_FD in #(
+      max*)
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        ulimit -n "$MAX_FD" ||
+            warn "Could not set maximum file descriptor limit to $MAX_FD"
+    esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+#   * args from the command line
+#   * the main class name
+#   * -classpath
+#   * -D...appname settings
+#   * --module-path (only if needed)
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+    JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    for arg do
+        if
+            case $arg in                                #(
+              -*)   false ;;                            # don't mess with options #(
+              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
+                    [ -e "$t" ] ;;                      #(
+              *)    false ;;
+            esac
+        then
+            arg=$( cygpath --path --ignore --mixed "$arg" )
+        fi
+        # Roll the args list around exactly as many times as the number of
+        # args, so each arg winds up back in the position where it started, but
+        # possibly modified.
+        #
+        # NB: a `for` loop captures its iteration list before it begins, so
+        # changing the positional parameters here affects neither the number of
+        # iterations, nor the values presented in `arg`.
+        shift                   # remove old arg
+        set -- "$@" "$arg"      # push replacement arg
+    done
+fi
+
+# Collect all arguments for the java command;
+#   * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+#     shell script including quotes and variable substitutions, so put them in
+#     double quotes to make sure that they get re-expanded; and
+#   * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+        "-Dorg.gradle.appname=$APP_BASE_NAME" \
+        -classpath "$CLASSPATH" \
+        org.gradle.wrapper.GradleWrapperMain \
+        "$@"
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+#   set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+        xargs -n1 |
+        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+        tr '\n' ' '
+    )" '"$@"'
+
+exec "$JAVACMD" "$@"

+ 89 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/gradlew.bat

@@ -0,0 +1,89 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem      https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

+ 1 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/settings.gradle.kts

@@ -0,0 +1 @@
+rootProject.name = "vertx-web-kotlin-coroutines-benchmark"

+ 9 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/conf/config.json

@@ -0,0 +1,9 @@
+{
+  "connection_string": "mongodb://tfb-database:27017",
+  "db_name": "hello_world",
+  "host": "tfb-database",
+  "username": "benchmarkdbuser",
+  "password": "benchmarkdbpass",
+  "database": "hello_world",
+  "maxPoolSize": 64
+}

+ 3 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/conf/vertx.json

@@ -0,0 +1,3 @@
+{
+    "preferNativeTransport": true
+}

+ 287 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/App.kt

@@ -0,0 +1,287 @@
+package io.vertx.benchmark
+
+import com.fasterxml.jackson.module.blackbird.BlackbirdModule
+import io.vertx.benchmark.model.Fortune
+import io.vertx.benchmark.model.Message
+import io.vertx.benchmark.model.World
+import io.vertx.core.Vertx
+import io.vertx.core.http.HttpHeaders
+import io.vertx.core.json.Json
+import io.vertx.core.json.JsonObject
+import io.vertx.core.json.jackson.DatabindCodec
+import io.vertx.ext.web.Route
+import io.vertx.ext.web.Router
+import io.vertx.ext.web.RoutingContext
+import io.vertx.ext.web.templ.rocker.RockerTemplateEngine
+import io.vertx.kotlin.coroutines.CoroutineVerticle
+import io.vertx.kotlin.coroutines.await
+import io.vertx.kotlin.pgclient.pgConnectOptionsOf
+import io.vertx.kotlin.sqlclient.poolOptionsOf
+import io.vertx.pgclient.PgPool
+import io.vertx.sqlclient.Tuple
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.launch
+import java.time.ZonedDateTime
+import java.time.format.DateTimeFormatter
+import kotlin.system.exitProcess
+
+class App : CoroutineVerticle() {
+    companion object {
+        init {
+            DatabindCodec.mapper().registerModule(BlackbirdModule())
+            DatabindCodec.prettyMapper().registerModule(BlackbirdModule())
+        }
+
+        private const val SERVER = "vertx-web"
+
+        // for PgClientBenchmark only
+        private const val UPDATE_WORLD = "UPDATE world SET randomnumber=$1 WHERE id=$2"
+        private const val SELECT_WORLD = "SELECT id, randomnumber from WORLD where id=$1"
+        private const val SELECT_FORTUNE = "SELECT id, message from FORTUNE"
+    }
+
+    inline fun Route.coroutineHandler(crossinline requestHandler: suspend (RoutingContext) -> Unit): Route =
+        handler { ctx -> launch { requestHandler(ctx) } }
+
+    inline fun RoutingContext.checkedRun(block: () -> Unit): Unit =
+        try {
+            block()
+        } catch (t: Throwable) {
+            fail(t)
+        }
+
+    inline fun Route.checkedCoroutineHandler(crossinline requestHandler: suspend (RoutingContext) -> Unit): Route =
+        coroutineHandler { ctx -> ctx.checkedRun { requestHandler(ctx) } }
+
+    /**
+     * PgClient implementation
+     */
+    private inner class PgClientBenchmark(vertx: Vertx, config: JsonObject) {
+        private val client: PgPool
+
+        // In order to use a template we first need to create an engine
+        private val engine: RockerTemplateEngine
+
+        init {
+            val options = with(config) {
+                pgConnectOptionsOf(
+                    cachePreparedStatements = true,
+                    host = getString("host"),
+                    port = getInteger("port", 5432),
+                    user = getString("username"),
+                    password = getString("password"),
+                    database = config.getString("database"),
+                    pipeliningLimit = 100000 // Large pipelining means less flushing and we use a single connection anyway;
+                )
+            }
+
+            client = PgPool.pool(vertx, options, poolOptionsOf(maxSize = 4))
+            engine = RockerTemplateEngine.create()
+        }
+
+        suspend fun dbHandler(ctx: RoutingContext) {
+            val result = try {
+                client
+                    .preparedQuery(SELECT_WORLD)
+                    .execute(Tuple.of(randomWorld()))
+                    .await()
+            } catch (t: Throwable) {
+                // adapted from the Java code and kept, though I don't see the purpose of this
+                t.printStackTrace()
+                throw t
+            }
+
+            val resultSet = result.iterator()
+            if (!resultSet.hasNext()) {
+                ctx.response()
+                    .setStatusCode(404)
+                    .end()
+                    .await()
+                return
+            }
+            val row = resultSet.next()
+            ctx.response()
+                .putHeader(HttpHeaders.SERVER, SERVER)
+                .putHeader(HttpHeaders.DATE, date)
+                .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+                .end(Json.encodeToBuffer(World(row.getInteger(0), row.getInteger(1))))
+                .await()
+        }
+
+        suspend fun queriesHandler(ctx: RoutingContext) {
+            val queries: Int = getQueries(ctx.request())
+            val worlds = arrayOfNulls<World>(queries)
+            val failed = booleanArrayOf(false)
+            val cnt = intArrayOf(0)
+            List(queries) {
+                async {
+                    val result = `try` { client.preparedQuery(SELECT_WORLD).execute(Tuple.of(randomWorld())).await() }
+
+                    if (!failed[0]) {
+                        if (result is Try.Failure) {
+                            failed[0] = true
+                            ctx.fail(result.throwable)
+                            return@async
+                        }
+
+                        // we need a final reference
+                        val row = (result as Try.Success).value.iterator().next()
+                        worlds[cnt[0]++] = World(row.getInteger(0), row.getInteger(1))
+
+                        // stop condition
+                        if (cnt[0] == queries) {
+                            ctx.response()
+                                .putHeader(HttpHeaders.SERVER, SERVER)
+                                .putHeader(HttpHeaders.DATE, date)
+                                .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+                                .end(Json.encodeToBuffer(worlds))
+                                .await()
+                        }
+                    }
+                }
+            }
+                .awaitAll()
+        }
+
+        suspend fun fortunesHandler(ctx: RoutingContext) {
+            val result = client.preparedQuery(SELECT_FORTUNE).execute().await()
+
+            val resultSet = result.iterator()
+            if (!resultSet.hasNext()) {
+                ctx.fail(404)
+                return
+            }
+            val fortunes = ArrayList<Fortune>()
+            while (resultSet.hasNext()) {
+                val row = resultSet.next()
+                fortunes.add(Fortune(row.getInteger(0), row.getString(1)))
+            }
+            fortunes.add(Fortune(0, "Additional fortune added at request time."))
+            fortunes.sort()
+            ctx.put("fortunes", fortunes)
+
+            // and now delegate to the engine to render it.
+            val result2 = engine.render(ctx.data(), "templates/Fortunes.rocker.html").await()
+            ctx.response()
+                .putHeader(HttpHeaders.SERVER, SERVER)
+                .putHeader(HttpHeaders.DATE, date)
+                .putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8")
+                .end(result2)
+                .await()
+        }
+
+        suspend fun updateHandler(ctx: RoutingContext) {
+            val queries = getQueries(ctx.request())
+            val worlds = arrayOfNulls<World>(queries)
+            val failed = booleanArrayOf(false)
+            val queryCount = intArrayOf(0)
+            List(worlds.size) {
+                val id = randomWorld()
+                async {
+                    val r2 = `try` { client.preparedQuery(SELECT_WORLD).execute(Tuple.of(id)).await() }
+
+                    if (!failed[0]) {
+                        if (r2 is Try.Failure) {
+                            failed[0] = true
+                            ctx.fail(r2.throwable)
+                            return@async
+                        }
+                        val row = (r2 as Try.Success).value.iterator().next()
+                        worlds[queryCount[0]++] = World(row.getInteger(0), randomWorld())
+                        if (queryCount[0] == worlds.size) {
+                            worlds.sort()
+                            val batch = ArrayList<Tuple>()
+                            for (world in worlds) {
+                                world!!
+                                batch.add(Tuple.of(world.randomNumber, world.id))
+                            }
+                            ctx.checkedRun {
+                                client.preparedQuery(UPDATE_WORLD)
+                                    .executeBatch(batch)
+                                    .await()
+                                ctx.response()
+                                    .putHeader(HttpHeaders.SERVER, SERVER)
+                                    .putHeader(HttpHeaders.DATE, date)
+                                    .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+                                    .end(Json.encodeToBuffer(worlds))
+                                    .await()
+                            }
+                        }
+                    }
+                }
+            }
+                .awaitAll()
+        }
+    }
+
+    private var date: String? = null
+    override suspend fun start() {
+        val app = Router.router(vertx)
+        // initialize the date header
+        date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now())
+        // refresh the value as a periodic task
+        vertx.setPeriodic(1000) { date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now()) }
+        val pgClientBenchmark = PgClientBenchmark(vertx, config)
+
+        /*
+         * This test exercises the framework fundamentals including keep-alive support, request routing, request header
+         * parsing, object instantiation, JSON serialization, response header generation, and request count throughput.
+         */
+        app.get("/json").checkedCoroutineHandler { ctx ->
+            ctx.response()
+                .putHeader(HttpHeaders.SERVER, SERVER)
+                .putHeader(HttpHeaders.DATE, date)
+                .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+                .end(Json.encodeToBuffer(Message("Hello, World!")))
+                .await()
+        }
+
+        /*
+         * This test exercises the framework's object-relational mapper (ORM), random number generator, database driver,
+         * and database connection pool.
+         */
+        app.get("/db").checkedCoroutineHandler { ctx -> pgClientBenchmark.dbHandler(ctx) }
+
+        /*
+         * This test is a variation of Test #2 and also uses the World table. Multiple rows are fetched to more dramatically
+         * punish the database driver and connection pool. At the highest queries-per-request tested (20), this test
+         * demonstrates all frameworks' convergence toward zero requests-per-second as database activity increases.
+         */
+        app.get("/queries").checkedCoroutineHandler { ctx -> pgClientBenchmark.queriesHandler(ctx) }
+
+        /*
+         * This test exercises the ORM, database connectivity, dynamic-size collections, sorting, server-side templates,
+         * XSS countermeasures, and character encoding.
+         */
+        app.get("/fortunes").checkedCoroutineHandler { ctx -> pgClientBenchmark.fortunesHandler(ctx) }
+
+        /*
+         * This test is a variation of Test #3 that exercises the ORM's persistence of objects and the database driver's
+         * performance at running UPDATE statements or similar. The spirit of this test is to exercise a variable number of
+         * read-then-write style database operations.
+         */
+        app.route("/update").checkedCoroutineHandler { ctx -> pgClientBenchmark.updateHandler(ctx) }
+
+        /*
+         * This test is an exercise of the request-routing fundamentals only, designed to demonstrate the capacity of
+         * high-performance platforms in particular. Requests will be sent using HTTP pipelining. The response payload is
+         * still small, meaning good performance is still necessary in order to saturate the gigabit Ethernet of the test
+         * environment.
+         */
+        app.get("/plaintext").checkedCoroutineHandler { ctx ->
+            ctx.response()
+                .putHeader(HttpHeaders.SERVER, SERVER)
+                .putHeader(HttpHeaders.DATE, date)
+                .putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
+                .end("Hello, World!")
+                .await()
+        }
+        try {
+            vertx.createHttpServer().requestHandler(app).listen(8080).await()
+        } catch (t: Throwable) {
+            t.printStackTrace()
+            exitProcess(1)
+        }
+    }
+}

+ 34 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/Helper.kt

@@ -0,0 +1,34 @@
+package io.vertx.benchmark
+
+import io.vertx.core.http.HttpServerRequest
+import java.util.*
+import kotlin.math.max
+import kotlin.math.min
+
+private val RANDOM = SplittableRandom()
+
+/**
+ * Returns the value of the "queries" getRequest parameter, which is an integer
+ * bound between 1 and 500 with a default value of 1.
+ *
+ * @param request the current HTTP request
+ * @return the value of the "queries" parameter
+ */
+fun getQueries(request: HttpServerRequest): Int {
+    val param = request.getParam("queries") ?: return 1
+    return try {
+        val parsedValue = param.toInt()
+        min(500, max(1, parsedValue))
+    } catch (e: NumberFormatException) {
+        1
+    }
+}
+
+/**
+ * Returns a random integer that is a suitable value for both the `id`
+ * and `randomNumber` properties of a world object.
+ *
+ * @return a random world number
+ */
+fun randomWorld(): Int =
+    1 + RANDOM.nextInt(10000)

+ 13 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/Try.kt

@@ -0,0 +1,13 @@
+package io.vertx.benchmark
+
+sealed class Try<out T> {
+    class Success<out T>(val value: T) : Try<T>()
+    class Failure(val throwable: Throwable) : Try<Nothing>()
+}
+
+inline fun <T> `try`(block: () -> T): Try<T> =
+    try {
+        Try.Success(block())
+    } catch (t: Throwable) {
+        Try.Failure(t)
+    }

+ 13 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/Fortune.kt

@@ -0,0 +1,13 @@
+package io.vertx.benchmark.model
+
+import io.vertx.core.json.JsonObject
+
+/**
+ * The model for the "fortune" database table.
+ */
+class Fortune(val id: Int, val message: String) : Comparable<Fortune> {
+    constructor(doc: JsonObject) : this(doc.getInteger("id"), doc.getString("message"))
+
+    override fun compareTo(other: Fortune): Int =
+        message compareTo other.message
+}

+ 3 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/Message.kt

@@ -0,0 +1,3 @@
+package io.vertx.benchmark.model
+
+class Message(val message: String)

+ 13 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/kotlin/io/vertx/benchmark/model/World.kt

@@ -0,0 +1,13 @@
+package io.vertx.benchmark.model
+
+import io.vertx.core.json.JsonObject
+
+/**
+ * The model for the "world" database table.
+ */
+class World(val id: Int, val randomNumber: Int) : Comparable<World> {
+    constructor(doc: JsonObject) : this(doc.getInteger("id"), doc.getInteger("randomNumber"))
+
+    override fun compareTo(other: World): Int =
+        id compareTo other.id
+}

+ 21 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/resources/templates/Fortunes.rocker.html

@@ -0,0 +1,21 @@
+@import java.util.*
+@import io.vertx.benchmark.model.*
+@args(List fortunes)
+<!DOCTYPE html>
+<html>
+<head><title>Fortunes</title></head>
+<body>
+<table>
+    <tr>
+        <th>id</th>
+        <th>message</th>
+    </tr>
+    @for ((ForIterator i, Fortune fortune) : fortunes) {
+    <tr>
+        <td>@fortune.getId()</td>
+        <td>@fortune.getMessage()</td>
+    </tr>
+    }
+</table>
+</body>
+</html>

+ 15 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/src/main/resources/templates/fortunes.hbs

@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html>
+<head><title>Fortunes</title></head>
+<body>
+<table>
+  <tr>
+    <th>id</th>
+    <th>message</th>
+  </tr> {{#each fortunes}}
+  <tr>
+    <td>{{id}}</td>
+    <td>{{message}}</td>
+  </tr> {{/each}} </table>
+</body>
+</html>

+ 36 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/vertx-web-kotlin-coroutines-postgres.dockerfile

@@ -0,0 +1,36 @@
+FROM gradle:7.3.3-jdk11 as gradle
+WORKDIR /vertx-web-kotlin-coroutines
+COPY gradle gradle
+COPY src src
+COPY build.gradle.kts build.gradle.kts
+COPY gradle.properties gradle.properties
+COPY gradlew gradlew
+COPY settings.gradle.kts settings.gradle.kts
+RUN gradle shadowJar
+
+EXPOSE 8080
+
+CMD java \
+    -server                                           \
+    -XX:+UseNUMA                                      \
+    -XX:+UseParallelGC                                \
+    -XX:+AggressiveOpts                               \
+    -Dvertx.disableMetrics=true                       \
+    -Dvertx.disableH2c=true                           \
+    -Dvertx.disableWebsockets=true                    \
+    -Dvertx.flashPolicyHandler=false                  \
+    -Dvertx.threadChecks=false                        \
+    -Dvertx.disableContextTimings=true                \
+    -Dvertx.disableTCCL=true                          \
+    -Dvertx.disableHttpHeadersValidation=true         \
+    -Dvertx.eventLoopPoolSize=$((`grep --count ^processor /proc/cpuinfo`)) \
+    -Dio.netty.buffer.checkBounds=false               \
+    -Dio.netty.buffer.checkAccessible=false           \
+    -jar                                              \
+    build/libs/vertx-web-kotlin-coroutines-benchmark-4.1.5-fat.jar \
+    --instances                                       \
+    `grep --count ^processor /proc/cpuinfo`           \
+    --conf                                            \
+    src/main/conf/config.json                         \
+    --options                                         \
+    src/main/conf/vertx.json

+ 34 - 0
frameworks/Kotlin/vertx-web-kotlin-coroutines/vertx-web-kotlin-coroutines.dockerfile

@@ -0,0 +1,34 @@
+FROM gradle:7.3.3-jdk11 as gradle
+WORKDIR /vertx-web-kotlin-coroutines
+COPY src src
+COPY build.gradle.kts build.gradle.kts
+COPY gradle.properties gradle.properties
+COPY settings.gradle.kts settings.gradle.kts
+RUN gradle shadowJar
+
+EXPOSE 8080
+
+CMD java \
+    -server                                           \
+    -XX:+UseNUMA                                      \
+    -XX:+UseParallelGC                                \
+    -XX:+AggressiveOpts                               \
+    -Dvertx.disableMetrics=true                       \
+    -Dvertx.disableH2c=true                           \
+    -Dvertx.disableWebsockets=true                    \
+    -Dvertx.flashPolicyHandler=false                  \
+    -Dvertx.threadChecks=false                        \
+    -Dvertx.disableContextTimings=true                \
+    -Dvertx.disableTCCL=true                          \
+    -Dvertx.disableHttpHeadersValidation=true         \
+    -Dvertx.eventLoopPoolSize=$((`grep --count ^processor /proc/cpuinfo`)) \
+    -Dio.netty.buffer.checkBounds=false               \
+    -Dio.netty.buffer.checkAccessible=false           \
+    -jar                                              \
+    build/libs/vertx-web-kotlin-coroutines-benchmark-4.1.5-fat.jar \
+    --instances                                       \
+    `grep --count ^processor /proc/cpuinfo`           \
+    --conf                                            \
+    src/main/conf/config.json                         \
+    --options                                         \
+    src/main/conf/vertx.json