Browse Source

New benchmark: Vert.x-Web Kotlinx (#7910)

* Run `tfb --new` and enter parameters in the Vagrant SSH

* Rerun `tfb --new` with the name "vertx-web-kotlin" and review the changes

* `gradle init`

* Change the Gradle wrapper distribution type to `all`

* Add some needed Gradle plugins and dependencies, and an empty main function

* Set 'compileKotlin' task jvm target to 17

* Complete the prototype "vertx-web-kotlinx" benchmark that produces valid results

Rename the project name from "vertx-web-kotlin" to "vertx-web-kotlinx" because it depends on some opinionated kotlinx libraries.

More performance tuning is needed. Refer to the projects "vert-web-kotlin-coroutines", "vert-web", and "vertx".

3 known exceptions during benchmarking:

1. During tests of almost all types:

   > io.netty.channel.unix.Errors$NativeIoException: recvAddress(..) failed: Connection reset by peer

2. During tests of types that require the database:

   > "logging time" io.vertx.ext.web.RoutingContext
   SEVERE: Unhandled exception in router
   io.netty.channel.StacklessClosedChannelException
   at io.netty.channel.AbstractChannel$AbstractUnsafe.write(Object, ChannelPromise)(Unknown Source)

3. During Database Updates, especially under high concurrency:

   > "logging time" io.vertx.ext.web.RoutingContext
   SEVERE: Unhandled exception in router
   vertx-web-kotlinx-postgresql: io.vertx.pgclient.PgException: ERROR: deadlock detected (40P01)

Performance results are significantly lower compared to "vertx-web-kotlin-coroutines" according to tests run on a Vagrant VirtualBox virtual machine with 24 cores and 24 GB of RAM. Most results are bwteewn 30% and 50% of corresponding ones. The result of Database Updates with `queries=20`, 24 threads, and 512 connections is only 10% of the corresponding one. The result of Plaintext is an exception, which is 2 to 3 times of the corresponding one. However, the Plaintext result in "vertx-web-kotlin-coroutines" is only about half of that in "vertx-web", which I suspect is caused by a newer version of Vert.x offering better performance on this.

* `git mv vertx-web-kotlin vertx-web-kotlinx`

* Resolve the 3 exceptions as mentioned in the previous commit, add JVM command-line options and Vert.x PostgreSQL Client parameters adapted from those in the "vertx-web" portion, and update README.md

Deadlocks in Database Updates are caused by batch-updating unsorted data, thus are resolved by sorting the data first.

There are actually 2 types of connection reset `io.netty.channel.unix.Errors$NativeIoException`s:

1. "recv failed reset exception"s, which are caught and printed in the `Router`'s `exceptionHandler` and caused by the wrk client resetting the connections

   ```plaintext
   io.netty.channel.unix.Errors$NativeIoException: recvAddress(..) failed: Connection reset by peer
   ```

   This type is resolved by handling them explicitly in the `exceptionHandler`.

1. "send failed reset exception"s, which are caused by using Coroutine `launch() { ... }` without specifying `context` and `start` arguments and trailing `end().await()` in request handlers

   ```plaintext
   ... (log time omitted) io.vertx.ext.web.RoutingContext
   SEVERE: Unhandled exception in router
   io.netty.channel.StacklessClosedChannelException
      at io.netty.channel.AbstractChannel$AbstractUnsafe.write(Object, ChannelPromise)(Unknown Source)
   Caused by: io.netty.channel.unix.Errors$NativeIoException: sendAddress(..) failed: Connection reset by peer
   ```

   This type is resolved by launching Coroutines with `Dispatchers.Unconfined` and removing the trailing `await()`s, which also improves the performance by reducing some context switching overhead and Coroutine await overhead, especially in Plaintext.

* Remove the logging code for debugging

* Resolve the performance optimization TODOs and update README.md

Performance comparison conclusions (order matters):

* Using chained calls (fluent API) makes no noticeable difference in Plaintext performance.
* Reusing a single cached buffer in Plaintext makes no noticeable difference.
* Vert.x and kotlinx.serialization offer roughly the same performance in JSON Serialization.
* `HttpServerRequest.getParam` and `RoutingContext.queryParam` offer roughly the same performance in both types of tests that call either of them.
* Replacing `single()`s with `first()`s makes no noticeable difference.
* `selectRandomWorlds2` and `selectRandomWorlds` offer roughly the same performance.
* using `buildString` and `appendHTML` offers better performance than concatenating `"<!DOCTYPE html>"` and the result of `createHTML` in Fortunes; `createHTMLDocument` doesn't pass the test because it adds an extra `<meta>` element.
* data class `copy`s make no noticeable difference in performance.
* Performance implications of different ways of running the Java app with different JVM Options as tested in Plaintext:
  * Running a shadow jar makes no noticeable difference.
  * The Parallel GC Java VM Option `-XX:+UseParallelGC` improves performance by about 7% - 8%.
  * The Java VM Options for Vert.x and netty improve performance by about 10%.
  * `-server` and `-XX:+UseNUMA` don't make much difference.
  * Other GCs are tested to yield worse performance than Parallel GC.
* PostgreSQL database tuning, tested with various types of tests that require the database:
  * While using `PgPool`, a max size of 4 (which is the default value) yields good performance.
  * Replacing `PgPool` (with a max size of 4) with `PgConnection` improves the performance by 30% - 300% in different tests.
  * `cachePreparedStatements` has improved the performance by 150% - 400% in different tests.
* About native transports:
  * Enabling native transports have improved the performance by 3% as tested with Plaintext.
  * The extra native transport networking options (SO_REUSEPORT, TCP_QUICKACK, TCP_CORK, TCP_FASTOPEN) don't benefit the performance.

All tests are run on my machine with a Ryzen 3900X CPU, 32 GB of RAM, and Ubuntu 22.04 LTS installed. The JSON and Plaintext tests are tested directly with wrk, and all the other tests are run in a Vagrant VM tuned with 24 processors, 24 GB of memory, and nested virtualization enabled.

Some other changes:
* `batchSelectRandomWorlds` does not work as expected and is removed; batch execution of queries seems to be not supported.
* `selectRandomWorlds2` is also removed to reduce the code size.

* Clean up and update README.md and correct some spellings

* Remove .gitignore in the subdirectory as it's not needed

* Rename `checkedCoroutineHandler` to `checkedCoroutineHandlerUnconfined` to better reflect its implementation

* Bump dependency versions (Gradle 8.0, Kotlin 1.8.10, and Vert.x 4.3.8) without updating the Dockerfiles

The Gradle 8.0 Docker Image is not available yet.

* Update the Gradle Docker Image to 8.0
Shreck Ye 2 years ago
parent
commit
f60048f96d

+ 9 - 0
frameworks/Kotlin/vertx-web-kotlinx/.gitattributes

@@ -0,0 +1,9 @@
+#
+# https://help.github.com/articles/dealing-with-line-endings/
+#
+# Linux start script should use lf
+/gradlew        text eol=lf
+
+# These are Windows script files and should use crlf
+*.bat           text eol=crlf
+

+ 60 - 0
frameworks/Kotlin/vertx-web-kotlinx/README.md

@@ -0,0 +1,60 @@
+# Vert.x-Web Kotlinx Benchmarking Test
+
+Vert.x-Web in Kotlin with request handling implemented as much with official kotlinx libraries as possible.
+
+Code is written from scratch to be as concise as possible with common code extracted into common (possibly inline) functions. SQL client implementation details and JVM Options are adapted referring to [the vertx-web portion](../../Java/vertx-web) and [the vertx portion](../../Java/vertx). All requests are handled in coroutines and suspend `await`s are used instead of future compositions. Compared to [the vertx-web-kotlin-coroutines portion](../vertx-web-kotlin-coroutines), besides adopting the Kotlinx libraries, this project simplifies the code by using more built-in Coroutine functions and avoids mutability as much as possible. JSON serialization is implemented with kotlinx.serialization and Fortunes with kotlinx.html. The benchmark is run on the latest LTS version of JVM, 17.
+
+## Test Type Implementation Source Code
+
+* [JSON](src/main/kotlin/MainVerticle.kt)
+
+  implemented with kotlinx.serialization
+
+* [PLAINTEXT](src/main/kotlin/MainVerticle.kt)
+* [DB](src/main/kotlin/MainVerticle.kt)
+* [QUERY](src/main/kotlin/MainVerticle.kt)
+* [CACHED QUERY](src/main/kotlin/MainVerticle.kt)
+* [UPDATE](src/main/kotlin/MainVerticle.kt)
+* [FORTUNES](src/main/kotlin/MainVerticle.kt)
+
+  implemented with kotlinx.html
+
+## Important Libraries
+
+The tests were run with:
+
+* [Vert.x-Web](https://vertx.io/docs/vertx-web/java/)
+* [Vert.x Reactive PostgreSQL Client](https://vertx.io/docs/vertx-pg-client/java/)
+* [kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)
+* [kotlinx.serialization](https://github.com/Kotlin/kotlinx.serialization)
+* [kotlinx.html](https://github.com/Kotlin/kotlinx.html)
+
+## Test URLs
+
+### JSON
+
+http://localhost:8080/json
+
+### PLAINTEXT
+
+http://localhost:8080/plaintext
+
+### DB
+
+http://localhost:8080/db
+
+### QUERY
+
+http://localhost:8080/query?queries=
+
+### CACHED QUERY
+
+http://localhost:8080/cached_query?queries=
+
+### UPDATE
+
+http://localhost:8080/update?queries=
+
+### FORTUNES
+
+http://localhost:8080/fortunes

+ 47 - 0
frameworks/Kotlin/vertx-web-kotlinx/benchmark_config.json

@@ -0,0 +1,47 @@
+{
+  "framework": "vertx-web-kotlinx",
+  "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-kotlinx",
+        "notes": "",
+        "versus": "vertx-web"
+      },
+      "postgresql": {
+        "db_url": "/db",
+        "query_url": "/queries?queries=",
+        "fortune_url": "/fortunes",
+        "update_url": "/updates?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-kotlinx-postgresql",
+        "notes": "",
+        "versus": "vertx-web"
+      }
+    }
+  ]
+}

+ 38 - 0
frameworks/Kotlin/vertx-web-kotlinx/build.gradle.kts

@@ -0,0 +1,38 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
+tasks.wrapper {
+    distributionType = Wrapper.DistributionType.ALL
+}
+
+plugins {
+    val kotlinVersion = "1.8.10"
+    kotlin("jvm") version kotlinVersion
+    kotlin("plugin.serialization") version kotlinVersion
+    application
+}
+
+repositories {
+    mavenCentral()
+}
+
+val vertxVersion = "4.3.8"
+dependencies {
+    implementation(platform("io.vertx:vertx-stack-depchain:$vertxVersion"))
+    implementation("io.vertx:vertx-web")
+    implementation("io.vertx:vertx-pg-client")
+    implementation("io.netty", "netty-transport-native-epoll", classifier = "linux-x86_64")
+    implementation("io.vertx:vertx-lang-kotlin")
+    implementation("io.vertx:vertx-lang-kotlin-coroutines")
+
+    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
+    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
+    implementation("org.jetbrains.kotlinx:kotlinx-html:0.8.0")
+    //implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
+}
+
+tasks.withType<KotlinCompile> {
+    compilerOptions.jvmTarget.set(JvmTarget.JVM_17)
+}
+
+application.mainClass.set("MainKt")

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

@@ -0,0 +1 @@
+org.gradle.parallel=true

BIN
frameworks/Kotlin/vertx-web-kotlinx/gradle/wrapper/gradle-wrapper.jar


+ 6 - 0
frameworks/Kotlin/vertx-web-kotlinx/gradle/wrapper/gradle-wrapper.properties

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

+ 244 - 0
frameworks/Kotlin/vertx-web-kotlinx/gradlew

@@ -0,0 +1,244 @@
+#!/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/HEAD/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
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+# 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*)
+        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC3045
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC3045
+        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 \
+        "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+    die "xargs is not available"
+fi
+
+# 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" "$@"

+ 92 - 0
frameworks/Kotlin/vertx-web-kotlinx/gradlew.bat

@@ -0,0 +1,92 @@
+@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=.
+@rem This is normally unused
+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% equ 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% equ 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!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

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

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

+ 12 - 0
frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/Database.kt

@@ -0,0 +1,12 @@
+import io.vertx.sqlclient.Row
+
+const val SELECT_WORLD_SQL = "SELECT id, randomnumber from WORLD where id = $1"
+const val UPDATE_WORLD_SQL = "UPDATE world SET randomnumber = $1 WHERE id = $2"
+const val SELECT_FORTUNE_SQL = "SELECT id, message from FORTUNE"
+
+
+fun Row.toWorld() =
+    World(getInteger(0), getInteger(1))
+
+fun Row.toFortune() =
+    Fortune(getInteger(0), getString(1))

+ 24 - 0
frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/Main.kt

@@ -0,0 +1,24 @@
+import io.vertx.core.Vertx
+import io.vertx.core.impl.cpu.CpuCoreSensor
+import io.vertx.kotlin.core.deploymentOptionsOf
+import io.vertx.kotlin.core.vertxOptionsOf
+import io.vertx.kotlin.coroutines.await
+import java.util.logging.Logger
+
+const val SERVER_NAME = "Vert.x-Web Kotlinx Benchmark"
+
+val logger = Logger.getLogger("Vert.x-Web Kotlinx Benchmark")
+suspend fun main(args: Array<String>) {
+    val hasDb = args.getOrNull(0)?.toBooleanStrictOrNull()
+        ?: throw IllegalArgumentException("Specify the first `hasDb` Boolean argument")
+
+    logger.info("$SERVER_NAME starting...")
+    val vertx = Vertx.vertx(vertxOptionsOf(preferNativeTransport = true))
+    vertx.exceptionHandler {
+        logger.info("Vertx exception caught: $it")
+        it.printStackTrace()
+    }
+    vertx.deployVerticle({ MainVerticle(hasDb) }, deploymentOptionsOf(instances = CpuCoreSensor.availableProcessors()))
+        .await()
+    logger.info("$SERVER_NAME started.")
+}

+ 208 - 0
frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/MainVerticle.kt

@@ -0,0 +1,208 @@
+import io.netty.channel.unix.Errors.NativeIoException
+import io.vertx.core.http.HttpHeaders
+import io.vertx.core.http.HttpServer
+import io.vertx.core.http.HttpServerRequest
+import io.vertx.core.http.HttpServerResponse
+import io.vertx.ext.web.Route
+import io.vertx.ext.web.Router
+import io.vertx.ext.web.RoutingContext
+import io.vertx.kotlin.core.http.httpServerOptionsOf
+import io.vertx.kotlin.coroutines.CoroutineVerticle
+import io.vertx.kotlin.coroutines.await
+import io.vertx.kotlin.pgclient.pgConnectOptionsOf
+import io.vertx.pgclient.PgConnection
+import io.vertx.sqlclient.PreparedQuery
+import io.vertx.sqlclient.Row
+import io.vertx.sqlclient.RowSet
+import io.vertx.sqlclient.Tuple
+import kotlinx.coroutines.*
+import kotlinx.html.*
+import kotlinx.html.stream.appendHTML
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import java.net.SocketException
+import java.time.ZonedDateTime
+import java.time.format.DateTimeFormatter
+
+class MainVerticle(val hasDb: Boolean) : CoroutineVerticle() {
+    inline fun Route.checkedCoroutineHandlerUnconfined(crossinline requestHandler: suspend (RoutingContext) -> Unit): Route =
+        handler { ctx ->
+            /* Some conclusions from the Plaintext test results with trailing `await()`s:
+               1. `launch { /*...*/ }` < `launch(start = CoroutineStart.UNDISPATCHED) { /*...*/ }` < `launch(Dispatchers.Unconfined) { /*...*/ }`.
+               1. `launch { /*...*/ }` without `context` or `start` lead to `io.netty.channel.StacklessClosedChannelException` and `io.netty.channel.unix.Errors$NativeIoException: sendAddress(..) failed: Connection reset by peer`. */
+            launch(Dispatchers.Unconfined) {
+                try {
+                    requestHandler(ctx)
+                } catch (t: Throwable) {
+                    ctx.fail(t)
+                }
+            }
+        }
+
+    // `PgConnection`s as used in the "vertx" portion offers better performance than `PgPool`s.
+    lateinit var pgConnection: PgConnection
+    lateinit var date: String
+    lateinit var httpServer: HttpServer
+
+    lateinit var selectWorldQuery: PreparedQuery<RowSet<Row>>
+    lateinit var selectFortuneQuery: PreparedQuery<RowSet<Row>>
+    lateinit var updateWordQuery: PreparedQuery<RowSet<Row>>
+
+    fun setCurrentDate() {
+        // kotlinx-datetime doesn't support the format yet.
+        //date = Clock.System.now().toString()
+        date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now())
+    }
+
+    override suspend fun start() {
+        if (hasDb) {
+            // Parameters are copied from the "vertx-web" and "vertx" portions.
+            pgConnection = PgConnection.connect(
+                vertx,
+                pgConnectOptionsOf(
+                    database = "hello_world",
+                    host = "tfb-database",
+                    user = "benchmarkdbuser",
+                    password = "benchmarkdbpass",
+                    cachePreparedStatements = true,
+                    pipeliningLimit = 100000
+                )
+            ).await()
+
+            selectWorldQuery = pgConnection.preparedQuery(SELECT_WORLD_SQL)
+            selectFortuneQuery = pgConnection.preparedQuery(SELECT_FORTUNE_SQL)
+            updateWordQuery = pgConnection.preparedQuery(UPDATE_WORLD_SQL)
+        }
+
+        setCurrentDate()
+        vertx.setPeriodic(1000) { setCurrentDate() }
+        httpServer = vertx.createHttpServer(httpServerOptionsOf(port = 8080))
+            .requestHandler(Router.router(vertx).apply { routes() })
+            .exceptionHandler {
+                // wrk resets the connections when benchmarking is finished.
+                if ((it is NativeIoException && it.message == "recvAddress(..) failed: Connection reset by peer")
+                    || (it is SocketException && it.message == "Connection reset")
+                )
+                    return@exceptionHandler
+
+                logger.info("Exception in HttpServer: $it")
+                it.printStackTrace()
+            }
+            .listen().await()
+    }
+
+
+    fun HttpServerRequest.getQueries(): Int {
+        val queriesParam: String? = getParam("queries")
+        return queriesParam?.toIntOrNull()?.coerceIn(1, 500) ?: 1
+    }
+
+    @Suppress("NOTHING_TO_INLINE")
+    inline fun HttpServerResponse.putCommonHeaders() {
+        putHeader(HttpHeaders.SERVER, "Vert.x-Web")
+        putHeader(HttpHeaders.DATE, date)
+    }
+
+    @Suppress("NOTHING_TO_INLINE")
+    inline fun HttpServerResponse.putJsonResponseHeader() {
+        putCommonHeaders()
+        putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+    }
+
+    inline fun <reified T : Any> Route.jsonResponseHandler(crossinline requestHandler: suspend (RoutingContext) -> @Serializable T) =
+        checkedCoroutineHandlerUnconfined {
+            it.response().run {
+                putJsonResponseHeader()
+                end(Json.encodeToString(requestHandler(it)))/*.await()*/
+            }
+        }
+
+    suspend fun selectRandomWorlds(queries: Int): List<World> {
+        val rowSets = List(queries) {
+            selectWorldQuery.execute(Tuple.of(randomIntBetween1And10000()))
+        }.awaitAll()
+        return rowSets.map { it.single().toWorld() }
+    }
+
+    fun Router.routes() {
+        get("/json").jsonResponseHandler {
+            jsonSerializationMessage
+        }
+
+        get("/db").jsonResponseHandler {
+            val rowSet = selectWorldQuery.execute(Tuple.of(randomIntBetween1And10000())).await()
+            rowSet.single().toWorld()
+        }
+
+        get("/queries").jsonResponseHandler {
+            val queries = it.request().getQueries()
+            selectRandomWorlds(queries)
+        }
+
+        get("/fortunes").checkedCoroutineHandlerUnconfined {
+            val fortunes = mutableListOf<Fortune>()
+            selectFortuneQuery.execute().await()
+                .mapTo(fortunes) { it.toFortune() }
+
+            fortunes.add(Fortune(0, "Additional fortune added at request time."))
+            fortunes.sortBy { it.message }
+
+            val htmlString = buildString {
+                append("<!DOCTYPE html>")
+                appendHTML(false).html {
+                    head {
+                        title("Fortunes")
+                    }
+                    body {
+                        table {
+                            tr {
+                                th { +"id" }
+                                th { +"message" }
+                            }
+                            for (fortune in fortunes)
+                                tr {
+                                    td { +fortune.id.toString() }
+                                    td { +fortune.message }
+                                }
+                        }
+                    }
+                }
+            }
+
+            it.response().run {
+                putCommonHeaders()
+                putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=utf-8")
+                end(htmlString)/*.await()*/
+            }
+        }
+
+        get("/updates").jsonResponseHandler {
+            val queries = it.request().getQueries()
+            val worlds = selectRandomWorlds(queries)
+            val updatedWorlds = worlds.map { it.copy(randomNumber = randomIntBetween1And10000()) }
+
+            // Approach 1
+            // The updated worlds need to be sorted first to avoid deadlocks.
+            updateWordQuery
+                .executeBatch(updatedWorlds.sortedBy { it.id }.map { Tuple.of(it.randomNumber, it.id) }).await()
+
+            /*
+            // Approach 2, worse performance
+            updatedWorlds.map {
+                pgPool.preparedQuery(UPDATE_WORLD_SQL).execute(Tuple.of(it.randomNumber, it.id))
+            }.awaitAll()
+            */
+
+            updatedWorlds
+        }
+
+        get("/plaintext").checkedCoroutineHandlerUnconfined {
+            it.response().run {
+                putCommonHeaders()
+                putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
+                end("Hello, World!")/*.await()*/
+            }
+        }
+    }
+}

+ 15 - 0
frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/Models.kt

@@ -0,0 +1,15 @@
+import kotlinx.serialization.Serializable
+import kotlin.random.Random
+
+@Serializable
+class Message(val message: String)
+
+val jsonSerializationMessage = Message("Hello, World!")
+
+@Serializable
+data class World(val id: Int, val randomNumber: Int)
+
+fun randomIntBetween1And10000() =
+    Random.nextInt(1, 10001)
+
+class Fortune(val id: Int, val message: String)

+ 6 - 0
frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/VertxCoroutine.kt

@@ -0,0 +1,6 @@
+import io.vertx.core.CompositeFuture
+import io.vertx.core.Future
+import io.vertx.kotlin.coroutines.await
+
+suspend fun <T> List<Future<T>>.awaitAll(): List<T> =
+    CompositeFuture.all(this).await().list()

+ 28 - 0
frameworks/Kotlin/vertx-web-kotlinx/vertx-web-kotlinx-postgresql.dockerfile

@@ -0,0 +1,28 @@
+FROM gradle:8.0-jdk17
+
+WORKDIR /vertx-web-kotlinx
+COPY build.gradle.kts build.gradle.kts
+COPY settings.gradle.kts settings.gradle.kts
+COPY gradle.properties gradle.properties
+COPY src src
+RUN gradle assembleDist
+RUN tar -xf build/distributions/vertx-web-kotlinx-benchmark.tar
+
+EXPOSE 8080
+
+CMD export JAVA_OPTS=" \
+    -server \
+    -XX:+UseNUMA \
+    -XX:+UseParallelGC \
+    -Dvertx.disableMetrics=true \
+    -Dvertx.disableH2c=true \
+    -Dvertx.disableWebsockets=true \
+    -Dvertx.flashPolicyHandler=false \
+    -Dvertx.threadChecks=false \
+    -Dvertx.disableContextTimings=true \
+    -Dvertx.disableTCCL=true \
+    -Dvertx.disableHttpHeadersValidation=true \
+    -Dio.netty.buffer.checkBounds=false \
+    -Dio.netty.buffer.checkAccessible=false \
+    " && \
+    vertx-web-kotlinx-benchmark/bin/vertx-web-kotlinx-benchmark true

+ 28 - 0
frameworks/Kotlin/vertx-web-kotlinx/vertx-web-kotlinx.dockerfile

@@ -0,0 +1,28 @@
+FROM gradle:8.0-jdk17
+
+WORKDIR /vertx-web-kotlinx
+COPY build.gradle.kts build.gradle.kts
+COPY settings.gradle.kts settings.gradle.kts
+COPY gradle.properties gradle.properties
+COPY src src
+RUN gradle assembleDist
+RUN tar -xf build/distributions/vertx-web-kotlinx-benchmark.tar
+
+EXPOSE 8080
+
+CMD export JAVA_OPTS=" \
+    -server \
+    -XX:+UseNUMA \
+    -XX:+UseParallelGC \
+    -Dvertx.disableMetrics=true \
+    -Dvertx.disableH2c=true \
+    -Dvertx.disableWebsockets=true \
+    -Dvertx.flashPolicyHandler=false \
+    -Dvertx.threadChecks=false \
+    -Dvertx.disableContextTimings=true \
+    -Dvertx.disableTCCL=true \
+    -Dvertx.disableHttpHeadersValidation=true \
+    -Dio.netty.buffer.checkBounds=false \
+    -Dio.netty.buffer.checkAccessible=false \
+    " && \
+    vertx-web-kotlinx-benchmark/bin/vertx-web-kotlinx-benchmark false