From 16fa679bc04f063ae443593fcc032ca6eb63a686 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Thu, 8 Oct 2026 13:40:27 +0300 Subject: [PATCH 1/7] Move lab1 to lab2 --- .dockerignore | 18 ++ .gitignore | 3 + Dockerfile | 19 ++ build.gradle.kts | 66 +++++ compose.yaml | 11 + gradle.properties | 1 + gradle/libs.versions.toml | 16 ++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 251 ++++++++++++++++++ gradlew.bat | 94 +++++++ run/development/config/application.conf | 10 + settings.gradle.kts | 17 ++ .../kotlin/com/mtusi/messenger/main/App.kt | 42 +++ .../main/extensions/ApplicationCall.kt | 44 +++ .../controllers/chat/ChatController.kt | 67 +++++ .../chat/requests/CreateChatRequest.kt | 9 + .../chat/responses/ChatPageResponse.kt | 10 + .../controllers/health/HealthController.kt | 20 ++ .../health/responses/HealthResponse.kt | 6 + .../controllers/message/MessageController.kt | 65 +++++ .../message/requests/CreateMessageRequest.kt | 8 + .../message/responses/MessagePageResponse.kt | 10 + .../controllers/user/UserController.kt | 41 +++ .../user/requests/CreateUserRequest.kt | 9 + .../messenger/main/infrastructure/dto/Chat.kt | 11 + .../main/infrastructure/dto/Message.kt | 12 + .../messenger/main/infrastructure/dto/User.kt | 11 + .../infrastructure/repositories/Repository.kt | 3 + .../repositories/chat/ChatRepository.kt | 12 + .../chat/InMemoryChatRepository.kt | 24 ++ .../message/InMemoryMessageRepository.kt | 45 ++++ .../repositories/message/MessageRepository.kt | 9 + .../user/InMemoryUserRepository.kt | 18 ++ .../repositories/user/UserRepository.kt | 12 + .../services/chat/ChatService.kt | 23 ++ .../services/chat/DefaultChatService.kt | 92 +++++++ .../services/message/DefaultMessageService.kt | 74 ++++++ .../services/message/MessageService.kt | 19 ++ .../services/user/DefaultUserService.kt | 33 +++ .../services/user/UserService.kt | 8 + .../main/infrastructure/types/ApiException.kt | 3 + .../main/infrastructure/types/ErrorCode.kt | 15 ++ .../messenger/main/plugins/CallLogging.kt | 14 + .../main/plugins/ContentNegotiation.kt | 21 ++ .../messenger/main/plugins/DefaultHeaders.kt | 7 + .../messenger/main/plugins/Dependencies.kt | 11 + .../mtusi/messenger/main/plugins/RequestId.kt | 20 ++ .../mtusi/messenger/main/plugins/Routing.kt | 16 ++ .../messenger/main/plugins/StatusPages.kt | 44 +++ .../mtusi/messenger/main/plugins/Swagger.kt | 8 + .../com/mtusi/messenger/main/utils/Page.kt | 6 + .../mtusi/messenger/main/utils/Pagination.kt | 40 +++ .../com/mtusi/messenger/main/utils/Time.kt | 11 + .../mtusi/messenger/main/utils/Validation.kt | 31 +++ src/main/resources/application.conf | 14 + src/main/resources/logback.xml | 12 + .../controllers/chat/ChatControllerTest.kt | 43 +++ .../health/HealthControllerTest.kt | 22 ++ .../message/MessageConcurrencyTest.kt | 74 ++++++ .../message/MessageControllerTest.kt | 190 +++++++++++++ .../controllers/user/UserControllerTest.kt | 72 +++++ .../message/InMemoryMessageRepositoryTest.kt | 58 ++++ .../mtusi/messenger/main/support/TestApp.kt | 71 +++++ src/test/resources/application.conf | 10 + 65 files changed, 2063 insertions(+) create mode 100644 Dockerfile create mode 100644 build.gradle.kts create mode 100644 compose.yaml create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 run/development/config/application.conf create mode 100644 settings.gradle.kts create mode 100644 src/main/kotlin/com/mtusi/messenger/main/App.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/requests/CreateChatRequest.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/responses/HealthResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/requests/CreateMessageRequest.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/Repository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ApiException.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ErrorCode.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/CallLogging.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/ContentNegotiation.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/DefaultHeaders.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/RequestId.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Swagger.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt create mode 100644 src/main/resources/application.conf create mode 100644 src/main/resources/logback.xml create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt create mode 100644 src/test/resources/application.conf diff --git a/.dockerignore b/.dockerignore index bc16e556..c3256588 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,21 @@ __pycache__ node_modules evidence .DS_Store +.gradle +.kotlin +build +.idea +*.iml +tests +scripts +examples +run +COURSE.md +CONTRIBUTING.md +MAINTAINERS.md +REPORT.md +README.md +requirements-dev.txt +Dockerfile.example +compose.example.yaml +Makefile diff --git a/.gitignore b/.gitignore index b5a71896..0fe411f8 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,8 @@ coverage/ .DS_Store .idea/ .vscode/ +.gradle/ +.kotlin/ +!gradle/wrapper/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..096e5a7a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM gradle:8.14-jdk21 AS build +WORKDIR /src +COPY settings.gradle.kts build.gradle.kts gradle.properties ./ +COPY gradle ./gradle +COPY gradlew ./ +COPY src ./src +COPY contracts ./contracts +RUN --mount=type=cache,target=/home/gradle/.gradle gradle --no-daemon shadowJar + +FROM eclipse-temurin:21-jre-alpine +RUN apk add --no-cache wget && addgroup -S app && adduser -S -G app app +WORKDIR /app +COPY --from=build /src/build/libs/messenger.jar /app/messenger.jar +USER app +ENV APP_HOST=0.0.0.0 APP_PORT=8080 +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=15s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 +ENTRYPOINT ["java","-XX:MaxRAMPercentage=75.0","-jar","/app/messenger.jar"] diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..d7d24c0e --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,66 @@ +plugins { + alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.serialization) + alias(libs.plugins.shadow) + id("application") +} + +group = "com.mtusi.messenger" +version = "1.0.0" + +repositories { + mavenCentral() +} + +dependencies { + implementation(libs.kotlinx.serialization.json) + implementation(libs.logback.classic) + + implementation(ktorLibs.server.core) + implementation(ktorLibs.server.netty) + implementation(ktorLibs.server.contentNegotiation) + implementation(ktorLibs.server.statusPages) + implementation(ktorLibs.server.callLogging) + implementation(ktorLibs.server.defaultHeaders) + implementation(ktorLibs.server.swagger) + implementation(ktorLibs.serialization.kotlinx.json) + + testImplementation(kotlin("test")) + testImplementation(ktorLibs.server.testHost) + testImplementation(ktorLibs.client.contentNegotiation) + testImplementation(libs.kotlinx.coroutines.test) +} + +kotlin { + jvmToolchain(21) +} + +application { + mainClass = "io.ktor.server.netty.EngineMain" + applicationDefaultJvmArgs = listOf("-Dio.ktor.development=false") +} + +sourceSets { + named("main") { + resources { + srcDir(layout.projectDirectory.dir("contracts")) + } + } +} + +tasks { + test { + useJUnitPlatform() + } + + shadowJar { + archiveBaseName = "messenger" + archiveClassifier = "" + archiveVersion = "" + mergeServiceFiles() + } + + getByName("run") { + workingDir = file("run/development") + } +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..31417a30 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,11 @@ +services: + messenger: + build: . + image: mtusi-messenger:lab2 + container_name: mtusi-messenger-lab2 + ports: + - "127.0.0.1:8080:8080" + environment: + APP_HOST: "0.0.0.0" + APP_PORT: "8080" + restart: unless-stopped diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..7fc6f1ff --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..5e51593a --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,16 @@ +[versions] +kotlin = "2.1.21" +kotlinx-serialization = "1.8.0" +logback = "1.5.12" +shadow = "8.3.5" +kotlinx-coroutines = "1.9.0" + +[plugins] +kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } + +[libraries] +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..1b33c55baabb587c669f562ae36f953de2481846 GIT binary patch literal 43764 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 '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# 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="\\\"\\\"" + + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +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=SC2039,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=SC2039,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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..db3a6ac2 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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 diff --git a/run/development/config/application.conf b/run/development/config/application.conf new file mode 100644 index 00000000..845ad1f4 --- /dev/null +++ b/run/development/config/application.conf @@ -0,0 +1,10 @@ +ktor { + application { + modules = [com.mtusi.messenger.main.AppKt.module] + } + + deployment { + host = "127.0.0.1" + port = 8080 + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..3adf8feb --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,17 @@ +dependencyResolutionManagement { + repositories { + mavenCentral() + } + + versionCatalogs { + create("ktorLibs") { + from("io.ktor:ktor-version-catalog:3.3.0") + } + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "mtusi-messenger-lab2" diff --git a/src/main/kotlin/com/mtusi/messenger/main/App.kt b/src/main/kotlin/com/mtusi/messenger/main/App.kt new file mode 100644 index 00000000..366cb856 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/App.kt @@ -0,0 +1,42 @@ +package com.mtusi.messenger.main + +import com.mtusi.messenger.main.infrastructure.repositories.chat.InMemoryChatRepository +import com.mtusi.messenger.main.infrastructure.repositories.message.InMemoryMessageRepository +import com.mtusi.messenger.main.infrastructure.repositories.user.InMemoryUserRepository +import com.mtusi.messenger.main.infrastructure.services.chat.DefaultChatService +import com.mtusi.messenger.main.infrastructure.services.message.DefaultMessageService +import com.mtusi.messenger.main.infrastructure.services.user.DefaultUserService +import com.mtusi.messenger.main.plugins.Dependencies +import com.mtusi.messenger.main.plugins.configureCallLogging +import com.mtusi.messenger.main.plugins.configureContentNegotiation +import com.mtusi.messenger.main.plugins.configureDefaultHeaders +import com.mtusi.messenger.main.plugins.configureRequestId +import com.mtusi.messenger.main.plugins.configureRouting +import com.mtusi.messenger.main.plugins.configureStatusPages +import io.ktor.server.application.Application +import io.ktor.server.netty.EngineMain + +fun main(args: Array): Unit = EngineMain.main(args) + +fun Application.module() { + val userRepository = InMemoryUserRepository() + val chatRepository = InMemoryChatRepository() + val messageRepository = InMemoryMessageRepository() + + val userService = DefaultUserService(userRepository) + val chatService = DefaultChatService(chatRepository, userRepository) + val messageService = DefaultMessageService(chatRepository, messageRepository) + + val dependencies = Dependencies( + userService = userService, + chatService = chatService, + messageService = messageService, + ) + + configureContentNegotiation() + configureDefaultHeaders() + configureRequestId() + configureCallLogging() + configureStatusPages() + configureRouting(dependencies) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt new file mode 100644 index 00000000..c6b1bb5b --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt @@ -0,0 +1,44 @@ +package com.mtusi.messenger.main.extensions + +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.plugins.RequestIdKey +import io.ktor.server.application.ApplicationCall +import io.ktor.server.response.header +import io.ktor.server.response.respond +import kotlinx.serialization.Serializable + +@Serializable +data class ErrorBody(val error: ErrorDetails) + +@Serializable +data class ErrorDetails( + val code: String, + val message: String, + val requestId: String, +) + +suspend fun ApplicationCall.respondError(code: ErrorCode, message: String) { + val requestId = attributes[RequestIdKey] + if (code == ErrorCode.UNAUTHORIZED) { + response.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"") + } + respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId))) +} + +private val UUID_REGEX = Regex( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" +) + +fun isValidUuid(value: String): Boolean = UUID_REGEX.matches(value) + +fun ApplicationCall.requireCurrentUser(userService: UserService): User { + val header = request.headers["X-User-Id"]?.trim() + if (header.isNullOrEmpty() || !isValidUuid(header)) { + throw ApiException(ErrorCode.UNAUTHORIZED, "missing or invalid X-User-Id") + } + return userService.findById(header) + ?: throw ApiException(ErrorCode.UNAUTHORIZED, "unknown user") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt new file mode 100644 index 00000000..8f252d8e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt @@ -0,0 +1,67 @@ +package com.mtusi.messenger.main.infrastructure.controllers.chat + +import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest +import com.mtusi.messenger.main.infrastructure.controllers.chat.responses.ChatPageResponse +import com.mtusi.messenger.main.infrastructure.services.chat.ChatService +import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.utils.requireNonBlankBounded +import com.mtusi.messenger.main.utils.requireUuid +import io.ktor.http.HttpStatusCode +import io.ktor.server.request.receive +import io.ktor.server.response.respond +import io.ktor.server.routing.Routing +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.routing.route + +private const val TITLE_MAX = 100 + +fun Routing.configureChatRouting( + chatService: ChatService, + userService: UserService, +) = route("/api/v1/chats") { + + post { + + val actor = call.requireCurrentUser(userService) + val body = call.receive() + + requireNonBlankBounded( + body.title, + min = 1, + max = TITLE_MAX, + field = "title" + ) + + val chat = chatService.create(actor.id, body.title, body.memberIds) + call.respond(HttpStatusCode.Created, chat) + } + + get { + + val actor = call.requireCurrentUser(userService) + + val page = chatService.findPageAccessible( + userId = actor.id, + rawLimit = call.request.queryParameters["limit"], + rawCursor = call.request.queryParameters["cursor"], + ) + + call.respond(HttpStatusCode.OK, ChatPageResponse(page.items, page.nextCursor)) + } + + get("{chat_id}") { + + val actor = call.requireCurrentUser(userService) + val chatId = call.parameters["chat_id"] + ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") + + requireUuid(chatId, "chat_id") + + val chat = chatService.findAccessible(actor.id, chatId) + call.respond(HttpStatusCode.OK, chat) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/requests/CreateChatRequest.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/requests/CreateChatRequest.kt new file mode 100644 index 00000000..d0505b9d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/requests/CreateChatRequest.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.infrastructure.controllers.chat.requests + +import kotlinx.serialization.Serializable + +@Serializable +data class CreateChatRequest( + val title: String, + val memberIds: List, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt new file mode 100644 index 00000000..49a29440 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt @@ -0,0 +1,10 @@ +package com.mtusi.messenger.main.infrastructure.controllers.chat.responses + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import kotlinx.serialization.Serializable + +@Serializable +data class ChatPageResponse( + val items: List, + val nextCursor: String?, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt new file mode 100644 index 00000000..7f9b836c --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt @@ -0,0 +1,20 @@ +package com.mtusi.messenger.main.infrastructure.controllers.health + +import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.respond +import io.ktor.server.routing.Routing +import io.ktor.server.routing.get +import io.ktor.server.routing.route + +fun Routing.configureHealthRouting() = route("/health") { + + get("live") { + call.respond(HttpStatusCode.OK, HealthResponse()) + } + + get("ready") { + call.respond(HttpStatusCode.OK, HealthResponse()) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/responses/HealthResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/responses/HealthResponse.kt new file mode 100644 index 00000000..a6b56097 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/responses/HealthResponse.kt @@ -0,0 +1,6 @@ +package com.mtusi.messenger.main.infrastructure.controllers.health.responses + +import kotlinx.serialization.Serializable + +@Serializable +data class HealthResponse(val status: String = "ok") diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt new file mode 100644 index 00000000..f956039e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt @@ -0,0 +1,65 @@ +package com.mtusi.messenger.main.infrastructure.controllers.message + +import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest +import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.services.message.MessageService +import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.utils.requireNonBlankBounded +import com.mtusi.messenger.main.utils.requireUuid +import io.ktor.http.HttpStatusCode +import io.ktor.server.request.receive +import io.ktor.server.response.respond +import io.ktor.server.routing.Routing +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.routing.route + +private const val TEXT_MAX = 4000 + +fun Routing.configureMessageRouting( + messageService: MessageService, + userService: UserService, +) = route("/api/v1/chats/{chat_id}/messages") { + + post { + + val actor = call.requireCurrentUser(userService) + val chatId = call.parameters["chat_id"] + ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") + + requireUuid(chatId, "chat_id") + + val body = call.receive() + + requireNonBlankBounded( + body.text, + min = 1, + max = TEXT_MAX, + field = "text" + ) + + val message = messageService.send(chatId, actor.id, body.text) + call.respond(HttpStatusCode.Created, message) + } + + get { + + val actor = call.requireCurrentUser(userService) + val chatId = call.parameters["chat_id"] + ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") + + requireUuid(chatId, "chat_id") + + val page = messageService.findPageByChatId( + chatId = chatId, + actorId = actor.id, + rawLimit = call.request.queryParameters["limit"], + rawCursor = call.request.queryParameters["cursor"], + ) + + call.respond(HttpStatusCode.OK, MessagePageResponse(page.items, page.nextCursor)) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/requests/CreateMessageRequest.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/requests/CreateMessageRequest.kt new file mode 100644 index 00000000..8a9a3c39 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/requests/CreateMessageRequest.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.controllers.message.requests + +import kotlinx.serialization.Serializable + +@Serializable +data class CreateMessageRequest( + val text: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt new file mode 100644 index 00000000..e2bd1fc4 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt @@ -0,0 +1,10 @@ +package com.mtusi.messenger.main.infrastructure.controllers.message.responses + +import com.mtusi.messenger.main.infrastructure.dto.Message +import kotlinx.serialization.Serializable + +@Serializable +data class MessagePageResponse( + val items: List, + val nextCursor: String?, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt new file mode 100644 index 00000000..a398b623 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt @@ -0,0 +1,41 @@ +package com.mtusi.messenger.main.infrastructure.controllers.user + +import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.utils.requireNonBlankBounded +import com.mtusi.messenger.main.utils.requireUsername +import io.ktor.http.HttpStatusCode +import io.ktor.server.request.receive +import io.ktor.server.response.respond +import io.ktor.server.routing.Routing +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.routing.route + +private const val DISPLAY_NAME_MAX = 100 + +fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/users") { + + post { + val body = call.receive() + + requireUsername(body.username) + + requireNonBlankBounded( + body.displayName, + min = 1, + max = DISPLAY_NAME_MAX, + field = "displayName" + ) + + val user = userService.create(body.username, body.displayName) + call.respond(HttpStatusCode.Created, user) + } + + get("me") { + val user = call.requireCurrentUser(userService) + call.respond(HttpStatusCode.OK, user) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt new file mode 100644 index 00000000..d7a9dbf1 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.infrastructure.controllers.user.requests + +import kotlinx.serialization.Serializable + +@Serializable +data class CreateUserRequest( + val username: String, + val displayName: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt new file mode 100644 index 00000000..84a57b85 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.infrastructure.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class Chat( + val id: String, + val title: String, + val memberIds: List, + val createdAt: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt new file mode 100644 index 00000000..979b8d32 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt @@ -0,0 +1,12 @@ +package com.mtusi.messenger.main.infrastructure.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class Message( + val id: String, + val chatId: String, + val senderId: String, + val text: String, + val createdAt: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt new file mode 100644 index 00000000..b6ed9b92 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.infrastructure.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class User( + val id: String, + val username: String, + val displayName: String, + val createdAt: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/Repository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/Repository.kt new file mode 100644 index 00000000..7d841e3e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/Repository.kt @@ -0,0 +1,3 @@ +package com.mtusi.messenger.main.infrastructure.repositories + +interface Repository diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt new file mode 100644 index 00000000..de0bc6ae --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt @@ -0,0 +1,12 @@ +package com.mtusi.messenger.main.infrastructure.repositories.chat + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.repositories.Repository + +interface ChatRepository : Repository { + fun findById(id: String): Chat? + + fun insert(chat: Chat) + + fun findAllAccessible(userId: String): List +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt new file mode 100644 index 00000000..b84d6e57 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt @@ -0,0 +1,24 @@ +package com.mtusi.messenger.main.infrastructure.repositories.chat + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import java.util.concurrent.ConcurrentHashMap + +class InMemoryChatRepository : ChatRepository { + private val byId = ConcurrentHashMap() + + override fun findById(id: String): Chat? = byId[id] + + override fun insert(chat: Chat) { + byId[chat.id] = chat + } + + override fun findAllAccessible(userId: String): List = + byId.values + .filter { userId in it.memberIds } + .sortedWith( + compareBy( + { it.createdAt }, + { it.id } + ) + ) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt new file mode 100644 index 00000000..371c0609 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt @@ -0,0 +1,45 @@ +package com.mtusi.messenger.main.infrastructure.repositories.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList + +class InMemoryMessageRepository : MessageRepository { + private val byChat = ConcurrentHashMap>() + private val locks = ConcurrentHashMap() + + override fun append( + chatId: String, + message: Message + ) { + + val lock = locks.computeIfAbsent(chatId) { + Any() + } + + synchronized(lock) { + byChat.computeIfAbsent(chatId) { + CopyOnWriteArrayList() + }.add(message) + } + } + + override fun findRangeByChatId( + chatId: String, + offset: Int, + count: Int, + ): List { + + val messages = byChat[chatId] + ?: return emptyList() + + // Append-only: indices below an observed size never change, so no snapshot copy is needed. + val end = minOf(messages.size, offset + count) + + if (offset >= end) { + return emptyList() + } + + return List(end - offset) { messages[offset + it] } + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt new file mode 100644 index 00000000..a0279d91 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.infrastructure.repositories.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.repositories.Repository + +interface MessageRepository : Repository { + fun append(chatId: String, message: Message) + fun findRangeByChatId(chatId: String, offset: Int, count: Int): List +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt new file mode 100644 index 00000000..125bae78 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt @@ -0,0 +1,18 @@ +package com.mtusi.messenger.main.infrastructure.repositories.user + +import com.mtusi.messenger.main.infrastructure.dto.User +import java.util.concurrent.ConcurrentHashMap + +class InMemoryUserRepository : UserRepository { + private val byId = ConcurrentHashMap() + + override fun insert(user: User) { + byId[user.id] = user + } + + override fun findById(id: String): User? = byId[id] + + override fun findByUsername(username: String): User? { + return byId.values.find { it.username == username } + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt new file mode 100644 index 00000000..62da5146 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt @@ -0,0 +1,12 @@ +package com.mtusi.messenger.main.infrastructure.repositories.user + +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.repositories.Repository + +interface UserRepository : Repository { + fun insert(user: User) + + fun findById(id: String): User? + + fun findByUsername(username: String): User? +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt new file mode 100644 index 00000000..b21197e7 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt @@ -0,0 +1,23 @@ +package com.mtusi.messenger.main.infrastructure.services.chat + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.utils.Page + +interface ChatService { + fun create( + creatorId: String, + title: String, + memberIds: List, + ): Chat + + fun findAccessible( + userId: String, + chatId: String, + ): Chat + + fun findPageAccessible( + userId: String, + rawLimit: String?, + rawCursor: String?, + ): Page +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt new file mode 100644 index 00000000..9678d267 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt @@ -0,0 +1,92 @@ +package com.mtusi.messenger.main.infrastructure.services.chat + +import com.mtusi.messenger.main.extensions.isValidUuid +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository +import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.utils.decodeCursor +import com.mtusi.messenger.main.utils.encodeCursor +import com.mtusi.messenger.main.utils.nowIsoUtc +import com.mtusi.messenger.main.utils.parseLimit +import java.util.UUID + +private const val MAX_MEMBERS = 100 + +class DefaultChatService( + private val chatRepository: ChatRepository, + private val userRepository: UserRepository, +) : ChatService { + + override fun create( + creatorId: String, + title: String, + memberIds: List, + ): Chat { + + if (memberIds.isEmpty() || memberIds.size > MAX_MEMBERS) { + throw ApiException(ErrorCode.INVALID_REQUEST, "size out of range") + } + + if (memberIds.toSet().size != memberIds.size) { + throw ApiException(ErrorCode.INVALID_REQUEST, "memberIds must be unique") + } + + if (creatorId !in memberIds) { + throw ApiException(ErrorCode.INVALID_REQUEST, "creator must be in members") + } + + for (id in memberIds) { + if (!isValidUuid(id)) + throw ApiException(ErrorCode.INVALID_REQUEST, "invalid member id") + + if (userRepository.findById(id) == null) + throw ApiException(ErrorCode.INVALID_REQUEST, "unknown member") + } + + val chat = Chat( + id = UUID.randomUUID().toString(), + title = title, + memberIds = memberIds, + createdAt = nowIsoUtc(), + ) + chatRepository.insert(chat) + + return chat + } + + override fun findAccessible( + userId: String, + chatId: String, + ): Chat { + + val chat = chatRepository.findById(chatId) + ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + + if (userId !in chat.memberIds) { + throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + } + + return chat + } + + override fun findPageAccessible( + userId: String, + rawLimit: String?, + rawCursor: String?, + ): Page { + + val limit = parseLimit(rawLimit) + val scope = "chats:$userId" + val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 + + val all = chatRepository.findAllAccessible(userId) + val slice = all.drop(start).take(limit) + val nextIndex = start + slice.size + val nextCursor = if (nextIndex < all.size) encodeCursor(scope, nextIndex) else null + + return Page(slice, nextCursor) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt new file mode 100644 index 00000000..52afe12c --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt @@ -0,0 +1,74 @@ +package com.mtusi.messenger.main.infrastructure.services.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository +import com.mtusi.messenger.main.infrastructure.repositories.message.MessageRepository +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.utils.decodeCursor +import com.mtusi.messenger.main.utils.encodeCursor +import com.mtusi.messenger.main.utils.nowIsoUtc +import com.mtusi.messenger.main.utils.parseLimit +import java.util.UUID + +class DefaultMessageService( + private val chatRepository: ChatRepository, + private val messageRepository: MessageRepository, +) : MessageService { + + override fun send( + chatId: String, + senderId: String, + text: String, + ): Message { + + requireChatMembership(chatId, senderId) + + val message = Message( + id = UUID.randomUUID().toString(), + chatId = chatId, + senderId = senderId, + text = text, + createdAt = nowIsoUtc(), + ) + + messageRepository.append(chatId, message) + + return message + } + + override fun findPageByChatId( + chatId: String, + actorId: String, + rawLimit: String?, + rawCursor: String?, + ): Page { + + requireChatMembership(chatId, actorId) + + val limit = parseLimit(rawLimit) + val scope = "messages:$chatId" + val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 + + val window = messageRepository.findRangeByChatId( + chatId = chatId, + offset = start, + count = limit + 1, + ) + + val items = window.take(limit) + val nextCursor = if (window.size > limit) encodeCursor(scope, start + limit) else null + + return Page(items, nextCursor) + } + + private fun requireChatMembership(chatId: String, userId: String) { + val chat = chatRepository.findById(chatId) + ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + + if (userId !in chat.memberIds) { + throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + } + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt new file mode 100644 index 00000000..24f54eb2 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt @@ -0,0 +1,19 @@ +package com.mtusi.messenger.main.infrastructure.services.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.utils.Page + +interface MessageService { + fun send( + chatId: String, + senderId: String, + text: String, + ): Message + + fun findPageByChatId( + chatId: String, + actorId: String, + rawLimit: String?, + rawCursor: String?, + ): Page +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt new file mode 100644 index 00000000..7dd8f22b --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt @@ -0,0 +1,33 @@ +package com.mtusi.messenger.main.infrastructure.services.user + +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.utils.nowIsoUtc +import java.util.UUID + +class DefaultUserService( + private val userRepository: UserRepository, +) : UserService { + + override fun create(username: String, displayName: String): User { + + if (userRepository.findByUsername(username) != null) { + throw ApiException(ErrorCode.CONFLICT, "username already taken") + } + + val user = User( + id = UUID.randomUUID().toString(), + username = username, + displayName = displayName, + createdAt = nowIsoUtc(), + ) + + userRepository.insert(user) + + return user + } + + override fun findById(id: String): User? = userRepository.findById(id) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt new file mode 100644 index 00000000..ad976c1c --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.services.user + +import com.mtusi.messenger.main.infrastructure.dto.User + +interface UserService { + fun create(username: String, displayName: String): User + fun findById(id: String): User? +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ApiException.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ApiException.kt new file mode 100644 index 00000000..90021402 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ApiException.kt @@ -0,0 +1,3 @@ +package com.mtusi.messenger.main.infrastructure.types + +class ApiException(val code: ErrorCode, message: String) : RuntimeException(message) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ErrorCode.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ErrorCode.kt new file mode 100644 index 00000000..d71aef95 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/ErrorCode.kt @@ -0,0 +1,15 @@ +package com.mtusi.messenger.main.infrastructure.types + +import io.ktor.http.HttpStatusCode + +enum class ErrorCode(val wire: String, val status: HttpStatusCode) { + INVALID_REQUEST("invalid_request", HttpStatusCode.BadRequest), + UNAUTHORIZED("unauthorized", HttpStatusCode.Unauthorized), + NOT_FOUND("not_found", HttpStatusCode.NotFound), + CONFLICT("conflict", HttpStatusCode.Conflict), + PAYLOAD_TOO_LARGE("payload_too_large", HttpStatusCode.PayloadTooLarge), + UNSUPPORTED_MEDIA_TYPE("unsupported_media_type", HttpStatusCode.UnsupportedMediaType), + RATE_LIMITED("rate_limited", HttpStatusCode.TooManyRequests), + UNAVAILABLE("unavailable", HttpStatusCode.ServiceUnavailable), + INTERNAL_ERROR("internal_error", HttpStatusCode.InternalServerError), +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/CallLogging.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/CallLogging.kt new file mode 100644 index 00000000..c9148e6b --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/CallLogging.kt @@ -0,0 +1,14 @@ +package com.mtusi.messenger.main.plugins + +import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.plugins.calllogging.CallLogging +import org.slf4j.event.Level + +fun Application.configureCallLogging() = install(CallLogging) { + level = Level.INFO + filter { call -> + val uri = call.request.local.uri + uri.startsWith("/api") || uri.startsWith("/health") + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/ContentNegotiation.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/ContentNegotiation.kt new file mode 100644 index 00000000..beb9fffb --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/ContentNegotiation.kt @@ -0,0 +1,21 @@ +package com.mtusi.messenger.main.plugins + +import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.plugins.contentnegotiation.ContentNegotiation +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNamingStrategy + +@OptIn(ExperimentalSerializationApi::class) +val json = Json { + ignoreUnknownKeys = false + explicitNulls = true + encodeDefaults = true + namingStrategy = JsonNamingStrategy.SnakeCase +} + +fun Application.configureContentNegotiation() = install(ContentNegotiation) { + json(json) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/DefaultHeaders.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/DefaultHeaders.kt new file mode 100644 index 00000000..e7be1a56 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/DefaultHeaders.kt @@ -0,0 +1,7 @@ +package com.mtusi.messenger.main.plugins + +import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.plugins.defaultheaders.DefaultHeaders + +fun Application.configureDefaultHeaders() = install(DefaultHeaders) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt new file mode 100644 index 00000000..46f4d02e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.infrastructure.services.chat.ChatService +import com.mtusi.messenger.main.infrastructure.services.message.MessageService +import com.mtusi.messenger.main.infrastructure.services.user.UserService + +data class Dependencies( + val userService: UserService, + val chatService: ChatService, + val messageService: MessageService, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/RequestId.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/RequestId.kt new file mode 100644 index 00000000..e22ef712 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/RequestId.kt @@ -0,0 +1,20 @@ +package com.mtusi.messenger.main.plugins + +import io.ktor.server.application.Application +import io.ktor.server.application.createApplicationPlugin +import io.ktor.server.application.install +import io.ktor.util.AttributeKey +import java.util.UUID + +val RequestIdKey: AttributeKey = AttributeKey("X-Request-Id") + +private val RequestIdPlugin = createApplicationPlugin("RequestId") { + onCall { call -> + val incoming = call.request.headers["X-Request-Id"]?.takeIf { it.isNotBlank() } + val id = incoming ?: UUID.randomUUID().toString() + call.attributes.put(RequestIdKey, id) + call.response.headers.append("X-Request-Id", id, safeOnly = false) + } +} + +fun Application.configureRequestId() = install(RequestIdPlugin) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt new file mode 100644 index 00000000..8ce80a6d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt @@ -0,0 +1,16 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.infrastructure.controllers.chat.configureChatRouting +import com.mtusi.messenger.main.infrastructure.controllers.health.configureHealthRouting +import com.mtusi.messenger.main.infrastructure.controllers.message.configureMessageRouting +import com.mtusi.messenger.main.infrastructure.controllers.user.configureUserRouting +import io.ktor.server.application.Application +import io.ktor.server.routing.routing + +fun Application.configureRouting(dependencies: Dependencies) = routing { + configureSwaggerRouting() + configureHealthRouting() + configureUserRouting(dependencies.userService) + configureChatRouting(dependencies.chatService, dependencies.userService) + configureMessageRouting(dependencies.messageService, dependencies.userService) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt new file mode 100644 index 00000000..b777ee92 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt @@ -0,0 +1,44 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.extensions.respondError +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import io.ktor.http.HttpStatusCode +import io.ktor.serialization.JsonConvertException +import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.plugins.BadRequestException +import io.ktor.server.plugins.NotFoundException +import io.ktor.server.plugins.UnsupportedMediaTypeException +import io.ktor.server.plugins.statuspages.StatusPages +import kotlinx.serialization.SerializationException + +fun Application.configureStatusPages() = install(StatusPages) { + exception { call, cause -> + call.respondError(cause.code, cause.message ?: cause.code.wire) + } + exception { call, _ -> + call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body") + } + exception { call, _ -> + call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body") + } + exception { call, _ -> + call.respondError(ErrorCode.INVALID_REQUEST, "invalid request") + } + exception { call, _ -> + call.respondError(ErrorCode.NOT_FOUND, "not found") + } + exception { call, _ -> + call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type") + } + exception { call, _ -> + call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") + } + status(HttpStatusCode.NotFound) { call, _ -> + call.respondError(ErrorCode.NOT_FOUND, "not found") + } + status(HttpStatusCode.MethodNotAllowed) { call, _ -> + call.respondError(ErrorCode.NOT_FOUND, "not found") + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Swagger.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Swagger.kt new file mode 100644 index 00000000..8f1d4f61 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Swagger.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.plugins + +import io.ktor.server.plugins.swagger.swaggerUI +import io.ktor.server.routing.Routing + +fun Routing.configureSwaggerRouting() { + swaggerUI(path = "docs", swaggerFile = "openapi.json") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt new file mode 100644 index 00000000..e4e8ce6e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt @@ -0,0 +1,6 @@ +package com.mtusi.messenger.main.utils + +data class Page( + val items: List, + val nextCursor: String?, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt new file mode 100644 index 00000000..415bca63 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt @@ -0,0 +1,40 @@ +package com.mtusi.messenger.main.utils + +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import java.util.Base64 +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +private const val DEFAULT_LIMIT = 50 +private const val MAX_LIMIT = 100 + +private val json = Json { ignoreUnknownKeys = true } + +@Serializable +private data class Cursor(val scope: String, val index: Int) + +fun encodeCursor(scope: String, index: Int): String { + val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, index)) + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.toByteArray(Charsets.UTF_8)) +} + +fun decodeCursor(raw: String, expectedScope: String): Int { + val decoded = try { + val bytes = Base64.getUrlDecoder().decode(raw) + json.decodeFromString(Cursor.serializer(), String(bytes, Charsets.UTF_8)) + } catch (_: Throwable) { + throw ApiException(ErrorCode.INVALID_REQUEST, "invalid cursor") + } + if (decoded.scope != expectedScope || decoded.index < 0) { + throw ApiException(ErrorCode.INVALID_REQUEST, "cursor does not belong to this resource") + } + return decoded.index +} + +fun parseLimit(raw: String?): Int { + if (raw == null) return DEFAULT_LIMIT + val v = raw.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") + if (v !in 1..MAX_LIMIT) throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range") + return v +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt new file mode 100644 index 00000000..e8f7d1e4 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.utils + +import java.time.Instant +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter + +private val RFC3339: DateTimeFormatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + .withZone(ZoneOffset.UTC) + +fun nowIsoUtc(): String = RFC3339.format(Instant.now()) diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt new file mode 100644 index 00000000..19ab2b57 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt @@ -0,0 +1,31 @@ +package com.mtusi.messenger.main.utils + +import com.mtusi.messenger.main.extensions.isValidUuid +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode + +private val USERNAME = Regex("^[a-z0-9_]{3,32}$") + +fun codePoints(value: String): Int = value.codePointCount(0, value.length) + +fun requireUsername(value: String) { + if (!USERNAME.matches(value)) { + throw ApiException(ErrorCode.INVALID_REQUEST, "invalid username") + } +} + +fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) { + if (value.isBlank()) { + throw ApiException(ErrorCode.INVALID_REQUEST, "$field must not be blank") + } + val n = codePoints(value) + if (n !in min..max) { + throw ApiException(ErrorCode.INVALID_REQUEST, "$field length out of range") + } +} + +fun requireUuid(value: String, field: String) { + if (!isValidUuid(value)) { + throw ApiException(ErrorCode.INVALID_REQUEST, "invalid $field") + } +} diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf new file mode 100644 index 00000000..ce1c5691 --- /dev/null +++ b/src/main/resources/application.conf @@ -0,0 +1,14 @@ +ktor { + application { + modules = [com.mtusi.messenger.main.AppKt.module] + } + + deployment { + host = "0.0.0.0" + host = ${?APP_HOST} + port = 8080 + port = ${?APP_PORT} + shutdownGracePeriod = 3000 + shutdownTimeout = 10000 + } +} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 00000000..5416c44d --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + %d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%thread] %logger{36} - %msg%n + + + + + + + + diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt new file mode 100644 index 00000000..5b310c46 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt @@ -0,0 +1,43 @@ +package com.mtusi.messenger.main.infrastructure.controllers.chat + +import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.call.body +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.http.HttpStatusCode +import kotlin.test.Test +import kotlin.test.assertEquals + +class ChatControllerTest { + + @Test + fun `foreign chat returns 404 for non-member`() = runApp { client -> + val alice = client.createUser("alice") + val bob = client.createUser("bob") + val chat = client.createChat(alice, title = "secret", memberIds = listOf(alice.id)) + + val response = client.get("/api/v1/chats/${chat.id}") { + header("X-User-Id", bob.id) + } + + assertEquals(HttpStatusCode.NotFound, response.status) + assertEquals("not_found", response.body().error.code) + } + + @Test + fun `member can read own chat`() = runApp { client -> + val alice = client.createUser("alice") + val created = client.createChat(alice, title = "notes", memberIds = listOf(alice.id)) + + val response = client.get("/api/v1/chats/${created.id}") { + header("X-User-Id", alice.id) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(created.id, response.body().id) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt new file mode 100644 index 00000000..fbe943fd --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt @@ -0,0 +1,22 @@ +package com.mtusi.messenger.main.infrastructure.controllers.health + +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.request.get +import io.ktor.http.HttpStatusCode +import kotlin.test.Test +import kotlin.test.assertEquals + +class HealthControllerTest { + + @Test + fun `live returns 200`() = runApp { client -> + val response = client.get("/health/live") + assertEquals(HttpStatusCode.OK, response.status) + } + + @Test + fun `ready returns 200`() = runApp { client -> + val response = client.get("/health/ready") + assertEquals(HttpStatusCode.OK, response.status) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt new file mode 100644 index 00000000..ea3cf062 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt @@ -0,0 +1,74 @@ +package com.mtusi.messenger.main.infrastructure.controllers.message + +import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest +import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.call.body +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlin.test.Test +import kotlin.test.assertEquals + +class MessageConcurrencyTest { + + @Test + fun `parallel senders produce exactly N unique messages`() = runApp { client -> + val alice = client.createUser("alice") + val chat = client.createChat(alice, title = "load", memberIds = listOf(alice.id)) + + val workers = 10 + val perWorker = 10 + val total = workers * perWorker + + coroutineScope { + (0 until workers).map { w -> + async { + repeat(perWorker) { i -> + val response = client.post("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "w$w-i$i")) + } + assertEquals(HttpStatusCode.Created, response.status) + } + } + }.awaitAll() + } + + val collected = mutableListOf() + var cursor: String? = null + + do { + val response = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + url { + parameters.append("limit", "100") + if (cursor != null) parameters.append("cursor", cursor!!) + } + } + assertEquals(HttpStatusCode.OK, response.status) + + val page = response.body() + collected += page.items.map { it.text } + cursor = page.nextCursor + } while (cursor != null) + + assertEquals(total, collected.size) + assertEquals(total, collected.toSet().size) + + val expected = buildSet { + for (w in 0 until workers) for (i in 0 until perWorker) add("w$w-i$i") + } + assertEquals(expected, collected.toSet()) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt new file mode 100644 index 00000000..d689ece9 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt @@ -0,0 +1,190 @@ +package com.mtusi.messenger.main.infrastructure.controllers.message + +import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest +import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.call.body +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +class MessageControllerTest { + + @Test + fun `empty text returns 400 invalid_request`() = runApp { client -> + val alice = client.createUser("alice") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + val response = client.post("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "")) + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("invalid_request", response.body().error.code) + } + + @Test + fun `foreign chat returns 404 when sending`() = runApp { client -> + val alice = client.createUser("alice") + val bob = client.createUser("bob") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + val response = client.post("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", bob.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "hi")) + } + + assertEquals(HttpStatusCode.NotFound, response.status) + assertEquals("not_found", response.body().error.code) + } + + @Test + fun `foreign chat returns 404 when listing`() = runApp { client -> + val alice = client.createUser("alice") + val bob = client.createUser("bob") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + val response = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", bob.id) + } + + assertEquals(HttpStatusCode.NotFound, response.status) + } + + @Test + fun `pagination walks all messages exactly once`() = runApp { client -> + val alice = client.createUser("alice") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + val total = 25 + repeat(total) { i -> + val r = client.post("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "m$i")) + } + assertEquals(HttpStatusCode.Created, r.status) + } + + val collected = mutableListOf() + var cursor: String? = null + var pages = 0 + + do { + val response = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + url { + parameters.append("limit", "10") + if (cursor != null) parameters.append("cursor", cursor!!) + } + } + assertEquals(HttpStatusCode.OK, response.status) + + val page = response.body() + collected += page.items.map { it.text } + cursor = page.nextCursor + pages++ + } while (cursor != null) + + assertEquals(3, pages) + assertEquals(total, collected.size) + assertEquals(total, collected.toSet().size) + assertEquals((0 until total).map { "m$it" }, collected) + } + + @Test + fun `history that is an exact multiple of limit ends with null next_cursor`() = runApp { client -> + val alice = client.createUser("alice") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + repeat(20) { i -> + client.post("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "m$i")) + } + } + + val first = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + url { parameters.append("limit", "10") } + }.body() + + val cursor = first.nextCursor + assertNotNull(cursor) + + val second = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + url { + parameters.append("limit", "10") + parameters.append("cursor", cursor) + } + }.body() + + assertEquals((10 until 20).map { "m$it" }, second.items.map { it.text }) + assertNull(second.nextCursor) + } + + @Test + fun `last page has null next_cursor`() = runApp { client -> + val alice = client.createUser("alice") + val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) + + val response = client.get("/api/v1/chats/${chat.id}/messages") { + header("X-User-Id", alice.id) + } + + assertEquals(HttpStatusCode.OK, response.status) + val page = response.body() + assertEquals(0, page.items.size) + assertNull(page.nextCursor) + } + + @Test + fun `foreign cursor returns 400`() = runApp { client -> + val alice = client.createUser("alice") + val chatA = client.createChat(alice, title = "a", memberIds = listOf(alice.id)) + val chatB = client.createChat(alice, title = "b", memberIds = listOf(alice.id)) + + repeat(2) { i -> + client.post("/api/v1/chats/${chatA.id}/messages") { + header("X-User-Id", alice.id) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "a$i")) + } + } + + val firstA = client.get("/api/v1/chats/${chatA.id}/messages") { + header("X-User-Id", alice.id) + url { parameters.append("limit", "1") } + }.body() + + val cursor = firstA.nextCursor + assertNotNull(cursor) + + val response = client.get("/api/v1/chats/${chatB.id}/messages") { + header("X-User-Id", alice.id) + url { + parameters.append("limit", "1") + parameters.append("cursor", cursor) + } + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("invalid_request", response.body().error.code) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt new file mode 100644 index 00000000..f2f689a5 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt @@ -0,0 +1,72 @@ +package com.mtusi.messenger.main.infrastructure.controllers.user + +import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.call.body +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +class UserControllerTest { + + @Test + fun `create user returns 201 and echoes fields`() = runApp { client -> + val response = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = "alice", displayName = "Alice")) + } + + assertEquals(HttpStatusCode.Created, response.status) + } + + @Test + fun `invalid JSON body returns 400 invalid_request`() = runApp { client -> + val response = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody("{not json") + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + + val body = response.body() + assertEquals("invalid_request", body.error.code) + assertNotNull(body.error.requestId) + } + + @Test + fun `duplicate username returns 409 conflict`() = runApp { client -> + client.createUser(username = "bob") + + val response = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = "bob", displayName = "Bob 2")) + } + + assertEquals(HttpStatusCode.Conflict, response.status) + assertEquals("conflict", response.body().error.code) + } + + @Test + fun `missing X-User-Id on protected endpoint returns 401`() = runApp { client -> + val response = client.get("/api/v1/users/me") + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals("unauthorized", response.body().error.code) + } + + @Test + fun `unknown X-User-Id returns 401`() = runApp { client -> + val response = client.get("/api/v1/users/me") { + header("X-User-Id", "00000000-0000-0000-0000-000000000000") + } + assertEquals(HttpStatusCode.Unauthorized, response.status) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt new file mode 100644 index 00000000..23e36884 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt @@ -0,0 +1,58 @@ +package com.mtusi.messenger.main.infrastructure.repositories.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +private const val CHAT_ID = "chat" + +class InMemoryMessageRepositoryTest { + + private fun repositoryWith(size: Int): InMemoryMessageRepository { + + val repository = InMemoryMessageRepository() + + repeat(size) { i -> + repository.append( + CHAT_ID, + Message( + id = "m$i", + chatId = CHAT_ID, + senderId = "u", + text = "t$i", + createdAt = "2026-01-01T00:00:00.000Z", + ), + ) + } + + return repository + } + + @Test + fun `returns requested window in append order`() { + val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 3, count = 4) + assertEquals(listOf("m3", "m4", "m5", "m6"), range.map { it.id }) + } + + @Test + fun `window is clipped at the end of history`() { + val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 8, count = 5) + assertEquals(listOf("m8", "m9"), range.map { it.id }) + } + + @Test + fun `offset past the end returns empty`() { + assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 10, count = 5).isEmpty()) + } + + @Test + fun `huge offset does not overflow`() { + assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = Int.MAX_VALUE - 1, count = 51).isEmpty()) + } + + @Test + fun `unknown chat returns empty`() { + assertTrue(InMemoryMessageRepository().findRangeByChatId("missing", offset = 0, count = 50).isEmpty()) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt new file mode 100644 index 00000000..6ce1f537 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt @@ -0,0 +1,71 @@ +package com.mtusi.messenger.main.support + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest +import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.module +import io.ktor.client.HttpClient +import io.ktor.client.call.body +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.testing.ApplicationTestBuilder +import io.ktor.server.testing.testApplication +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNamingStrategy + +@OptIn(ExperimentalSerializationApi::class) +val testJson = Json { + ignoreUnknownKeys = true + encodeDefaults = true + namingStrategy = JsonNamingStrategy.SnakeCase +} + +fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApplication { + application { + module() + } + val client = createClient { + install(ContentNegotiation) { + json(testJson) + } + } + block(client) +} + +suspend fun HttpClient.createUser(username: String, displayName: String = username): User { + val response = post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = username, displayName = displayName)) + } + check(response.status == HttpStatusCode.Created) { "createUser failed: ${response.status}" } + return response.body() +} + +suspend fun HttpClient.createChat( + creator: User, + title: String, + memberIds: List, +): Chat { + val response = post("/api/v1/chats") { + header("X-User-Id", creator.id) + contentType(ContentType.Application.Json) + setBody(CreateChatRequest(title = title, memberIds = memberIds)) + } + check(response.status == HttpStatusCode.Created) { "createChat failed: ${response.status}" } + return response.body() +} + +fun HttpResponse.header(name: String): String? = headers[name] + +val HttpResponse.requestId: String? + get() = headers[HttpHeaders.XRequestId] diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf new file mode 100644 index 00000000..cbc3abad --- /dev/null +++ b/src/test/resources/application.conf @@ -0,0 +1,10 @@ +ktor { + application { + modules = [com.mtusi.messenger.main.AppKt.module] + } + + deployment { + host = "127.0.0.1" + port = 0 + } +} -- 2.54.0 From b38a33308d0394d212eb5d96e978955aa42c2fe6 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Thu, 8 Oct 2026 20:26:09 +0300 Subject: [PATCH 2/7] Completed for a grade of three --- .gitignore | 1 + build.gradle.kts | 39 ++++- compose.yaml | 48 +++++- gradle/libs.versions.toml | 43 ++++- .../_template/config}/application.conf | 4 +- run/_template/config/authentication.conf | 4 + run/_template/config/database.conf | 9 ++ scripts/init-secrets.sh | 16 ++ scripts/restart.sh | 7 + .../kotlin/com/mtusi/messenger/main/App.kt | 29 ++-- .../main/compat/serializers/UUIDSerializer.kt | 31 ++++ .../messenger/main/config/ConfigModule.kt | 8 + .../authentication/AuthenticationConfig.kt | 8 + .../DefaultAuthenticationConfig.kt | 11 ++ .../SerialAuthenticationConfig.kt | 9 ++ .../main/config/database/DatabaseConfig.kt | 19 +++ .../config/database/DefaultDatabaseConfig.kt | 11 ++ .../config/database/SerialDatabaseConfig.kt | 15 ++ .../main/extensions/ApplicationCall.kt | 31 ++-- .../_common/parameters/PageParameters.kt | 31 ++++ .../AuthenticationController.kt | 55 +++++++ .../responses/SessionResponse.kt | 13 ++ .../controllers/chat/ChatController.kt | 131 ++++++++++----- .../chat/responses/ChatPageResponse.kt | 10 -- .../controllers/health/HealthController.kt | 21 +++ .../controllers/message/MessageController.kt | 103 +++++++----- .../message/responses/MessagePageResponse.kt | 10 -- .../controllers/user/UserController.kt | 62 +++++-- .../user/requests/CreateUserRequest.kt | 1 + .../messenger/main/infrastructure/dto/Chat.kt | 8 +- .../main/infrastructure/dto/Message.kt | 10 +- .../main/infrastructure/dto/PageResponse.kt | 9 ++ .../messenger/main/infrastructure/dto/User.kt | 6 +- .../dto/authentication/IssuedSession.kt | 6 + .../dto/authentication/Session.kt | 11 ++ .../dto/authentication/UserCredentials.kt | 8 + .../models/authentication/SessionModel.kt | 13 ++ .../models/chat/ChatMemberModel.kt | 13 ++ .../infrastructure/models/chat/ChatModel.kt | 12 ++ .../models/message/MessageModel.kt | 16 ++ .../infrastructure/models/user/UserModel.kt | 14 ++ .../repositories/RepositoriesModule.kt | 8 + .../session/ExposedSessionRepository.kt | 67 ++++++++ .../session/SessionRepository.kt | 25 +++ .../repositories/chat/ChatRepository.kt | 29 +++- .../chat/ExposedChatRepository.kt | 134 ++++++++++++++++ .../chat/InMemoryChatRepository.kt | 24 --- .../message/ExposedMessageRepository.kt | 81 ++++++++++ .../message/InMemoryMessageRepository.kt | 45 ------ .../repositories/message/MessageRepository.kt | 19 ++- .../user/ExposedUserRepository.kt | 82 ++++++++++ .../user/InMemoryUserRepository.kt | 18 --- .../repositories/user/UserRepository.kt | 24 ++- .../infrastructure/services/ServicesModule.kt | 8 + .../authentication/AuthenticationService.kt | 27 ++++ .../DefaultAuthenticationService.kt | 91 +++++++++++ .../services/chat/ChatService.kt | 26 +-- .../services/chat/DefaultChatService.kt | 95 +++++------ .../chat/results/ChatCreationResult.kt | 17 ++ .../services/chat/results/ChatPageResult.kt | 16 ++ .../services/hashing/DefaultHashingService.kt | 123 ++++++++++++++ .../services/hashing/HashingService.kt | 18 +++ .../hashing/types/HashingAlgorithm.kt | 5 + .../services/message/DefaultMessageService.kt | 92 +++++------ .../services/message/MessageService.kt | 25 +-- .../message/results/MessageCreationResult.kt | 15 ++ .../message/results/MessagePageResult.kt | 17 ++ .../services/user/DefaultUserService.kt | 42 +++-- .../services/user/UserService.kt | 15 +- .../user/results/UserCreationResult.kt | 15 ++ .../infrastructure/types/AuthChallenge.kt | 6 + .../mtusi/messenger/main/plugins/Database.kt | 70 ++++++++ .../messenger/main/plugins/Dependencies.kt | 11 -- .../com/mtusi/messenger/main/plugins/Koin.kt | 27 ++++ .../mtusi/messenger/main/plugins/Routing.kt | 10 +- .../messenger/main/plugins/StatusPages.kt | 24 ++- .../plugins/authentication/Authentication.kt | 48 ++++++ .../authentication/CredentialsPrincipal.kt | 7 + .../plugins/authentication/UserPrincipal.kt | 8 + .../providers/BasicCredentialsProvider.kt | 66 ++++++++ .../providers/BearerSessionProvider.kt | 71 ++++++++ .../com/mtusi/messenger/main/utils/Hashing.kt | 10 ++ .../com/mtusi/messenger/main/utils/Page.kt | 6 - .../mtusi/messenger/main/utils/Pagination.kt | 66 +++++--- .../com/mtusi/messenger/main/utils/Time.kt | 21 ++- .../mtusi/messenger/main/utils/Validation.kt | 11 +- .../utils/exposed/operations/RowGreater.kt | 32 ++++ src/main/resources/application.conf | 22 +++ src/main/resources/migrations/V1__init.sql | 50 ++++++ .../AuthenticationControllerTest.kt | 151 ++++++++++++++++++ .../controllers/chat/ChatControllerTest.kt | 133 +++++++++++++-- .../health/HealthControllerTest.kt | 2 +- .../message/MessageConcurrencyTest.kt | 15 +- .../message/MessageControllerTest.kt | 59 +++---- .../controllers/user/UserControllerTest.kt | 132 +++++++++++++-- .../message/InMemoryMessageRepositoryTest.kt | 58 ------- .../hashing/DefaultHashingServiceTest.kt | 45 ++++++ .../main/plugins/DatabaseMigrationTest.kt | 49 ++++++ .../mtusi/messenger/main/support/TestApp.kt | 91 +++++++++-- .../messenger/main/support/TestDatabase.kt | 24 +++ 100 files changed, 2832 insertions(+), 602 deletions(-) rename {src/test/resources => run/_template/config}/application.conf (87%) create mode 100644 run/_template/config/authentication.conf create mode 100644 run/_template/config/database.conf create mode 100755 scripts/init-secrets.sh create mode 100755 scripts/restart.sh create mode 100644 src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt create mode 100644 src/main/resources/migrations/V1__init.sql create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt delete mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt diff --git a/.gitignore b/.gitignore index 0fe411f8..6137e904 100644 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,6 @@ coverage/ .gradle/ .kotlin/ !gradle/wrapper/ +/run/development/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/build.gradle.kts b/build.gradle.kts index d7d24c0e..cfb31b6c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,12 +1,13 @@ plugins { alias(libs.plugins.kotlin) alias(libs.plugins.kotlin.serialization) + alias(libs.plugins.ksp) alias(libs.plugins.shadow) id("application") } group = "com.mtusi.messenger" -version = "1.0.0" +version = "2.0.0" repositories { mavenCentral() @@ -14,10 +15,12 @@ repositories { dependencies { implementation(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.serialization.hocon) implementation(libs.logback.classic) implementation(ktorLibs.server.core) implementation(ktorLibs.server.netty) + implementation(ktorLibs.server.auth) implementation(ktorLibs.server.contentNegotiation) implementation(ktorLibs.server.statusPages) implementation(ktorLibs.server.callLogging) @@ -25,16 +28,40 @@ dependencies { implementation(ktorLibs.server.swagger) implementation(ktorLibs.serialization.kotlinx.json) + implementation(libs.koin.core) + implementation(libs.koin.ktor) + implementation(libs.koin.annotations) + ksp(libs.koin.compiler) + + implementation(libs.exposed.core) + implementation(libs.exposed.jdbc) + implementation(libs.exposed.kotlin.datetime) + + implementation(libs.postgres) + implementation(libs.hikaricp) + implementation(libs.flyway) + implementation(libs.flyway.postgresql) + + implementation(libs.bouncycastle) + testImplementation(kotlin("test")) testImplementation(ktorLibs.server.testHost) testImplementation(ktorLibs.client.contentNegotiation) testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.koin.test) + testImplementation(libs.testContainers) + testImplementation(libs.testContainers.postgresql) } kotlin { jvmToolchain(21) } +ksp { + arg("KOIN_CONFIG_CHECK", "true") + arg("KOIN_DEFAULT_MODULE", "false") +} + application { mainClass = "io.ktor.server.netty.EngineMain" applicationDefaultJvmArgs = listOf("-Dio.ktor.development=false") @@ -61,6 +88,16 @@ tasks { } getByName("run") { + + val configArgs = File("run/development/config") + .listFiles() + ?.filter { it.extension == "conf" } + ?.map { + "-config=config/${it.name}" + } + ?: emptyList() + + args = configArgs workingDir = file("run/development") } } diff --git a/compose.yaml b/compose.yaml index 31417a30..5e562850 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,51 @@ +name: mtusi-messenger-lab2 + services: - messenger: + + postgres: + image: postgres:17.6-alpine3.22 + container_name: mtusi-lab2-postgres + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: + - db_password + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 10s + restart: unless-stopped + + api: build: . image: mtusi-messenger:lab2 - container_name: mtusi-messenger-lab2 - ports: - - "127.0.0.1:8080:8080" + container_name: mtusi-lab2-api + depends_on: + postgres: + condition: service_healthy environment: APP_HOST: "0.0.0.0" APP_PORT: "8080" + DB_HOST: postgres + DB_PORT: "5432" + DB_NAME: messenger + DB_USER: messenger + DB_PASSWORD_FILE: /run/secrets/db_password + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + secrets: + - db_password + ports: + - "127.0.0.1:8080:8080" restart: unless-stopped + +secrets: + db_password: + file: ./secrets/db_password + +volumes: + postgres-data: diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5e51593a..ad76a4c8 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,16 +1,49 @@ [versions] -kotlin = "2.1.21" -kotlinx-serialization = "1.8.0" -logback = "1.5.12" -shadow = "8.3.5" +kotlin = "2.3.20" +ksp = "2.3.0" +kotlinx-serialization = "1.10.0" kotlinx-coroutines = "1.9.0" +logback = "1.5.13" +shadow = "8.3.5" +koin = "4.1.0-RC1" +koin-ktor = "4.1.0-Beta8" +koin-compiler = "2.0.0" +exposed = "1.0.0" +postgres = "42.7.3" +hikaricp = "6.3.0" +flyway = "11.9.0" +bouncycastle = "1.81" +test-containers = "1.21.0" [plugins] kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } [libraries] kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } -logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } +kotlinx-serialization-hocon = { module = "org.jetbrains.kotlinx:kotlinx-serialization-hocon", version.ref = "kotlinx-serialization" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } + +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } + +koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" } +koin-ktor = { module = "io.insert-koin:koin-ktor3", version.ref = "koin-ktor" } +koin-annotations = { module = "io.insert-koin:koin-annotations", version.ref = "koin-compiler" } +koin-compiler = { module = "io.insert-koin:koin-ksp-compiler", version.ref = "koin-compiler" } +koin-test = { module = "io.insert-koin:koin-test", version.ref = "koin" } + +exposed-core = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" } +exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "exposed" } +exposed-kotlin-datetime = { module = "org.jetbrains.exposed:exposed-kotlin-datetime", version.ref = "exposed" } + +postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" } +hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" } +flyway = { module = "org.flywaydb:flyway-core", version.ref = "flyway" } +flyway-postgresql = { module = "org.flywaydb:flyway-database-postgresql", version.ref = "flyway" } + +bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } + +testContainers = { module = "org.testcontainers:testcontainers", version.ref = "test-containers" } +testContainers-postgresql = { module = "org.testcontainers:postgresql", version.ref = "test-containers" } diff --git a/src/test/resources/application.conf b/run/_template/config/application.conf similarity index 87% rename from src/test/resources/application.conf rename to run/_template/config/application.conf index cbc3abad..d9373003 100644 --- a/src/test/resources/application.conf +++ b/run/_template/config/application.conf @@ -1,10 +1,12 @@ ktor { + application { modules = [com.mtusi.messenger.main.AppKt.module] } deployment { host = "127.0.0.1" - port = 0 + port = 8080 } + } diff --git a/run/_template/config/authentication.conf b/run/_template/config/authentication.conf new file mode 100644 index 00000000..8debebf3 --- /dev/null +++ b/run/_template/config/authentication.conf @@ -0,0 +1,4 @@ +authentication { + realm = "messenger" + sessionTtlSeconds = 3600 +} diff --git a/run/_template/config/database.conf b/run/_template/config/database.conf new file mode 100644 index 00000000..6de16a67 --- /dev/null +++ b/run/_template/config/database.conf @@ -0,0 +1,9 @@ +database { + host = "localhost" + port = 5432 + name = "messenger" + username = "username" + password = "password" + maxPoolSize = 10 + connectionTimeoutMs = 2000 +} diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..1700f205 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Creates local secrets for the Compose stack. Never overwrites an existing secret: +# the PostgreSQL volume is initialised with the first password and keeps it. +set -eu +cd "$(dirname "$0")/.." + +mkdir -p secrets + +if [ ! -s secrets/db_password ]; then + # Readable by the non-root users inside the api/postgres containers (bind-mounted as is). + umask 022 + openssl rand -hex 24 > secrets/db_password + echo "created secrets/db_password" +else + echo "secrets/db_password already exists, keeping it" +fi diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..6fd26f11 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Restarts the API and PostgreSQL, keeping the named volume (no `down -v`, no re-seed). +set -eu +cd "$(dirname "$0")/.." + +docker compose stop api postgres +docker compose up -d --wait postgres api diff --git a/src/main/kotlin/com/mtusi/messenger/main/App.kt b/src/main/kotlin/com/mtusi/messenger/main/App.kt index 366cb856..31e47039 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/App.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/App.kt @@ -1,15 +1,11 @@ package com.mtusi.messenger.main -import com.mtusi.messenger.main.infrastructure.repositories.chat.InMemoryChatRepository -import com.mtusi.messenger.main.infrastructure.repositories.message.InMemoryMessageRepository -import com.mtusi.messenger.main.infrastructure.repositories.user.InMemoryUserRepository -import com.mtusi.messenger.main.infrastructure.services.chat.DefaultChatService -import com.mtusi.messenger.main.infrastructure.services.message.DefaultMessageService -import com.mtusi.messenger.main.infrastructure.services.user.DefaultUserService -import com.mtusi.messenger.main.plugins.Dependencies +import com.mtusi.messenger.main.plugins.authentication.configureAuthentication import com.mtusi.messenger.main.plugins.configureCallLogging import com.mtusi.messenger.main.plugins.configureContentNegotiation +import com.mtusi.messenger.main.plugins.configureDatabase import com.mtusi.messenger.main.plugins.configureDefaultHeaders +import com.mtusi.messenger.main.plugins.configureKoin import com.mtusi.messenger.main.plugins.configureRequestId import com.mtusi.messenger.main.plugins.configureRouting import com.mtusi.messenger.main.plugins.configureStatusPages @@ -19,24 +15,17 @@ import io.ktor.server.netty.EngineMain fun main(args: Array): Unit = EngineMain.main(args) fun Application.module() { - val userRepository = InMemoryUserRepository() - val chatRepository = InMemoryChatRepository() - val messageRepository = InMemoryMessageRepository() - val userService = DefaultUserService(userRepository) - val chatService = DefaultChatService(chatRepository, userRepository) - val messageService = DefaultMessageService(chatRepository, messageRepository) - - val dependencies = Dependencies( - userService = userService, - chatService = chatService, - messageService = messageService, - ) + configureKoin() + configureDatabase() configureContentNegotiation() configureDefaultHeaders() configureRequestId() configureCallLogging() configureStatusPages() - configureRouting(dependencies) + + configureAuthentication() + configureRouting() + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt b/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt new file mode 100644 index 00000000..5a1ccff8 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt @@ -0,0 +1,31 @@ +package com.mtusi.messenger.main.compat.serializers + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import java.util.UUID + +typealias SerialUUID = @Serializable(UUIDSerializer::class) UUID + +object UUIDSerializer : KSerializer { + + override val descriptor = PrimitiveSerialDescriptor( + serialName = "UUID", + kind = PrimitiveKind.STRING + ) + + override fun deserialize(decoder: Decoder): UUID { + return decoder.decodeString().run(UUID::fromString) + } + + override fun serialize( + encoder: Encoder, + value: UUID + ) { + encoder.encodeString(value.toString()) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt b/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt new file mode 100644 index 00000000..e4763008 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.config + +import org.koin.core.annotation.ComponentScan +import org.koin.core.annotation.Module + +@Module(createdAtStart = true) +@ComponentScan +class ConfigModule diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt new file mode 100644 index 00000000..bef24b8f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.config.authentication + +interface AuthenticationConfig { + + val realm: String + val sessionTtlSeconds: Long + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt new file mode 100644 index 00000000..7be2ab3f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.config.authentication + +import io.ktor.server.application.Application +import io.ktor.server.config.getAs +import org.koin.core.annotation.Provided +import org.koin.core.annotation.Single + +@Single +class DefaultAuthenticationConfig( + @Provided app: Application +) : AuthenticationConfig by app.environment.config.property("authentication").getAs() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt new file mode 100644 index 00000000..aa2f51cf --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.config.authentication + +import kotlinx.serialization.Serializable + +@Serializable +data class SerialAuthenticationConfig( + override val realm: String, + override val sessionTtlSeconds: Long +) : AuthenticationConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt new file mode 100644 index 00000000..e679f562 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt @@ -0,0 +1,19 @@ +package com.mtusi.messenger.main.config.database + +interface DatabaseConfig { + + val host: String + val port: Int + val name: String + + val username: String + val password: String? + val passwordFile: String? + + val maxPoolSize: Int + val connectionTimeoutMs: Long + + val jdbcConnectionUrl: String + get() = "jdbc:postgresql://$host:$port/$name" + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt new file mode 100644 index 00000000..72a6c044 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.config.database + +import io.ktor.server.application.Application +import io.ktor.server.config.getAs +import org.koin.core.annotation.Provided +import org.koin.core.annotation.Single + +@Single +class DefaultDatabaseConfig( + @Provided app: Application +) : DatabaseConfig by app.environment.config.property("database").getAs() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt new file mode 100644 index 00000000..c4f11b84 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt @@ -0,0 +1,15 @@ +package com.mtusi.messenger.main.config.database + +import kotlinx.serialization.Serializable + +@Serializable +data class SerialDatabaseConfig( + override val host: String, + override val port: Int, + override val name: String, + override val username: String, + override val password: String? = null, + override val passwordFile: String? = null, + override val maxPoolSize: Int, + override val connectionTimeoutMs: Long +) : DatabaseConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt index c6b1bb5b..0fc40818 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt @@ -1,11 +1,12 @@ package com.mtusi.messenger.main.extensions -import com.mtusi.messenger.main.infrastructure.dto.User -import com.mtusi.messenger.main.infrastructure.services.user.UserService -import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.AuthChallenge import com.mtusi.messenger.main.infrastructure.types.ErrorCode import com.mtusi.messenger.main.plugins.RequestIdKey +import com.mtusi.messenger.main.plugins.authentication.UserPrincipal +import io.ktor.http.HttpHeaders import io.ktor.server.application.ApplicationCall +import io.ktor.server.auth.principal import io.ktor.server.response.header import io.ktor.server.response.respond import kotlinx.serialization.Serializable @@ -20,25 +21,17 @@ data class ErrorDetails( val requestId: String, ) -suspend fun ApplicationCall.respondError(code: ErrorCode, message: String) { +suspend fun ApplicationCall.respondError( + code: ErrorCode, + message: String, + challenge: String = AuthChallenge.BEARER, +) { val requestId = attributes[RequestIdKey] if (code == ErrorCode.UNAUTHORIZED) { - response.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"") + response.header(HttpHeaders.WWWAuthenticate, challenge) } respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId))) } -private val UUID_REGEX = Regex( - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" -) - -fun isValidUuid(value: String): Boolean = UUID_REGEX.matches(value) - -fun ApplicationCall.requireCurrentUser(userService: UserService): User { - val header = request.headers["X-User-Id"]?.trim() - if (header.isNullOrEmpty() || !isValidUuid(header)) { - throw ApiException(ErrorCode.UNAUTHORIZED, "missing or invalid X-User-Id") - } - return userService.findById(header) - ?: throw ApiException(ErrorCode.UNAUTHORIZED, "unknown user") -} +val ApplicationCall.currentUser: UserPrincipal + get() = principal()!! diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt new file mode 100644 index 00000000..043b686e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt @@ -0,0 +1,31 @@ +package com.mtusi.messenger.main.infrastructure.controllers._common.parameters + +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import io.ktor.server.application.ApplicationCall + +private const val DEFAULT_LIMIT = 50 +private const val MAX_LIMIT = 100 + +data class PageParameters( + val limit: Int, + val cursor: String? +) + +fun ApplicationCall.pageParameters(): PageParameters { + + val query = request.queryParameters + + val limit = query["limit"] + ?.let { it.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") } + ?: DEFAULT_LIMIT + + if (limit !in 1..MAX_LIMIT) { + throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range") + } + + val cursor = query["cursor"] + ?.takeIf { it.isNotEmpty() } + + return PageParameters(limit, cursor) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt new file mode 100644 index 00000000..90f6e012 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt @@ -0,0 +1,55 @@ +package com.mtusi.messenger.main.infrastructure.controllers.authentication + +import com.mtusi.messenger.main.extensions.currentUser +import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse +import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService +import com.mtusi.messenger.main.plugins.authentication.CREDENTIALS_AUTH +import com.mtusi.messenger.main.plugins.authentication.CredentialsPrincipal +import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH +import com.mtusi.messenger.main.plugins.suspendedTransaction +import io.ktor.http.HttpStatusCode +import io.ktor.server.auth.authenticate +import io.ktor.server.auth.principal +import io.ktor.server.response.respond +import io.ktor.server.routing.Routing +import io.ktor.server.routing.delete +import io.ktor.server.routing.post +import io.ktor.server.routing.route +import org.koin.ktor.ext.inject + +fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") { + + val authenticationService by inject() + + authenticate(CREDENTIALS_AUTH) { + post { + + val (user) = call.principal()!! + + val issued = suspendedTransaction { + authenticationService.createSession(user.id) + } + + call.respond( + HttpStatusCode.Created, + SessionResponse( + token = issued.token, + expiresAt = issued.session.expiresAt, + user = user + ) + ) + } + } + + authenticate(SESSION_AUTH) { + delete("current") { + + suspendedTransaction { + authenticationService.revokeSession(call.currentUser.sessionId) + } + + call.respond(HttpStatusCode.NoContent) + } + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt new file mode 100644 index 00000000..f9c4e343 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt @@ -0,0 +1,13 @@ +package com.mtusi.messenger.main.infrastructure.controllers.authentication.responses + +import com.mtusi.messenger.main.infrastructure.dto.User +import kotlinx.serialization.Serializable +import kotlin.time.Instant + +@Serializable +data class SessionResponse( + val token: String, + val tokenType: String = "Bearer", + val expiresAt: Instant, + val user: User, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt index 8f252d8e..e2fd839a 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt @@ -1,67 +1,112 @@ package com.mtusi.messenger.main.infrastructure.controllers.chat -import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.extensions.currentUser +import com.mtusi.messenger.main.extensions.respondError +import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest -import com.mtusi.messenger.main.infrastructure.controllers.chat.responses.ChatPageResponse +import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_MEMBERS +import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_TITLE_LENGTH import com.mtusi.messenger.main.infrastructure.services.chat.ChatService -import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult import com.mtusi.messenger.main.infrastructure.types.ApiException import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH +import com.mtusi.messenger.main.plugins.suspendedTransaction import com.mtusi.messenger.main.utils.requireNonBlankBounded import com.mtusi.messenger.main.utils.requireUuid import io.ktor.http.HttpStatusCode +import io.ktor.server.auth.authenticate import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Routing import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.server.routing.route +import org.koin.ktor.ext.inject -private const val TITLE_MAX = 100 +fun Routing.configureChatRouting() = route("/api/v1/chats") { -fun Routing.configureChatRouting( - chatService: ChatService, - userService: UserService, -) = route("/api/v1/chats") { + val chatService by inject() - post { + authenticate(SESSION_AUTH) { - val actor = call.requireCurrentUser(userService) - val body = call.receive() + post { - requireNonBlankBounded( - body.title, - min = 1, - max = TITLE_MAX, - field = "title" - ) + val actor = call.currentUser + val body = call.receive() + + requireNonBlankBounded( + body.title, + min = 1, + max = MAX_CHAT_TITLE_LENGTH, + field = "title" + ) + + if (body.memberIds.isEmpty() || body.memberIds.size > MAX_CHAT_MEMBERS) { + throw ApiException(ErrorCode.INVALID_REQUEST, "member_ids size out of range") + } + + val memberIds = body.memberIds.map { requireUuid(it, "member_ids") } + + val result = suspendedTransaction { + chatService.create( + creatorId = actor.id, + title = body.title, + memberIds = memberIds + ) + } + + when (result) { + is ChatCreationResult.DuplicateMembers -> + call.respondError(ErrorCode.INVALID_REQUEST, "member_ids must be unique") + is ChatCreationResult.CreatorNotMember -> + call.respondError(ErrorCode.INVALID_REQUEST, "creator must be in member ids") + is ChatCreationResult.UnknownMembers -> + call.respondError(ErrorCode.INVALID_REQUEST, "unknown member") + is ChatCreationResult.Success -> + call.respond(HttpStatusCode.Created, result.chat) + } + } + + get { + + val actor = call.currentUser + val (limit, cursor) = call.pageParameters() + + val result = suspendedTransaction { + chatService.findPageAccessible( + userId = actor.id, + limit = limit, + cursor = cursor + ) + } + + when (result) { + is ChatPageResult.InvalidCursor -> + call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor") + is ChatPageResult.Success -> + call.respond(HttpStatusCode.OK, result.page) + } + } + + get("{chat_id}") { + + val actor = call.currentUser + val chatId = requireUuid(call.parameters["chat_id"], "chat_id") + + val chat = suspendedTransaction { + chatService.findAccessible(actor.id, chatId) + } + + if (chat == null) { + call.respondError(ErrorCode.NOT_FOUND, "chat not found") + return@get + } + + call.respond(HttpStatusCode.OK, chat) + } - val chat = chatService.create(actor.id, body.title, body.memberIds) - call.respond(HttpStatusCode.Created, chat) } - get { - - val actor = call.requireCurrentUser(userService) - - val page = chatService.findPageAccessible( - userId = actor.id, - rawLimit = call.request.queryParameters["limit"], - rawCursor = call.request.queryParameters["cursor"], - ) - - call.respond(HttpStatusCode.OK, ChatPageResponse(page.items, page.nextCursor)) - } - - get("{chat_id}") { - - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") - - requireUuid(chatId, "chat_id") - - val chat = chatService.findAccessible(actor.id, chatId) - call.respond(HttpStatusCode.OK, chat) - } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt deleted file mode 100644 index 49a29440..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.controllers.chat.responses - -import com.mtusi.messenger.main.infrastructure.dto.Chat -import kotlinx.serialization.Serializable - -@Serializable -data class ChatPageResponse( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt index 7f9b836c..51465719 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt @@ -1,7 +1,11 @@ package com.mtusi.messenger.main.infrastructure.controllers.health +import com.mtusi.messenger.main.extensions.respondError import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.plugins.suspendedTransaction import io.ktor.http.HttpStatusCode +import io.ktor.server.application.log import io.ktor.server.response.respond import io.ktor.server.routing.Routing import io.ktor.server.routing.get @@ -13,7 +17,24 @@ fun Routing.configureHealthRouting() = route("/health") { call.respond(HttpStatusCode.OK, HealthResponse()) } + // PostgreSQL is the only dependency of the synchronous path: without it nothing can be served. get("ready") { + + val isDatabaseReachable = try { + suspendedTransaction { + exec("SELECT 1") + } + true + } catch (cause: Exception) { + call.application.log.warn("Readiness check failed: ${cause.message}") + false + } + + if (!isDatabaseReachable) { + call.respondError(ErrorCode.UNAVAILABLE, "database unavailable") + return@get + } + call.respond(HttpStatusCode.OK, HealthResponse()) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt index f956039e..d1b02be5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt @@ -1,65 +1,88 @@ package com.mtusi.messenger.main.infrastructure.controllers.message -import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.extensions.currentUser +import com.mtusi.messenger.main.extensions.respondError +import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest -import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.models.message.MAX_MESSAGE_TEXT_LENGTH import com.mtusi.messenger.main.infrastructure.services.message.MessageService -import com.mtusi.messenger.main.infrastructure.services.user.UserService -import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult +import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH +import com.mtusi.messenger.main.plugins.suspendedTransaction import com.mtusi.messenger.main.utils.requireNonBlankBounded import com.mtusi.messenger.main.utils.requireUuid import io.ktor.http.HttpStatusCode +import io.ktor.server.auth.authenticate import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Routing import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.server.routing.route +import org.koin.ktor.ext.inject -private const val TEXT_MAX = 4000 +fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages") { -fun Routing.configureMessageRouting( - messageService: MessageService, - userService: UserService, -) = route("/api/v1/chats/{chat_id}/messages") { + val messageService by inject() - post { + authenticate(SESSION_AUTH) { - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") + post { - requireUuid(chatId, "chat_id") + val actor = call.currentUser + val chatId = requireUuid(call.parameters["chat_id"], "chat_id") + val body = call.receive() - val body = call.receive() + requireNonBlankBounded( + body.text, + min = 1, + max = MAX_MESSAGE_TEXT_LENGTH, + field = "text" + ) - requireNonBlankBounded( - body.text, - min = 1, - max = TEXT_MAX, - field = "text" - ) + val result = suspendedTransaction { + messageService.send( + chatId = chatId, + senderId = actor.id, + text = body.text + ) + } + + when (result) { + is MessageCreationResult.ChatNotFound -> + call.respondError(ErrorCode.NOT_FOUND, "chat not found") + is MessageCreationResult.Success -> + call.respond(HttpStatusCode.Created, result.message) + } + } + + get { + + val actor = call.currentUser + val chatId = requireUuid(call.parameters["chat_id"], "chat_id") + val (limit, cursor) = call.pageParameters() + + val result = suspendedTransaction { + messageService.findPageByChatId( + chatId = chatId, + actorId = actor.id, + limit = limit, + cursor = cursor + ) + } + + when (result) { + is MessagePageResult.ChatNotFound -> + call.respondError(ErrorCode.NOT_FOUND, "chat not found") + is MessagePageResult.InvalidCursor -> + call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor") + is MessagePageResult.Success -> + call.respond(HttpStatusCode.OK, result.page) + } + } - val message = messageService.send(chatId, actor.id, body.text) - call.respond(HttpStatusCode.Created, message) } - get { - - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") - - requireUuid(chatId, "chat_id") - - val page = messageService.findPageByChatId( - chatId = chatId, - actorId = actor.id, - rawLimit = call.request.queryParameters["limit"], - rawCursor = call.request.queryParameters["cursor"], - ) - - call.respond(HttpStatusCode.OK, MessagePageResponse(page.items, page.nextCursor)) - } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt deleted file mode 100644 index e2bd1fc4..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.controllers.message.responses - -import com.mtusi.messenger.main.infrastructure.dto.Message -import kotlinx.serialization.Serializable - -@Serializable -data class MessagePageResponse( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt index a398b623..d49bc9a9 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt @@ -1,23 +1,35 @@ package com.mtusi.messenger.main.infrastructure.controllers.user -import com.mtusi.messenger.main.extensions.requireCurrentUser +import com.mtusi.messenger.main.extensions.currentUser +import com.mtusi.messenger.main.extensions.respondError import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.infrastructure.models.user.MAX_DISPLAY_NAME_LENGTH import com.mtusi.messenger.main.infrastructure.services.user.UserService +import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH +import com.mtusi.messenger.main.plugins.suspendedTransaction import com.mtusi.messenger.main.utils.requireNonBlankBounded import com.mtusi.messenger.main.utils.requireUsername import io.ktor.http.HttpStatusCode +import io.ktor.server.auth.authenticate import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Routing import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.server.routing.route +import org.koin.ktor.ext.inject -private const val DISPLAY_NAME_MAX = 100 +private const val PASSWORD_MIN = 12 +private const val PASSWORD_MAX = 128 -fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/users") { +fun Routing.configureUserRouting() = route("/api/v1/users") { + + val userService by inject() post { + val body = call.receive() requireUsername(body.username) @@ -25,17 +37,47 @@ fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/user requireNonBlankBounded( body.displayName, min = 1, - max = DISPLAY_NAME_MAX, - field = "displayName" + max = MAX_DISPLAY_NAME_LENGTH, + field = "display_name" ) - val user = userService.create(body.username, body.displayName) - call.respond(HttpStatusCode.Created, user) + requireNonBlankBounded( + body.password, + min = PASSWORD_MIN, + max = PASSWORD_MAX, + field = "password" + ) + + val result = suspendedTransaction { + userService.create( + username = body.username, + displayName = body.displayName, + password = body.password + ) + } + + when (result) { + is UserCreationResult.UsernameTaken -> + call.respondError(ErrorCode.CONFLICT, "username already taken") + is UserCreationResult.Success -> + call.respond(HttpStatusCode.Created, result.user) + } } - get("me") { - val user = call.requireCurrentUser(userService) - call.respond(HttpStatusCode.OK, user) + authenticate(SESSION_AUTH) { + get("me") { + + val user = suspendedTransaction { + userService.findById(call.currentUser.id) + } + + if (user == null) { + call.respondError(ErrorCode.UNAUTHORIZED, "unknown user") + return@get + } + + call.respond(HttpStatusCode.OK, user) + } } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt index d7a9dbf1..0e7bb113 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt @@ -6,4 +6,5 @@ import kotlinx.serialization.Serializable data class CreateUserRequest( val username: String, val displayName: String, + val password: String, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt index 84a57b85..846d6c82 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt @@ -1,11 +1,13 @@ package com.mtusi.messenger.main.infrastructure.dto +import com.mtusi.messenger.main.compat.serializers.SerialUUID import kotlinx.serialization.Serializable +import kotlin.time.Instant @Serializable data class Chat( - val id: String, + val id: SerialUUID, val title: String, - val memberIds: List, - val createdAt: String, + val memberIds: List, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt index 979b8d32..15e30304 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt @@ -1,12 +1,14 @@ package com.mtusi.messenger.main.infrastructure.dto +import com.mtusi.messenger.main.compat.serializers.SerialUUID import kotlinx.serialization.Serializable +import kotlin.time.Instant @Serializable data class Message( - val id: String, - val chatId: String, - val senderId: String, + val id: SerialUUID, + val chatId: SerialUUID, + val senderId: SerialUUID, val text: String, - val createdAt: String, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt new file mode 100644 index 00000000..28fa6dce --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.infrastructure.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class PageResponse( + val items: List, + val nextCursor: String?, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt index b6ed9b92..4f768822 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt @@ -1,11 +1,13 @@ package com.mtusi.messenger.main.infrastructure.dto +import com.mtusi.messenger.main.compat.serializers.SerialUUID import kotlinx.serialization.Serializable +import kotlin.time.Instant @Serializable data class User( - val id: String, + val id: SerialUUID, val username: String, val displayName: String, - val createdAt: String, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt new file mode 100644 index 00000000..480607bf --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt @@ -0,0 +1,6 @@ +package com.mtusi.messenger.main.infrastructure.dto.authentication + +data class IssuedSession( + val session: Session, + val token: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt new file mode 100644 index 00000000..4734da86 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.infrastructure.dto.authentication + +import java.util.UUID +import kotlin.time.Instant + +data class Session( + val id: UUID, + val userId: UUID, + val createdAt: Instant, + val expiresAt: Instant, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt new file mode 100644 index 00000000..2533ff71 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.dto.authentication + +import com.mtusi.messenger.main.infrastructure.dto.User + +data class UserCredentials( + val user: User, + val passwordHash: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt new file mode 100644 index 00000000..cfc1d7e3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt @@ -0,0 +1,13 @@ +package com.mtusi.messenger.main.infrastructure.models.authentication + +import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import org.jetbrains.exposed.v1.core.ReferenceOption +import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable +import org.jetbrains.exposed.v1.datetime.timestamp + +object SessionModel : UUIDTable("sessions") { + val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE) + val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key") + val createdAt = timestamp("created_at") + val expiresAt = timestamp("expires_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt new file mode 100644 index 00000000..acbcb0fb --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt @@ -0,0 +1,13 @@ +package com.mtusi.messenger.main.infrastructure.models.chat + +import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import org.jetbrains.exposed.v1.core.ReferenceOption +import org.jetbrains.exposed.v1.core.Table + +object ChatMemberModel : Table("chat_members") { + val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE) + val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE) + val position = integer("position") + + override val primaryKey = PrimaryKey(chatId, userId) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt new file mode 100644 index 00000000..984fbfd8 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt @@ -0,0 +1,12 @@ +package com.mtusi.messenger.main.infrastructure.models.chat + +import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable +import org.jetbrains.exposed.v1.datetime.timestamp + +const val MAX_CHAT_TITLE_LENGTH = 100 +const val MAX_CHAT_MEMBERS = 100 + +object ChatModel : UUIDTable("chats") { + val title = varchar("title", MAX_CHAT_TITLE_LENGTH) + val createdAt = timestamp("created_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt new file mode 100644 index 00000000..9d90d600 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt @@ -0,0 +1,16 @@ +package com.mtusi.messenger.main.infrastructure.models.message + +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import org.jetbrains.exposed.v1.core.ReferenceOption +import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable +import org.jetbrains.exposed.v1.datetime.timestamp + +const val MAX_MESSAGE_TEXT_LENGTH = 4000 + +object MessageModel : UUIDTable("messages") { + val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE) + val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE) + val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH) + val createdAt = timestamp("created_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt new file mode 100644 index 00000000..8dfa1664 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt @@ -0,0 +1,14 @@ +package com.mtusi.messenger.main.infrastructure.models.user + +import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable +import org.jetbrains.exposed.v1.datetime.timestamp + +const val MAX_USERNAME_LENGTH = 32 +const val MAX_DISPLAY_NAME_LENGTH = 100 + +object UserModel : UUIDTable("users") { + val username = varchar("username", MAX_USERNAME_LENGTH).uniqueIndex("users_username_key") + val displayName = varchar("display_name", MAX_DISPLAY_NAME_LENGTH) + val passwordHash = varchar("password_hash", 255) + val createdAt = timestamp("created_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt new file mode 100644 index 00000000..b5d76471 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.repositories + +import org.koin.core.annotation.ComponentScan +import org.koin.core.annotation.Module + +@Module +@ComponentScan +class RepositoriesModule diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt new file mode 100644 index 00000000..41f87e76 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt @@ -0,0 +1,67 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session + +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel +import com.mtusi.messenger.main.utils.nowMicros +import org.jetbrains.exposed.v1.core.ResultRow +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.greater +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.koin.core.annotation.Single +import java.util.UUID +import kotlin.time.Clock +import kotlin.time.Instant + +@Single +class ExposedSessionRepository : SessionRepository { + + override fun create( + userId: UUID, + tokenHash: String, + expiresAt: Instant + ): Session { + + val insertedRow = SessionModel.insert { + it[this.userId] = userId + it[this.tokenHash] = tokenHash + it[this.createdAt] = Clock.System.nowMicros() + it[this.expiresAt] = expiresAt + } + + return Session( + id = insertedRow[SessionModel.id].value, + userId = userId, + createdAt = insertedRow[SessionModel.createdAt], + expiresAt = expiresAt + ) + } + + override fun findActiveByTokenHash( + tokenHash: String, + now: Instant + ): Session? { + return SessionModel + .selectAll() + .where((SessionModel.tokenHash eq tokenHash) and (SessionModel.expiresAt greater now)) + .firstOrNull() + ?.toSession() + } + + override fun deleteById( + id: UUID + ): Boolean { + val deletedRows = SessionModel.deleteWhere { SessionModel.id eq id } + return deletedRows > 0 + } + + private fun ResultRow.toSession() = Session( + id = this[SessionModel.id].value, + userId = this[SessionModel.userId].value, + createdAt = this[SessionModel.createdAt], + expiresAt = this[SessionModel.expiresAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt new file mode 100644 index 00000000..d5bb2256 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt @@ -0,0 +1,25 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session + +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories.Repository +import java.util.UUID +import kotlin.time.Instant + +interface SessionRepository : Repository { + + fun create( + userId: UUID, + tokenHash: String, + expiresAt: Instant + ): Session + + fun findActiveByTokenHash( + tokenHash: String, + now: Instant + ): Session? + + fun deleteById( + id: UUID + ): Boolean + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt index de0bc6ae..956e9dfc 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt @@ -2,11 +2,32 @@ package com.mtusi.messenger.main.infrastructure.repositories.chat import com.mtusi.messenger.main.infrastructure.dto.Chat import com.mtusi.messenger.main.infrastructure.repositories.Repository +import com.mtusi.messenger.main.utils.PageKey +import java.util.UUID -interface ChatRepository : Repository { - fun findById(id: String): Chat? +interface ChatRepository : Repository { - fun insert(chat: Chat) + fun create( + title: String, + memberIds: List + ): Chat + + fun findById( + id: UUID + ): Chat? + + fun isMember( + chatId: UUID, + userId: UUID + ): Boolean + + /** + * Chats of [userId] ordered by `(created_at, id)`, strictly after [after]. + */ + fun findPageByMemberId( + userId: UUID, + after: PageKey?, + limit: Int + ): List - fun findAllAccessible(userId: String): List } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt new file mode 100644 index 00000000..2afe352d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt @@ -0,0 +1,134 @@ +package com.mtusi.messenger.main.infrastructure.repositories.chat + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.utils.PageKey +import com.mtusi.messenger.main.utils.exposed.operations.RowGreater +import com.mtusi.messenger.main.utils.nowMicros +import org.jetbrains.exposed.v1.core.QueryParameter +import org.jetbrains.exposed.v1.core.ResultRow +import org.jetbrains.exposed.v1.core.SortOrder +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.core.dao.id.EntityID +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.inList +import org.jetbrains.exposed.v1.jdbc.batchInsert +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.koin.core.annotation.Single +import java.util.UUID +import kotlin.time.Clock + +@Single +class ExposedChatRepository : ChatRepository { + + override fun create( + title: String, + memberIds: List + ): Chat { + + val insertedRow = ChatModel.insert { + it[this.title] = title + it[this.createdAt] = Clock.System.nowMicros() + } + + val chatId = insertedRow[ChatModel.id].value + + ChatMemberModel.batchInsert(memberIds.withIndex()) { (position, userId) -> + this[ChatMemberModel.chatId] = chatId + this[ChatMemberModel.userId] = userId + this[ChatMemberModel.position] = position + } + + return Chat( + id = chatId, + title = title, + memberIds = memberIds, + createdAt = insertedRow[ChatModel.createdAt] + ) + } + + override fun findById( + id: UUID + ): Chat? { + + val row = ChatModel + .selectAll() + .where(ChatModel.id eq id) + .firstOrNull() + ?: return null + + return row.toChat(findMemberIds(listOf(id))[id].orEmpty()) + } + + override fun isMember( + chatId: UUID, + userId: UUID + ): Boolean { + return ChatMemberModel + .selectAll() + .where((ChatMemberModel.chatId eq chatId) and (ChatMemberModel.userId eq userId)) + .empty() + .not() + } + + override fun findPageByMemberId( + userId: UUID, + after: PageKey?, + limit: Int + ): List { + + var condition = ChatMemberModel.userId eq userId + + if (after != null) { + condition = condition and RowGreater( + left = listOf(ChatModel.createdAt, ChatModel.id), + right = listOf( + QueryParameter(after.createdAt, ChatModel.createdAt.columnType), + QueryParameter(EntityID(after.id, ChatModel), ChatModel.id.columnType) + ) + ) + } + + val rows = ChatModel + .innerJoin(ChatMemberModel) + .selectAll() + .where(condition) + .orderBy(ChatModel.createdAt to SortOrder.ASC, ChatModel.id to SortOrder.ASC) + .limit(limit) + .toList() + + val memberIds = findMemberIds(rows.map { it[ChatModel.id].value }) + + return rows.map { + it.toChat(memberIds[it[ChatModel.id].value].orEmpty()) + } + } + + private fun findMemberIds( + chatIds: List + ): Map> { + + if (chatIds.isEmpty()) { + return emptyMap() + } + + return ChatMemberModel + .selectAll() + .where(ChatMemberModel.chatId inList chatIds) + .orderBy(ChatMemberModel.position to SortOrder.ASC) + .groupBy( + keySelector = { it[ChatMemberModel.chatId].value }, + valueTransform = { it[ChatMemberModel.userId].value } + ) + } + + private fun ResultRow.toChat(memberIds: List) = Chat( + id = this[ChatModel.id].value, + title = this[ChatModel.title], + memberIds = memberIds, + createdAt = this[ChatModel.createdAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt deleted file mode 100644 index b84d6e57..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.chat - -import com.mtusi.messenger.main.infrastructure.dto.Chat -import java.util.concurrent.ConcurrentHashMap - -class InMemoryChatRepository : ChatRepository { - private val byId = ConcurrentHashMap() - - override fun findById(id: String): Chat? = byId[id] - - override fun insert(chat: Chat) { - byId[chat.id] = chat - } - - override fun findAllAccessible(userId: String): List = - byId.values - .filter { userId in it.memberIds } - .sortedWith( - compareBy( - { it.createdAt }, - { it.id } - ) - ) -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt new file mode 100644 index 00000000..19dc19c4 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt @@ -0,0 +1,81 @@ +package com.mtusi.messenger.main.infrastructure.repositories.message + +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.models.message.MessageModel +import com.mtusi.messenger.main.utils.PageKey +import com.mtusi.messenger.main.utils.exposed.operations.RowGreater +import com.mtusi.messenger.main.utils.nowMicros +import org.jetbrains.exposed.v1.core.QueryParameter +import org.jetbrains.exposed.v1.core.ResultRow +import org.jetbrains.exposed.v1.core.SortOrder +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.core.dao.id.EntityID +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.koin.core.annotation.Single +import java.util.UUID +import kotlin.time.Clock + +@Single +class ExposedMessageRepository : MessageRepository { + + override fun create( + chatId: UUID, + senderId: UUID, + text: String + ): Message { + + val insertedRow = MessageModel.insert { + it[this.chatId] = chatId + it[this.senderId] = senderId + it[this.text] = text + it[this.createdAt] = Clock.System.nowMicros() + } + + return Message( + id = insertedRow[MessageModel.id].value, + chatId = chatId, + senderId = senderId, + text = text, + createdAt = insertedRow[MessageModel.createdAt] + ) + } + + override fun findPageByChatId( + chatId: UUID, + after: PageKey?, + limit: Int + ): List { + + var condition = MessageModel.chatId eq chatId + + if (after != null) { + condition = condition and RowGreater( + left = listOf(MessageModel.createdAt, MessageModel.id), + right = listOf( + QueryParameter(after.createdAt, MessageModel.createdAt.columnType), + QueryParameter(EntityID(after.id, MessageModel), MessageModel.id.columnType) + ) + ) + } + + return MessageModel + .selectAll() + .where(condition) + .orderBy(MessageModel.createdAt to SortOrder.ASC, MessageModel.id to SortOrder.ASC) + .limit(limit) + .map { + it.toMessage() + } + } + + private fun ResultRow.toMessage() = Message( + id = this[MessageModel.id].value, + chatId = this[MessageModel.chatId].value, + senderId = this[MessageModel.senderId].value, + text = this[MessageModel.text], + createdAt = this[MessageModel.createdAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt deleted file mode 100644 index 371c0609..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.message - -import com.mtusi.messenger.main.infrastructure.dto.Message -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.CopyOnWriteArrayList - -class InMemoryMessageRepository : MessageRepository { - private val byChat = ConcurrentHashMap>() - private val locks = ConcurrentHashMap() - - override fun append( - chatId: String, - message: Message - ) { - - val lock = locks.computeIfAbsent(chatId) { - Any() - } - - synchronized(lock) { - byChat.computeIfAbsent(chatId) { - CopyOnWriteArrayList() - }.add(message) - } - } - - override fun findRangeByChatId( - chatId: String, - offset: Int, - count: Int, - ): List { - - val messages = byChat[chatId] - ?: return emptyList() - - // Append-only: indices below an observed size never change, so no snapshot copy is needed. - val end = minOf(messages.size, offset + count) - - if (offset >= end) { - return emptyList() - } - - return List(end - offset) { messages[offset + it] } - } -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt index a0279d91..80a130d2 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt @@ -2,8 +2,21 @@ package com.mtusi.messenger.main.infrastructure.repositories.message import com.mtusi.messenger.main.infrastructure.dto.Message import com.mtusi.messenger.main.infrastructure.repositories.Repository +import com.mtusi.messenger.main.utils.PageKey +import java.util.UUID + +interface MessageRepository : Repository { + + fun create( + chatId: UUID, + senderId: UUID, + text: String + ): Message + + fun findPageByChatId( + chatId: UUID, + after: PageKey?, + limit: Int + ): List -interface MessageRepository : Repository { - fun append(chatId: String, message: Message) - fun findRangeByChatId(chatId: String, offset: Int, count: Int): List } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt new file mode 100644 index 00000000..404a333f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt @@ -0,0 +1,82 @@ +package com.mtusi.messenger.main.infrastructure.repositories.user + +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials +import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import com.mtusi.messenger.main.utils.nowMicros +import org.jetbrains.exposed.v1.core.ResultRow +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.inList +import org.jetbrains.exposed.v1.jdbc.insertIgnore +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.koin.core.annotation.Single +import java.util.UUID +import kotlin.time.Clock + +@Single +class ExposedUserRepository : UserRepository { + + override fun create( + username: String, + displayName: String, + passwordHash: String + ): User? { + + val statement = UserModel.insertIgnore { + it[this.username] = username + it[this.displayName] = displayName + it[this.passwordHash] = passwordHash + it[this.createdAt] = Clock.System.nowMicros() + } + + if (statement.insertedCount == 0) { + return null + } + + return statement.resultedValues + ?.singleOrNull() + ?.toUser() + } + + override fun findById( + id: UUID + ): User? { + return UserModel + .selectAll() + .where(UserModel.id eq id) + .firstOrNull() + ?.toUser() + } + + override fun findCredentialsByUsername( + username: String + ): UserCredentials? { + return UserModel + .selectAll() + .where(UserModel.username eq username) + .firstOrNull() + ?.let { + UserCredentials( + user = it.toUser(), + passwordHash = it[UserModel.passwordHash] + ) + } + } + + override fun countByIds( + ids: Collection + ): Long { + return UserModel + .selectAll() + .where(UserModel.id inList ids) + .count() + } + + private fun ResultRow.toUser() = User( + id = this[UserModel.id].value, + username = this[UserModel.username], + displayName = this[UserModel.displayName], + createdAt = this[UserModel.createdAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt deleted file mode 100644 index 125bae78..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.user - -import com.mtusi.messenger.main.infrastructure.dto.User -import java.util.concurrent.ConcurrentHashMap - -class InMemoryUserRepository : UserRepository { - private val byId = ConcurrentHashMap() - - override fun insert(user: User) { - byId[user.id] = user - } - - override fun findById(id: String): User? = byId[id] - - override fun findByUsername(username: String): User? { - return byId.values.find { it.username == username } - } -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt index 62da5146..0773d071 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt @@ -1,12 +1,28 @@ package com.mtusi.messenger.main.infrastructure.repositories.user import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials import com.mtusi.messenger.main.infrastructure.repositories.Repository +import java.util.UUID -interface UserRepository : Repository { - fun insert(user: User) +interface UserRepository : Repository { - fun findById(id: String): User? + fun create( + username: String, + displayName: String, + passwordHash: String + ): User? + + fun findById( + id: UUID + ): User? + + fun findCredentialsByUsername( + username: String + ): UserCredentials? + + fun countByIds( + ids: Collection + ): Long - fun findByUsername(username: String): User? } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt new file mode 100644 index 00000000..d7d75fc9 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.services + +import org.koin.core.annotation.ComponentScan +import org.koin.core.annotation.Module + +@Module +@ComponentScan +class ServicesModule diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt new file mode 100644 index 00000000..6ef710d0 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt @@ -0,0 +1,27 @@ +package com.mtusi.messenger.main.infrastructure.services.authentication + +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import java.util.UUID + +interface AuthenticationService { + + fun validateCredentials( + username: String, + password: String + ): User? + + fun createSession( + userId: UUID + ): IssuedSession + + fun findSessionByToken( + token: String + ): Session? + + fun revokeSession( + sessionId: UUID + ): Boolean + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt new file mode 100644 index 00000000..960be0ad --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt @@ -0,0 +1,91 @@ +package com.mtusi.messenger.main.infrastructure.services.authentication + +import com.mtusi.messenger.main.config.authentication.AuthenticationConfig +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository +import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository +import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import com.mtusi.messenger.main.utils.computeSha256 +import com.mtusi.messenger.main.utils.nowMicros +import org.koin.core.annotation.Single +import java.security.SecureRandom +import java.util.Base64 +import java.util.UUID +import kotlin.time.Clock +import kotlin.time.Duration.Companion.seconds + +private const val TOKEN_BYTES = 32 + +@Single +class DefaultAuthenticationService( + private val userRepository: UserRepository, + private val sessionRepository: SessionRepository, + private val hashingService: HashingService, + private val config: AuthenticationConfig +) : AuthenticationService { + + private val random = SecureRandom() + + private val dummyPasswordHash by lazy { + hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing") + } + + override fun validateCredentials( + username: String, + password: String + ): User? { + + val credentials = userRepository.findCredentialsByUsername(username) + + val isPasswordValid = hashingService.validateHash( + algorithm = HashingAlgorithm.Argon2id, + input = password, + hashed = credentials?.passwordHash ?: dummyPasswordHash + ) + + if (credentials == null || !isPasswordValid) { + return null + } + + return credentials.user + } + + override fun createSession( + userId: UUID + ): IssuedSession { + + val token = ByteArray(TOKEN_BYTES) + .also(random::nextBytes) + .let(Base64.getUrlEncoder().withoutPadding()::encodeToString) + + val session = sessionRepository.create( + userId = userId, + tokenHash = token.toByteArray().computeSha256(), + expiresAt = Clock.System.nowMicros() + config.sessionTtlSeconds.seconds + ) + + return IssuedSession( + session = session, + token = token + ) + } + + override fun findSessionByToken( + token: String + ): Session? { + return sessionRepository.findActiveByTokenHash( + tokenHash = token.toByteArray().computeSha256(), + now = Clock.System.now() + ) + } + + override fun revokeSession( + sessionId: UUID + ): Boolean { + return sessionRepository.deleteById(sessionId) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt index b21197e7..603abc9f 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt @@ -1,23 +1,27 @@ package com.mtusi.messenger.main.infrastructure.services.chat import com.mtusi.messenger.main.infrastructure.dto.Chat -import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult +import java.util.UUID interface ChatService { + fun create( - creatorId: String, + creatorId: UUID, title: String, - memberIds: List, - ): Chat + memberIds: List + ): ChatCreationResult fun findAccessible( - userId: String, - chatId: String, - ): Chat + userId: UUID, + chatId: UUID + ): Chat? fun findPageAccessible( - userId: String, - rawLimit: String?, - rawCursor: String?, - ): Page + userId: UUID, + limit: Int, + cursor: String? + ): ChatPageResult + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt index 9678d267..b38620c5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt @@ -1,92 +1,79 @@ package com.mtusi.messenger.main.infrastructure.services.chat -import com.mtusi.messenger.main.extensions.isValidUuid import com.mtusi.messenger.main.infrastructure.dto.Chat import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository -import com.mtusi.messenger.main.infrastructure.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult +import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult +import com.mtusi.messenger.main.utils.PageKey import com.mtusi.messenger.main.utils.decodeCursor -import com.mtusi.messenger.main.utils.encodeCursor -import com.mtusi.messenger.main.utils.nowIsoUtc -import com.mtusi.messenger.main.utils.parseLimit +import com.mtusi.messenger.main.utils.toPage +import org.koin.core.annotation.Single import java.util.UUID -private const val MAX_MEMBERS = 100 - +@Single class DefaultChatService( private val chatRepository: ChatRepository, - private val userRepository: UserRepository, + private val userRepository: UserRepository ) : ChatService { override fun create( - creatorId: String, + creatorId: UUID, title: String, - memberIds: List, - ): Chat { - - if (memberIds.isEmpty() || memberIds.size > MAX_MEMBERS) { - throw ApiException(ErrorCode.INVALID_REQUEST, "size out of range") - } + memberIds: List + ): ChatCreationResult { if (memberIds.toSet().size != memberIds.size) { - throw ApiException(ErrorCode.INVALID_REQUEST, "memberIds must be unique") + return ChatCreationResult.DuplicateMembers } if (creatorId !in memberIds) { - throw ApiException(ErrorCode.INVALID_REQUEST, "creator must be in members") + return ChatCreationResult.CreatorNotMember } - for (id in memberIds) { - if (!isValidUuid(id)) - throw ApiException(ErrorCode.INVALID_REQUEST, "invalid member id") - - if (userRepository.findById(id) == null) - throw ApiException(ErrorCode.INVALID_REQUEST, "unknown member") + if (userRepository.countByIds(memberIds) != memberIds.size.toLong()) { + return ChatCreationResult.UnknownMembers } - val chat = Chat( - id = UUID.randomUUID().toString(), + val chat = chatRepository.create( title = title, - memberIds = memberIds, - createdAt = nowIsoUtc(), + memberIds = memberIds ) - chatRepository.insert(chat) - return chat + return ChatCreationResult.Success(chat) } override fun findAccessible( - userId: String, - chatId: String, - ): Chat { - - val chat = chatRepository.findById(chatId) - ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - - if (userId !in chat.memberIds) { - throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - } - - return chat + userId: UUID, + chatId: UUID + ): Chat? { + return chatRepository.findById(chatId) + ?.takeIf { userId in it.memberIds } } override fun findPageAccessible( - userId: String, - rawLimit: String?, - rawCursor: String?, - ): Page { + userId: UUID, + limit: Int, + cursor: String? + ): ChatPageResult { - val limit = parseLimit(rawLimit) val scope = "chats:$userId" - val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 - val all = chatRepository.findAllAccessible(userId) - val slice = all.drop(start).take(limit) - val nextIndex = start + slice.size - val nextCursor = if (nextIndex < all.size) encodeCursor(scope, nextIndex) else null + val after = cursor?.let { + decodeCursor(it, scope) ?: return ChatPageResult.InvalidCursor + } - return Page(slice, nextCursor) + val page = chatRepository + .findPageByMemberId( + userId = userId, + after = after, + limit = limit + 1 + ) + .toPage(limit, scope) { + PageKey(it.createdAt, it.id) + } + + return ChatPageResult.Success(page) } + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt new file mode 100644 index 00000000..61c35511 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt @@ -0,0 +1,17 @@ +package com.mtusi.messenger.main.infrastructure.services.chat.results + +import com.mtusi.messenger.main.infrastructure.dto.Chat + +sealed class ChatCreationResult { + + sealed class Error : ChatCreationResult() + + data object DuplicateMembers : Error() + data object CreatorNotMember : Error() + data object UnknownMembers : Error() + + data class Success( + val chat: Chat + ) : ChatCreationResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt new file mode 100644 index 00000000..d347bad6 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt @@ -0,0 +1,16 @@ +package com.mtusi.messenger.main.infrastructure.services.chat.results + +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.PageResponse + +sealed class ChatPageResult { + + sealed class Error : ChatPageResult() + + data object InvalidCursor : Error() + + data class Success( + val page: PageResponse + ) : ChatPageResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt new file mode 100644 index 00000000..d18110ac --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt @@ -0,0 +1,123 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing + +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import org.bouncycastle.crypto.generators.Argon2BytesGenerator +import org.bouncycastle.crypto.params.Argon2Parameters +import org.koin.core.annotation.Single +import java.security.MessageDigest +import java.security.SecureRandom +import java.util.Base64 + +// TODO: Move to config later +private const val ARGON2_MEMORY_KIB = 19 * 1024 +private const val ARGON2_ITERATIONS = 2 +private const val ARGON2_PARALLELISM = 1 +private const val ARGON2_SALT_LENGTH = 16 +private const val ARGON2_HASH_LENGTH = 32 + +@Single +class DefaultHashingService : HashingService { + + private val random = SecureRandom() + private val encoder = Base64.getEncoder().withoutPadding() + private val decoder = Base64.getDecoder() + + override fun computeHash( + algorithm: HashingAlgorithm, + input: String + ): String { + return when (algorithm) { + HashingAlgorithm.Argon2id -> computeHashArgon2id(input) + } + } + + private fun computeHashArgon2id(input: String): String { + + val salt = ByteArray(ARGON2_SALT_LENGTH).also(random::nextBytes) + + val hash = argon2id( + input = input, + salt = salt, + memoryKib = ARGON2_MEMORY_KIB, + iterations = ARGON2_ITERATIONS, + parallelism = ARGON2_PARALLELISM, + length = ARGON2_HASH_LENGTH + ) + + return "\$argon2id\$v=19\$m=$ARGON2_MEMORY_KIB,t=$ARGON2_ITERATIONS,p=$ARGON2_PARALLELISM" + + "\$${encoder.encodeToString(salt)}\$${encoder.encodeToString(hash)}" + } + + override fun validateHash( + algorithm: HashingAlgorithm, + input: String, + hashed: String + ): Boolean { + return when (algorithm) { + HashingAlgorithm.Argon2id -> validateHashArgon2id(input, hashed) + } + } + + private fun validateHashArgon2id( + input: String, + hashed: String + ): Boolean { + return try { + + val parts = hashed.split('$') + if (parts.size != 6 || parts[1] != "argon2id" || parts[2] != "v=19") { + return false + } + + val parameters = parts[3] + .split(',') + .associate { + val (key, value) = it.split('=') + key to value.toInt() + } + + val salt = decoder.decode(parts[4]) + val expected = decoder.decode(parts[5]) + + val actual = argon2id( + input = input, + salt = salt, + memoryKib = parameters.getValue("m"), + iterations = parameters.getValue("t"), + parallelism = parameters.getValue("p"), + length = expected.size + ) + + MessageDigest.isEqual(expected, actual) + } catch (_: Exception) { + false + } + } + + private fun argon2id( + input: String, + salt: ByteArray, + memoryKib: Int, + iterations: Int, + parallelism: Int, + length: Int + ): ByteArray { + + val parameters = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id) + .withVersion(Argon2Parameters.ARGON2_VERSION_13) + .withMemoryAsKB(memoryKib) + .withIterations(iterations) + .withParallelism(parallelism) + .withSalt(salt) + .build() + + val generator = Argon2BytesGenerator().apply { + init(parameters) + } + + return ByteArray(length).also { + generator.generateBytes(input.toByteArray(Charsets.UTF_8), it) + } + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt new file mode 100644 index 00000000..0de59beb --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt @@ -0,0 +1,18 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing + +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm + +interface HashingService { + + fun computeHash( + algorithm: HashingAlgorithm, + input: String + ): String + + fun validateHash( + algorithm: HashingAlgorithm, + input: String, + hashed: String + ): Boolean + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt new file mode 100644 index 00000000..8f39402b --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt @@ -0,0 +1,5 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing.types + +sealed class HashingAlgorithm { + data object Argon2id : HashingAlgorithm() +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt index 52afe12c..800af6fe 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt @@ -1,74 +1,68 @@ package com.mtusi.messenger.main.infrastructure.services.message -import com.mtusi.messenger.main.infrastructure.dto.Message import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository import com.mtusi.messenger.main.infrastructure.repositories.message.MessageRepository -import com.mtusi.messenger.main.infrastructure.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult +import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult +import com.mtusi.messenger.main.utils.PageKey import com.mtusi.messenger.main.utils.decodeCursor -import com.mtusi.messenger.main.utils.encodeCursor -import com.mtusi.messenger.main.utils.nowIsoUtc -import com.mtusi.messenger.main.utils.parseLimit +import com.mtusi.messenger.main.utils.toPage +import org.koin.core.annotation.Single import java.util.UUID +@Single class DefaultMessageService( private val chatRepository: ChatRepository, - private val messageRepository: MessageRepository, + private val messageRepository: MessageRepository ) : MessageService { override fun send( - chatId: String, - senderId: String, - text: String, - ): Message { + chatId: UUID, + senderId: UUID, + text: String + ): MessageCreationResult { - requireChatMembership(chatId, senderId) + if (!chatRepository.isMember(chatId, senderId)) { + return MessageCreationResult.ChatNotFound + } - val message = Message( - id = UUID.randomUUID().toString(), + val message = messageRepository.create( chatId = chatId, senderId = senderId, - text = text, - createdAt = nowIsoUtc(), + text = text ) - messageRepository.append(chatId, message) - - return message + return MessageCreationResult.Success(message) } override fun findPageByChatId( - chatId: String, - actorId: String, - rawLimit: String?, - rawCursor: String?, - ): Page { + chatId: UUID, + actorId: UUID, + limit: Int, + cursor: String? + ): MessagePageResult { - requireChatMembership(chatId, actorId) - - val limit = parseLimit(rawLimit) - val scope = "messages:$chatId" - val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 - - val window = messageRepository.findRangeByChatId( - chatId = chatId, - offset = start, - count = limit + 1, - ) - - val items = window.take(limit) - val nextCursor = if (window.size > limit) encodeCursor(scope, start + limit) else null - - return Page(items, nextCursor) - } - - private fun requireChatMembership(chatId: String, userId: String) { - val chat = chatRepository.findById(chatId) - ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - - if (userId !in chat.memberIds) { - throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + if (!chatRepository.isMember(chatId, actorId)) { + return MessagePageResult.ChatNotFound } + + val scope = "messages:$chatId" + + val after = cursor?.let { + decodeCursor(it, scope) ?: return MessagePageResult.InvalidCursor + } + + val page = messageRepository + .findPageByChatId( + chatId = chatId, + after = after, + limit = limit + 1 + ) + .toPage(limit, scope) { + PageKey(it.createdAt, it.id) + } + + return MessagePageResult.Success(page) } + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt index 24f54eb2..075c35d7 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt @@ -1,19 +1,22 @@ package com.mtusi.messenger.main.infrastructure.services.message -import com.mtusi.messenger.main.infrastructure.dto.Message -import com.mtusi.messenger.main.utils.Page +import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult +import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult +import java.util.UUID interface MessageService { + fun send( - chatId: String, - senderId: String, - text: String, - ): Message + chatId: UUID, + senderId: UUID, + text: String + ): MessageCreationResult fun findPageByChatId( - chatId: String, - actorId: String, - rawLimit: String?, - rawCursor: String?, - ): Page + chatId: UUID, + actorId: UUID, + limit: Int, + cursor: String? + ): MessagePageResult + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt new file mode 100644 index 00000000..d5ac9756 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt @@ -0,0 +1,15 @@ +package com.mtusi.messenger.main.infrastructure.services.message.results + +import com.mtusi.messenger.main.infrastructure.dto.Message + +sealed class MessageCreationResult { + + sealed class Error : MessageCreationResult() + + data object ChatNotFound : Error() + + data class Success( + val message: Message + ) : MessageCreationResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt new file mode 100644 index 00000000..254b1d52 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt @@ -0,0 +1,17 @@ +package com.mtusi.messenger.main.infrastructure.services.message.results + +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.dto.PageResponse + +sealed class MessagePageResult { + + sealed class Error : MessagePageResult() + + data object ChatNotFound : Error() + data object InvalidCursor : Error() + + data class Success( + val page: PageResponse + ) : MessagePageResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt index 7dd8f22b..618ca129 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt @@ -2,32 +2,42 @@ package com.mtusi.messenger.main.infrastructure.services.user import com.mtusi.messenger.main.infrastructure.dto.User import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository -import com.mtusi.messenger.main.infrastructure.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.nowIsoUtc +import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult +import org.koin.core.annotation.Single import java.util.UUID +@Single class DefaultUserService( private val userRepository: UserRepository, + private val hashingService: HashingService ) : UserService { - override fun create(username: String, displayName: String): User { + override fun create( + username: String, + displayName: String, + password: String + ): UserCreationResult { - if (userRepository.findByUsername(username) != null) { - throw ApiException(ErrorCode.CONFLICT, "username already taken") - } - - val user = User( - id = UUID.randomUUID().toString(), - username = username, - displayName = displayName, - createdAt = nowIsoUtc(), + val passwordHash = hashingService.computeHash( + algorithm = HashingAlgorithm.Argon2id, + input = password ) - userRepository.insert(user) + val user = userRepository.create( + username = username, + displayName = displayName, + passwordHash = passwordHash + ) ?: return UserCreationResult.UsernameTaken - return user + return UserCreationResult.Success(user) + } + + override fun findById( + id: UUID + ): User? { + return userRepository.findById(id) } - override fun findById(id: String): User? = userRepository.findById(id) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt index ad976c1c..da9528ed 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt @@ -1,8 +1,19 @@ package com.mtusi.messenger.main.infrastructure.services.user import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult +import java.util.UUID interface UserService { - fun create(username: String, displayName: String): User - fun findById(id: String): User? + + fun create( + username: String, + displayName: String, + password: String + ): UserCreationResult + + fun findById( + id: UUID + ): User? + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt new file mode 100644 index 00000000..ae51bf5d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt @@ -0,0 +1,15 @@ +package com.mtusi.messenger.main.infrastructure.services.user.results + +import com.mtusi.messenger.main.infrastructure.dto.User + +sealed class UserCreationResult { + + sealed class Error : UserCreationResult() + + data object UsernameTaken : Error() + + data class Success( + val user: User + ) : UserCreationResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt new file mode 100644 index 00000000..d8f23b56 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt @@ -0,0 +1,6 @@ +package com.mtusi.messenger.main.infrastructure.types + +object AuthChallenge { + const val BASIC = "Basic realm=\"messenger\", charset=\"UTF-8\"" + const val BEARER = "Bearer realm=\"messenger\"" +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt new file mode 100644 index 00000000..74b55b5f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -0,0 +1,70 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.config.database.DatabaseConfig +import com.zaxxer.hikari.HikariConfig +import com.zaxxer.hikari.HikariDataSource +import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationStopped +import kotlinx.coroutines.Dispatchers +import org.flywaydb.core.Flyway +import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig +import org.jetbrains.exposed.v1.jdbc.Database +import org.jetbrains.exposed.v1.jdbc.JdbcTransaction +import org.jetbrains.exposed.v1.jdbc.transactions.experimental.newSuspendedTransaction +import org.koin.ktor.ext.inject +import java.io.File +import javax.sql.DataSource + +fun Application.configureDatabase() { + + val config by inject() + + val dataSource = HikariDataSource( + HikariConfig().apply { + poolName = "messenger" + jdbcUrl = config.jdbcConnectionUrl + username = config.username + password = config.resolvePassword() + maximumPoolSize = config.maxPoolSize + connectionTimeout = config.connectionTimeoutMs + } + ) + + Database.connect( + datasource = dataSource, + databaseConfig = ExposedDatabaseConfig { + defaultMaxAttempts = 1 + } + ) + applyDatabaseMigrations(dataSource) + + monitor.subscribe(ApplicationStopped) { + dataSource.close() + } + +} + +private fun DatabaseConfig.resolvePassword(): String { + return password + ?: passwordFile?.let { File(it).readText().trim() } + ?: "" +} + +fun applyDatabaseMigrations( + dataSource: DataSource +) { + + val flyway = Flyway.configure() + .dataSource(dataSource) + .locations("classpath:migrations") + .load() + + flyway.migrate() + flyway.validate() + +} + +suspend fun suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction( + context = Dispatchers.IO, + statement = statement +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt deleted file mode 100644 index 46f4d02e..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.mtusi.messenger.main.plugins - -import com.mtusi.messenger.main.infrastructure.services.chat.ChatService -import com.mtusi.messenger.main.infrastructure.services.message.MessageService -import com.mtusi.messenger.main.infrastructure.services.user.UserService - -data class Dependencies( - val userService: UserService, - val chatService: ChatService, - val messageService: MessageService, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt new file mode 100644 index 00000000..6702609f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt @@ -0,0 +1,27 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.config.ConfigModule +import com.mtusi.messenger.main.infrastructure.repositories.RepositoriesModule +import com.mtusi.messenger.main.infrastructure.services.ServicesModule +import io.ktor.server.application.Application +import io.ktor.server.application.install +import org.koin.dsl.module +import org.koin.ksp.generated.module +import org.koin.ktor.plugin.Koin + +fun Application.configureKoin() { + + val applicationModule = module { + single { this@configureKoin } + } + + install(Koin) { + modules( + applicationModule, + ConfigModule().module, + RepositoriesModule().module, + ServicesModule().module + ) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt index 8ce80a6d..5329f729 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt @@ -1,5 +1,6 @@ package com.mtusi.messenger.main.plugins +import com.mtusi.messenger.main.infrastructure.controllers.authentication.configureAuthenticationRouting import com.mtusi.messenger.main.infrastructure.controllers.chat.configureChatRouting import com.mtusi.messenger.main.infrastructure.controllers.health.configureHealthRouting import com.mtusi.messenger.main.infrastructure.controllers.message.configureMessageRouting @@ -7,10 +8,11 @@ import com.mtusi.messenger.main.infrastructure.controllers.user.configureUserRou import io.ktor.server.application.Application import io.ktor.server.routing.routing -fun Application.configureRouting(dependencies: Dependencies) = routing { +fun Application.configureRouting() = routing { configureSwaggerRouting() configureHealthRouting() - configureUserRouting(dependencies.userService) - configureChatRouting(dependencies.chatService, dependencies.userService) - configureMessageRouting(dependencies.messageService, dependencies.userService) + configureUserRouting() + configureAuthenticationRouting() + configureChatRouting() + configureMessageRouting() } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt index b777ee92..41d58395 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt @@ -7,11 +7,16 @@ import io.ktor.http.HttpStatusCode import io.ktor.serialization.JsonConvertException import io.ktor.server.application.Application import io.ktor.server.application.install +import io.ktor.server.application.log import io.ktor.server.plugins.BadRequestException import io.ktor.server.plugins.NotFoundException import io.ktor.server.plugins.UnsupportedMediaTypeException import io.ktor.server.plugins.statuspages.StatusPages import kotlinx.serialization.SerializationException +import java.sql.SQLException +import java.sql.SQLTransientConnectionException + +private const val CONNECTION_ERROR_SQL_STATE_CLASS = "08" fun Application.configureStatusPages() = install(StatusPages) { exception { call, cause -> @@ -32,7 +37,17 @@ fun Application.configureStatusPages() = install(StatusPages) { exception { call, _ -> call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type") } - exception { call, _ -> + exception { call, cause -> + if (cause.isConnectionFailure()) { + call.application.log.warn("Database unavailable: ${cause.message}") + call.respondError(ErrorCode.UNAVAILABLE, "service temporarily unavailable") + } else { + call.application.log.error("Database error", cause) + call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") + } + } + exception { call, cause -> + call.application.log.error("Unhandled error", cause) call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") } status(HttpStatusCode.NotFound) { call, _ -> @@ -42,3 +57,10 @@ fun Application.configureStatusPages() = install(StatusPages) { call.respondError(ErrorCode.NOT_FOUND, "not found") } } + +private fun SQLException.isConnectionFailure(): Boolean { + return generateSequence(this) { it.cause }.any { + it is SQLTransientConnectionException || + (it is SQLException && it.sqlState?.startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) == true) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt new file mode 100644 index 00000000..e0d7b8e3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt @@ -0,0 +1,48 @@ +package com.mtusi.messenger.main.plugins.authentication + +import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService +import com.mtusi.messenger.main.plugins.authentication.providers.basicCredentials +import com.mtusi.messenger.main.plugins.authentication.providers.bearerSession +import com.mtusi.messenger.main.plugins.suspendedTransaction +import io.ktor.server.application.Application +import io.ktor.server.auth.authentication +import org.koin.ktor.ext.inject + +const val CREDENTIALS_AUTH = "credentials" +const val SESSION_AUTH = "session" + +fun Application.configureAuthentication() { + + val authenticationService by inject() + + authentication { + + basicCredentials(CREDENTIALS_AUTH) { + validate { credential -> + val user = suspendedTransaction { + authenticationService.validateCredentials( + username = credential.name, + password = credential.password + ) + } ?: return@validate null + + return@validate CredentialsPrincipal(user) + } + } + + bearerSession(SESSION_AUTH) { + authenticate { token -> + val session = suspendedTransaction { + authenticationService.findSessionByToken(token) + } ?: return@authenticate null + + return@authenticate UserPrincipal( + id = session.userId, + sessionId = session.id + ) + } + } + + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt new file mode 100644 index 00000000..9a5684a3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt @@ -0,0 +1,7 @@ +package com.mtusi.messenger.main.plugins.authentication + +import com.mtusi.messenger.main.infrastructure.dto.User + +data class CredentialsPrincipal( + val user: User +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt new file mode 100644 index 00000000..b8870e9c --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.plugins.authentication + +import java.util.UUID + +data class UserPrincipal( + val id: UUID, + val sessionId: UUID +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt new file mode 100644 index 00000000..f8ab4179 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt @@ -0,0 +1,66 @@ +package com.mtusi.messenger.main.plugins.authentication.providers + +import com.mtusi.messenger.main.extensions.respondError +import com.mtusi.messenger.main.infrastructure.types.AuthChallenge +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import io.ktor.server.application.ApplicationCall +import io.ktor.server.auth.AuthenticationConfig +import io.ktor.server.auth.AuthenticationContext +import io.ktor.server.auth.AuthenticationFailedCause +import io.ktor.server.auth.AuthenticationProvider +import io.ktor.server.auth.UserPasswordCredential +import io.ktor.server.auth.basicAuthenticationCredentials +import io.ktor.server.plugins.BadRequestException + +private const val CHALLENGE_KEY = "BasicCredentials" + +class BasicCredentialsProvider(config: Config) : AuthenticationProvider(config) { + + private val validate = config.validate + + override suspend fun onAuthenticate(context: AuthenticationContext) { + + val credential = try { + context.call.request.basicAuthenticationCredentials(Charsets.UTF_8) + } catch (_: BadRequestException) { + null + } + + val principal = credential?.let { validate(context.call, it) } + + if (principal == null) { + + val cause = if (credential == null) { + AuthenticationFailedCause.NoCredentials + } else { + AuthenticationFailedCause.InvalidCredentials + } + + context.challenge(CHALLENGE_KEY, cause) { challenge, call -> + call.respondError(ErrorCode.UNAUTHORIZED, "invalid credentials", AuthChallenge.BASIC) + challenge.complete() + } + return + } + + context.principal(principal) + } + + class Config(name: String?) : AuthenticationProvider.Config(name) { + + internal var validate: suspend ApplicationCall.(UserPasswordCredential) -> Any? = { null } + + fun validate(body: suspend ApplicationCall.(UserPasswordCredential) -> Any?) { + validate = body + } + + } + +} + +fun AuthenticationConfig.basicCredentials( + name: String, + configure: BasicCredentialsProvider.Config.() -> Unit +) { + register(BasicCredentialsProvider(BasicCredentialsProvider.Config(name).apply(configure))) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt new file mode 100644 index 00000000..9d3ad728 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt @@ -0,0 +1,71 @@ +package com.mtusi.messenger.main.plugins.authentication.providers + +import com.mtusi.messenger.main.extensions.respondError +import com.mtusi.messenger.main.infrastructure.types.AuthChallenge +import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import io.ktor.http.auth.HttpAuthHeader +import io.ktor.server.application.ApplicationCall +import io.ktor.server.auth.AuthenticationConfig +import io.ktor.server.auth.AuthenticationContext +import io.ktor.server.auth.AuthenticationFailedCause +import io.ktor.server.auth.AuthenticationProvider +import io.ktor.server.auth.parseAuthorizationHeader +import io.ktor.server.plugins.BadRequestException + +private const val CHALLENGE_KEY = "BearerSession" +private const val BEARER_SCHEME = "Bearer" + +class BearerSessionProvider(config: Config) : AuthenticationProvider(config) { + + private val authenticate = config.authenticate + + override suspend fun onAuthenticate(context: AuthenticationContext) { + + val header = try { + context.call.request.parseAuthorizationHeader() + } catch (_: BadRequestException) { + null + } + + val token = (header as? HttpAuthHeader.Single) + ?.takeIf { it.authScheme.equals(BEARER_SCHEME, ignoreCase = true) } + ?.blob + + val principal = token?.let { authenticate(context.call, it) } + + if (principal == null) { + + val cause = if (token == null) { + AuthenticationFailedCause.NoCredentials + } else { + AuthenticationFailedCause.InvalidCredentials + } + + context.challenge(CHALLENGE_KEY, cause) { challenge, call -> + call.respondError(ErrorCode.UNAUTHORIZED, "authentication required", AuthChallenge.BEARER) + challenge.complete() + } + return + } + + context.principal(principal) + } + + class Config(name: String?) : AuthenticationProvider.Config(name) { + + internal var authenticate: suspend ApplicationCall.(String) -> Any? = { null } + + fun authenticate(body: suspend ApplicationCall.(String) -> Any?) { + authenticate = body + } + + } + +} + +fun AuthenticationConfig.bearerSession( + name: String, + configure: BearerSessionProvider.Config.() -> Unit +) { + register(BearerSessionProvider(BearerSessionProvider.Config(name).apply(configure))) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt new file mode 100644 index 00000000..824b9059 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt @@ -0,0 +1,10 @@ +package com.mtusi.messenger.main.utils + +import java.security.MessageDigest + +@OptIn(ExperimentalStdlibApi::class) +fun ByteArray.computeSha256(): String { + return MessageDigest.getInstance("SHA-256") + .digest(this) + .toHexString() +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt deleted file mode 100644 index e4e8ce6e..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.mtusi.messenger.main.utils - -data class Page( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt index 415bca63..cd84ad28 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt @@ -1,40 +1,64 @@ package com.mtusi.messenger.main.utils -import com.mtusi.messenger.main.infrastructure.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import java.util.Base64 +import com.mtusi.messenger.main.compat.serializers.SerialUUID +import com.mtusi.messenger.main.infrastructure.dto.PageResponse import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import java.util.Base64 +import java.util.UUID +import kotlin.time.Instant -private const val DEFAULT_LIMIT = 50 -private const val MAX_LIMIT = 100 +private val json = Json { ignoreUnknownKeys = false } -private val json = Json { ignoreUnknownKeys = true } +/** + * Position in a `(created_at, id)` ordered list: the next page starts strictly after it. + */ +data class PageKey( + val createdAt: Instant, + val id: UUID, +) @Serializable -private data class Cursor(val scope: String, val index: Int) +private data class Cursor( + val scope: String, + val createdAt: Instant, + val id: SerialUUID, +) -fun encodeCursor(scope: String, index: Int): String { - val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, index)) +fun encodeCursor(scope: String, key: PageKey): String { + val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, key.createdAt, key.id)) return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.toByteArray(Charsets.UTF_8)) } -fun decodeCursor(raw: String, expectedScope: String): Int { - val decoded = try { +/** + * @return page key, or null if the cursor is malformed or was issued for another resource + */ +fun decodeCursor(raw: String, expectedScope: String): PageKey? { + val cursor = try { val bytes = Base64.getUrlDecoder().decode(raw) json.decodeFromString(Cursor.serializer(), String(bytes, Charsets.UTF_8)) - } catch (_: Throwable) { - throw ApiException(ErrorCode.INVALID_REQUEST, "invalid cursor") + } catch (_: Exception) { + return null } - if (decoded.scope != expectedScope || decoded.index < 0) { - throw ApiException(ErrorCode.INVALID_REQUEST, "cursor does not belong to this resource") + + if (cursor.scope != expectedScope) { + return null } - return decoded.index + + return PageKey(cursor.createdAt, cursor.id) } -fun parseLimit(raw: String?): Int { - if (raw == null) return DEFAULT_LIMIT - val v = raw.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") - if (v !in 1..MAX_LIMIT) throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range") - return v +/** + * Builds a page from `limit + 1` rows fetched after the cursor: the extra row only signals that more data exists. + */ +fun List.toPage( + limit: Int, + scope: String, + key: (T) -> PageKey, +): PageResponse { + + val items = take(limit) + val nextCursor = if (size > limit) encodeCursor(scope, key(items.last())) else null + + return PageResponse(items, nextCursor) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt index e8f7d1e4..7c8c8d43 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt @@ -1,11 +1,18 @@ package com.mtusi.messenger.main.utils -import java.time.Instant -import java.time.ZoneOffset -import java.time.format.DateTimeFormatter +import kotlin.time.Clock +import kotlin.time.Instant -private val RFC3339: DateTimeFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .withZone(ZoneOffset.UTC) +private const val NANOS_PER_MICRO = 1_000 -fun nowIsoUtc(): String = RFC3339.format(Instant.now()) +/** + * Current time truncated to microseconds: PostgreSQL timestamptz keeps exactly this precision, + * so the value returned to the client equals the one read back from the database. + */ +fun Clock.nowMicros(): Instant { + val now = now() + return Instant.fromEpochSeconds( + epochSeconds = now.epochSeconds, + nanosecondAdjustment = now.nanosecondsOfSecond / NANOS_PER_MICRO * NANOS_PER_MICRO + ) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt index 19ab2b57..395e8fb6 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt @@ -1,11 +1,15 @@ package com.mtusi.messenger.main.utils -import com.mtusi.messenger.main.extensions.isValidUuid import com.mtusi.messenger.main.infrastructure.types.ApiException import com.mtusi.messenger.main.infrastructure.types.ErrorCode +import java.util.UUID private val USERNAME = Regex("^[a-z0-9_]{3,32}$") +private val UUID_REGEX = Regex( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" +) + fun codePoints(value: String): Int = value.codePointCount(0, value.length) fun requireUsername(value: String) { @@ -24,8 +28,9 @@ fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) { } } -fun requireUuid(value: String, field: String) { - if (!isValidUuid(value)) { +fun requireUuid(value: String?, field: String): UUID { + if (value == null || !UUID_REGEX.matches(value)) { throw ApiException(ErrorCode.INVALID_REQUEST, "invalid $field") } + return UUID.fromString(value) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt new file mode 100644 index 00000000..190d93fa --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt @@ -0,0 +1,32 @@ +package com.mtusi.messenger.main.utils.exposed.operations + +import org.jetbrains.exposed.v1.core.Expression +import org.jetbrains.exposed.v1.core.Op +import org.jetbrains.exposed.v1.core.QueryBuilder + +class RowGreater( + private val left: List>, + private val right: List> +) : Op() { + + init { + require(left.size == right.size) { "Rows must have the same arity" } + } + + override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { + appendRow(left) + append(" > ") + appendRow(right) + } + + private fun QueryBuilder.appendRow(expressions: List>) { + append("(") + expressions.forEachIndexed { index, expression -> + if (index > 0) { + append(", ") + } + append(expression) + } + append(")") + } +} diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf index ce1c5691..dc393054 100644 --- a/src/main/resources/application.conf +++ b/src/main/resources/application.conf @@ -12,3 +12,25 @@ ktor { shutdownTimeout = 10000 } } + +database { + host = "localhost" + host = ${?DB_HOST} + port = 5432 + port = ${?DB_PORT} + name = "messenger" + name = ${?DB_NAME} + username = "messenger" + username = ${?DB_USER} + password = ${?DB_PASSWORD} + passwordFile = ${?DB_PASSWORD_FILE} + maxPoolSize = 10 + maxPoolSize = ${?DB_MAX_POOL_SIZE} + connectionTimeoutMs = 2000 +} + +authentication { + realm = "messenger" + sessionTtlSeconds = 3600 + sessionTtlSeconds = ${?SESSION_TTL_SECONDS} +} diff --git a/src/main/resources/migrations/V1__init.sql b/src/main/resources/migrations/V1__init.sql new file mode 100644 index 00000000..b580eefd --- /dev/null +++ b/src/main/resources/migrations/V1__init.sql @@ -0,0 +1,50 @@ +-- Users, chats, membership, messages and sessions. PostgreSQL is the source of truth. +-- Timestamps are timestamptz: an absolute instant, independent of server/JVM time zone. + +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL, + display_name varchar(100) NOT NULL, + password_hash varchar(255) NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$') +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title varchar(100) NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + position integer NOT NULL, + PRIMARY KEY (chat_id, user_id) +); + +-- "Chats of a user": the PK leads with chat_id, so the reverse lookup needs its own index. +CREATE INDEX chat_members_user_id_idx ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + text varchar(4000) NOT NULL, + created_at timestamptz NOT NULL +); + +-- Keyset pagination of a chat history: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id. +CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + id uuid PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + token_hash varchar(64) NOT NULL, + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + CONSTRAINT sessions_token_hash_key UNIQUE (token_hash) +); + +CREATE INDEX sessions_user_id_idx ON sessions (user_id); diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt new file mode 100644 index 00000000..67734ad9 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt @@ -0,0 +1,151 @@ +package com.mtusi.messenger.main.infrastructure.controllers.authentication + +import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse +import com.mtusi.messenger.main.support.TEST_PASSWORD +import com.mtusi.messenger.main.support.auth +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import io.ktor.client.call.body +import io.ktor.client.request.basicAuth +import io.ktor.client.request.bearerAuth +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import kotlinx.coroutines.delay +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +private const val BASIC_CHALLENGE = "Basic realm=\"messenger\", charset=\"UTF-8\"" + +class AuthenticationControllerTest { + + @Test + fun `valid Basic credentials open a session`() = runApp { client -> + val user = client.createUser("alice") + + val response = client.post("/api/v1/auth/sessions") { + basicAuth(user.username, TEST_PASSWORD) + } + + assertEquals(HttpStatusCode.Created, response.status) + + val session = response.body() + assertEquals("Bearer", session.tokenType) + assertEquals(user, session.user) + assertTrue(session.token.length >= 43, "token must carry at least 256 bits") + assertTrue(session.expiresAt > Clock.System.now() + 59.minutes) + } + + @Test + fun `each login issues a different token`() = runApp { client -> + val user = client.createUser("alice") + + val first = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) } + val second = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) } + + assertNotEquals(first.body().token, second.body().token) + } + + @Test + fun `password containing a colon and non-ASCII characters works`() = runApp { client -> + val password = "пароль:с-двоеточием" + val user = client.createUser("colon", password = password) + + val response = client.post("/api/v1/auth/sessions") { + basicAuth(user.username, password) + } + + assertEquals(HttpStatusCode.Created, response.status) + } + + @Test + fun `wrong password and unknown user get the same 401`() = runApp { client -> + val user = client.createUser("alice") + + val wrongPassword = client.post("/api/v1/auth/sessions") { + basicAuth(user.username, "wrong-password-123") + } + val unknownUser = client.post("/api/v1/auth/sessions") { + basicAuth("nobody_${user.username}".take(32), TEST_PASSWORD) + } + + for (response in listOf(wrongPassword, unknownUser)) { + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate]) + assertEquals("unauthorized", response.body().error.code) + } + } + + @Test + fun `missing or malformed Basic header returns 401`() = runApp { client -> + val missing = client.post("/api/v1/auth/sessions") + val malformed = client.post("/api/v1/auth/sessions") { + header(HttpHeaders.Authorization, "Basic !!!not-base64") + } + + for (response in listOf(missing, malformed)) { + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate]) + } + } + + @Test + fun `Bearer token cannot open a session`() = runApp { client -> + val alice = client.register("alice") + + val response = client.post("/api/v1/auth/sessions") { + auth(alice) + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + } + + @Test + fun `logout revokes only the current token`() = runApp { client -> + val alice = client.register("alice") + val secondSession = client.post("/api/v1/auth/sessions") { + basicAuth(alice.user.username, alice.password) + }.body() + + val logout = client.delete("/api/v1/auth/sessions/current") { auth(alice) } + assertEquals(HttpStatusCode.NoContent, logout.status) + + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + assertEquals(HttpStatusCode.Unauthorized, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + + val other = client.get("/api/v1/users/me") { bearerAuth(secondSession.token) } + assertEquals(HttpStatusCode.OK, other.status) + } + + @Test + fun `unknown token returns 401`() = runApp { client -> + val response = client.get("/api/v1/users/me") { + bearerAuth("this-token-was-never-issued-by-the-server-at-all") + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + } + + @Test + fun `session expires after SESSION_TTL_SECONDS`() = runApp(sessionTtlSeconds = 2) { client -> + val alice = client.register("alice") + + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + + delay(2.5.seconds) + + val expired = client.get("/api/v1/users/me") { auth(alice) } + assertEquals(HttpStatusCode.Unauthorized, expired.status) + assertEquals("Bearer realm=\"messenger\"", expired.headers[HttpHeaders.WWWAuthenticate]) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt index 5b310c46..ea0b63e4 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt @@ -1,27 +1,64 @@ package com.mtusi.messenger.main.infrastructure.controllers.chat import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.support.TestUser +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp +import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get -import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull class ChatControllerTest { + private suspend fun HttpClient.postChat(actor: TestUser, title: String, memberIds: List): HttpResponse = + post("/api/v1/chats") { + auth(actor) + contentType(ContentType.Application.Json) + setBody(CreateChatRequest(title = title, memberIds = memberIds)) + } + + @Test + fun `member can read own chat and members keep their order`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + val created = client.createChat(alice, title = "notes", memberIds = listOf(bob.id, alice.id)) + + val response = client.get("/api/v1/chats/${created.id}") { + auth(bob) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(created, response.body()) + assertEquals(listOf(bob.id, alice.id), created.memberIds) + } + @Test fun `foreign chat returns 404 for non-member`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val eve = client.register("eve") val chat = client.createChat(alice, title = "secret", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}") { - header("X-User-Id", bob.id) + auth(eve) } assertEquals(HttpStatusCode.NotFound, response.status) @@ -29,15 +66,87 @@ class ChatControllerTest { } @Test - fun `member can read own chat`() = runApp { client -> - val alice = client.createUser("alice") - val created = client.createChat(alice, title = "notes", memberIds = listOf(alice.id)) + fun `invalid member lists are rejected with 400`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") - val response = client.get("/api/v1/chats/${created.id}") { - header("X-User-Id", alice.id) + val cases = listOf( + listOf(bob.id.toString()), // creator is not a member + listOf(alice.id.toString(), alice.id.toString()), // duplicates + listOf(alice.id.toString(), "not-a-uuid"), // malformed id + listOf(alice.id.toString(), UUID.randomUUID().toString()), // unknown user + emptyList(), + ) + + for (memberIds in cases) { + val response = client.postChat(alice, "bad", memberIds) + assertEquals(HttpStatusCode.BadRequest, response.status, "member_ids=$memberIds") + } + } + + @Test + fun `failed chat creation leaves no partial rows`() = runApp { client -> + val alice = client.register("alice") + val title = "atomic-${UUID.randomUUID()}" + + val response = client.postChat(alice, title, listOf(alice.id.toString(), UUID.randomUUID().toString())) + assertEquals(HttpStatusCode.BadRequest, response.status) + + val chats = transaction { + ChatModel.selectAll().where(ChatModel.title eq title).count() + } + assertEquals(0, chats) + } + + @Test + fun `chat list contains only own chats and is paginated`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + val eve = client.register("eve") + + val created = (0 until 5).map { + client.createChat(alice, title = "c$it", memberIds = listOf(alice.id, bob.id)) + } + client.createChat(eve, title = "eve only", memberIds = listOf(eve.id)) + + val collected = mutableListOf() + var cursor: String? = null + + do { + val page = client.get("/api/v1/chats") { + auth(bob) + url { + parameters.append("limit", "2") + cursor?.let { parameters.append("cursor", it) } + } + }.body>() + + collected += page.items + cursor = page.nextCursor + } while (cursor != null) + + assertEquals(created, collected) + + val evePage = client.get("/api/v1/chats") { auth(eve) }.body>() + assertEquals(listOf("eve only"), evePage.items.map { it.title }) + assertNull(evePage.nextCursor) + } + + @Test + fun `cursor issued to another user is rejected`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + repeat(2) { client.createChat(alice, title = "c$it", memberIds = listOf(alice.id)) } + + val cursor = client.get("/api/v1/chats?limit=1") { auth(alice) } + .body>() + .nextCursor!! + + val response = client.get("/api/v1/chats") { + auth(bob) + url { parameters.append("cursor", cursor) } } - assertEquals(HttpStatusCode.OK, response.status) - assertEquals(created.id, response.body().id) + assertEquals(HttpStatusCode.BadRequest, response.status) } } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt index fbe943fd..66a36f3f 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt @@ -15,7 +15,7 @@ class HealthControllerTest { } @Test - fun `ready returns 200`() = runApp { client -> + fun `ready returns 200 when database is reachable`() = runApp { client -> val response = client.get("/health/ready") assertEquals(HttpStatusCode.OK, response.status) } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt index ea3cf062..a91cb3d8 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt @@ -1,13 +1,14 @@ package com.mtusi.messenger.main.infrastructure.controllers.message import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest -import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp import io.ktor.client.call.body import io.ktor.client.request.get -import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType @@ -23,7 +24,7 @@ class MessageConcurrencyTest { @Test fun `parallel senders produce exactly N unique messages`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "load", memberIds = listOf(alice.id)) val workers = 10 @@ -35,7 +36,7 @@ class MessageConcurrencyTest { async { repeat(perWorker) { i -> val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "w$w-i$i")) } @@ -50,7 +51,7 @@ class MessageConcurrencyTest { do { val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "100") if (cursor != null) parameters.append("cursor", cursor!!) @@ -58,7 +59,7 @@ class MessageConcurrencyTest { } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() collected += page.items.map { it.text } cursor = page.nextCursor } while (cursor != null) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt index d689ece9..ac72e82c 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt @@ -2,13 +2,14 @@ package com.mtusi.messenger.main.infrastructure.controllers.message import com.mtusi.messenger.main.extensions.ErrorBody import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest -import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp import io.ktor.client.call.body import io.ktor.client.request.get -import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType @@ -23,11 +24,11 @@ class MessageControllerTest { @Test fun `empty text returns 400 invalid_request`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "")) } @@ -38,12 +39,12 @@ class MessageControllerTest { @Test fun `foreign chat returns 404 when sending`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val bob = client.register("bob") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", bob.id) + auth(bob) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "hi")) } @@ -54,12 +55,12 @@ class MessageControllerTest { @Test fun `foreign chat returns 404 when listing`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val bob = client.register("bob") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", bob.id) + auth(bob) } assertEquals(HttpStatusCode.NotFound, response.status) @@ -67,13 +68,13 @@ class MessageControllerTest { @Test fun `pagination walks all messages exactly once`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val total = 25 repeat(total) { i -> val r = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "m$i")) } @@ -86,7 +87,7 @@ class MessageControllerTest { do { val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") if (cursor != null) parameters.append("cursor", cursor!!) @@ -94,7 +95,7 @@ class MessageControllerTest { } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() collected += page.items.map { it.text } cursor = page.nextCursor pages++ @@ -108,32 +109,32 @@ class MessageControllerTest { @Test fun `history that is an exact multiple of limit ends with null next_cursor`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) repeat(20) { i -> client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "m$i")) } } val first = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") } - }.body() + }.body>() val cursor = first.nextCursor assertNotNull(cursor) val second = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") parameters.append("cursor", cursor) } - }.body() + }.body>() assertEquals((10 until 20).map { "m$it" }, second.items.map { it.text }) assertNull(second.nextCursor) @@ -141,43 +142,43 @@ class MessageControllerTest { @Test fun `last page has null next_cursor`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() assertEquals(0, page.items.size) assertNull(page.nextCursor) } @Test fun `foreign cursor returns 400`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chatA = client.createChat(alice, title = "a", memberIds = listOf(alice.id)) val chatB = client.createChat(alice, title = "b", memberIds = listOf(alice.id)) repeat(2) { i -> client.post("/api/v1/chats/${chatA.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "a$i")) } } val firstA = client.get("/api/v1/chats/${chatA.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "1") } - }.body() + }.body>() val cursor = firstA.nextCursor assertNotNull(cursor) val response = client.get("/api/v1/chats/${chatB.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "1") parameters.append("cursor", cursor) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt index f2f689a5..b2d7dfea 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt @@ -2,30 +2,48 @@ package com.mtusi.messenger.main.infrastructure.controllers.user import com.mtusi.messenger.main.extensions.ErrorBody import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.support.TEST_PASSWORD +import com.mtusi.messenger.main.support.auth +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp +import com.mtusi.messenger.main.support.uniqueUsername import io.ktor.client.call.body +import io.ktor.client.request.basicAuth import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.contentType +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNotNull class UserControllerTest { @Test - fun `create user returns 201 and echoes fields`() = runApp { client -> + fun `create user returns 201 without password`() = runApp { client -> + val username = uniqueUsername("alice") + val response = client.post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = "alice", displayName = "Alice")) + setBody(CreateUserRequest(username = username, displayName = "Alice", password = TEST_PASSWORD)) } assertEquals(HttpStatusCode.Created, response.status) + + val body = response.bodyAsText() + assertFalse("password" in body) + assertFalse(TEST_PASSWORD in body) + assertEquals(username, response.body().username) } @Test @@ -43,30 +61,120 @@ class UserControllerTest { } @Test - fun `duplicate username returns 409 conflict`() = runApp { client -> - client.createUser(username = "bob") - + fun `missing password returns 400`() = runApp { client -> val response = client.post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = "bob", displayName = "Bob 2")) + setBody("""{"username":"${uniqueUsername("nopass")}","display_name":"x"}""") } - assertEquals(HttpStatusCode.Conflict, response.status) - assertEquals("conflict", response.body().error.code) + assertEquals(HttpStatusCode.BadRequest, response.status) } @Test - fun `missing X-User-Id on protected endpoint returns 401`() = runApp { client -> + fun `password shorter than 12 code points returns 400`() = runApp { client -> + val response = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = uniqueUsername("short"), displayName = "x", password = "elevenchars")) + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + } + + @Test + fun `duplicate username returns 409 conflict`() = runApp { client -> + val username = uniqueUsername("bob") + + val request = CreateUserRequest(username = username, displayName = "Bob", password = TEST_PASSWORD) + + val first = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(request) + } + assertEquals(HttpStatusCode.Created, first.status) + + val second = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(request.copy(displayName = "Bob 2")) + } + + assertEquals(HttpStatusCode.Conflict, second.status) + assertEquals("conflict", second.body().error.code) + } + + @Test + fun `concurrent registrations of one username create exactly one user`() = runApp { client -> + val username = uniqueUsername("race") + val attempts = 10 + + val statuses = coroutineScope { + (0 until attempts).map { + async { + client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = username, displayName = "r$it", password = TEST_PASSWORD)) + }.status + } + }.awaitAll() + } + + assertEquals(1, statuses.count { it == HttpStatusCode.Created }) + assertEquals(attempts - 1, statuses.count { it == HttpStatusCode.Conflict }) + } + + @Test + fun `me returns the session owner`() = runApp { client -> + val alice = client.register("alice") + + val response = client.get("/api/v1/users/me") { + auth(alice) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(alice.user, response.body()) + } + + @Test + fun `missing token returns 401 with Bearer challenge`() = runApp { client -> val response = client.get("/api/v1/users/me") + assertEquals(HttpStatusCode.Unauthorized, response.status) assertEquals("unauthorized", response.body().error.code) + assertEquals("Bearer realm=\"messenger\"", response.headers[HttpHeaders.WWWAuthenticate]) } @Test - fun `unknown X-User-Id returns 401`() = runApp { client -> + fun `X-User-Id alone gives no access`() = runApp { client -> + val alice = client.register("alice") + val response = client.get("/api/v1/users/me") { - header("X-User-Id", "00000000-0000-0000-0000-000000000000") + header("X-User-Id", alice.id.toString()) } + assertEquals(HttpStatusCode.Unauthorized, response.status) } + + @Test + fun `X-User-Id does not override bearer identity`() = runApp { client -> + val alice = client.register("alice") + val eve = client.register("eve") + + val response = client.get("/api/v1/users/me") { + auth(alice) + header("X-User-Id", eve.id.toString()) + } + + assertEquals(alice.id, response.body().id) + } + + @Test + fun `Basic credentials are rejected on business endpoints`() = runApp { client -> + val alice = client.register("alice") + + val response = client.get("/api/v1/users/me") { + basicAuth(alice.user.username, alice.password) + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals("Bearer realm=\"messenger\"", response.headers[HttpHeaders.WWWAuthenticate]) + } } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt deleted file mode 100644 index 23e36884..00000000 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.message - -import com.mtusi.messenger.main.infrastructure.dto.Message -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -private const val CHAT_ID = "chat" - -class InMemoryMessageRepositoryTest { - - private fun repositoryWith(size: Int): InMemoryMessageRepository { - - val repository = InMemoryMessageRepository() - - repeat(size) { i -> - repository.append( - CHAT_ID, - Message( - id = "m$i", - chatId = CHAT_ID, - senderId = "u", - text = "t$i", - createdAt = "2026-01-01T00:00:00.000Z", - ), - ) - } - - return repository - } - - @Test - fun `returns requested window in append order`() { - val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 3, count = 4) - assertEquals(listOf("m3", "m4", "m5", "m6"), range.map { it.id }) - } - - @Test - fun `window is clipped at the end of history`() { - val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 8, count = 5) - assertEquals(listOf("m8", "m9"), range.map { it.id }) - } - - @Test - fun `offset past the end returns empty`() { - assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 10, count = 5).isEmpty()) - } - - @Test - fun `huge offset does not overflow`() { - assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = Int.MAX_VALUE - 1, count = 51).isEmpty()) - } - - @Test - fun `unknown chat returns empty`() { - assertTrue(InMemoryMessageRepository().findRangeByChatId("missing", offset = 0, count = 50).isEmpty()) - } -} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt new file mode 100644 index 00000000..384e053c --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt @@ -0,0 +1,45 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing + +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +class DefaultHashingServiceTest { + + private val service = DefaultHashingService() + + @Test + fun `hash is a salted Argon2id PHC string`() { + val first = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + val second = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + + assertTrue(first.startsWith("\$argon2id\$v=19\$m=19456,t=2,p=1\$")) + assertFalse("correct-horse-battery" in first) + assertNotEquals(first, second, "same password must produce different hashes (random salt)") + } + + @Test + fun `validates the right password and rejects a wrong one`() { + val hash = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + + assertTrue(service.validateHash(HashingAlgorithm.Argon2id, "correct-horse-battery", hash)) + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "correct-horse-batterY", hash)) + } + + @Test + fun `passwords differing only after 72 bytes are distinguished`() { + // bcrypt silently truncates input to 72 bytes; Argon2id must not. + val prefix = "ж".repeat(40) // 80 bytes in UTF-8 + val hash = service.computeHash(HashingAlgorithm.Argon2id, prefix + "a") + + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, prefix + "b", hash)) + } + + @Test + fun `malformed hash is rejected instead of throwing`() { + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "whatever", "not-a-hash")) + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "whatever", "\$argon2id\$v=19\$m=x\$a\$b")) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt b/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt new file mode 100644 index 00000000..93ccd43f --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt @@ -0,0 +1,49 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.support.TestDatabase +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import com.zaxxer.hikari.HikariDataSource +import org.flywaydb.core.Flyway +import kotlin.test.Test +import kotlin.test.assertEquals + +class DatabaseMigrationTest { + + @Test + fun `re-running migrations applies nothing and keeps data`() = runApp { client -> + client.createUser("keep") + + HikariDataSource().apply { + jdbcUrl = TestDatabase.container.jdbcUrl + username = TestDatabase.USERNAME + password = TestDatabase.PASSWORD + }.use { dataSource -> + + val usersBefore = countUsers(dataSource) + + applyDatabaseMigrations(dataSource) + applyDatabaseMigrations(dataSource) + + val flyway = Flyway.configure() + .dataSource(dataSource) + .locations("classpath:migrations") + .load() + + assertEquals(0, flyway.info().pending().size) + assertEquals(flyway.info().applied().size, flyway.info().all().size) + assertEquals(usersBefore, countUsers(dataSource)) + } + } + + private fun countUsers(dataSource: HikariDataSource): Long { + return dataSource.connection.use { connection -> + connection.createStatement().use { statement -> + statement.executeQuery("SELECT count(*) FROM users").use { + it.next() + it.getLong(1) + } + } + } + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt index 6ce1f537..4917d5f5 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt @@ -1,27 +1,31 @@ package com.mtusi.messenger.main.support -import com.mtusi.messenger.main.infrastructure.dto.Chat -import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.User import com.mtusi.messenger.main.module +import com.typesafe.config.ConfigFactory import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.client.request.header +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.basicAuth +import io.ktor.client.request.bearerAuth import io.ktor.client.request.post import io.ktor.client.request.setBody -import io.ktor.client.statement.HttpResponse import io.ktor.http.ContentType -import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.config.HoconApplicationConfig import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonNamingStrategy +import java.util.UUID @OptIn(ExperimentalSerializationApi::class) val testJson = Json { @@ -30,7 +34,40 @@ val testJson = Json { namingStrategy = JsonNamingStrategy.SnakeCase } -fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApplication { +const val TEST_PASSWORD = "correct-horse-battery" + +data class TestUser( + val user: User, + val password: String, + val token: String, +) { + val id: UUID + get() = user.id +} + +private fun testConfig(sessionTtlSeconds: Long) = HoconApplicationConfig( + ConfigFactory.parseMap( + mapOf( + "database.host" to TestDatabase.container.host, + "database.port" to TestDatabase.container.firstMappedPort, + "database.name" to TestDatabase.NAME, + "database.username" to TestDatabase.USERNAME, + "database.password" to TestDatabase.PASSWORD, + "database.maxPoolSize" to 10, + "database.connectionTimeoutMs" to 10000, + "authentication.realm" to "messenger", + "authentication.sessionTtlSeconds" to sessionTtlSeconds, + ) + ) +) + +fun runApp( + sessionTtlSeconds: Long = 3600, + block: suspend ApplicationTestBuilder.(HttpClient) -> Unit +) = testApplication { + environment { + config = testConfig(sessionTtlSeconds) + } application { module() } @@ -42,30 +79,50 @@ fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApp block(client) } -suspend fun HttpClient.createUser(username: String, displayName: String = username): User { +/** + * Usernames are unique per call: all tests share one database. + */ +fun uniqueUsername(prefix: String): String = "${prefix}_${UUID.randomUUID().toString().replace("-", "").take(12)}" + +suspend fun HttpClient.createUser(prefix: String, password: String = TEST_PASSWORD): User { + val username = uniqueUsername(prefix) val response = post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = username, displayName = displayName)) + setBody(CreateUserRequest(username = username, displayName = prefix, password = password)) } check(response.status == HttpStatusCode.Created) { "createUser failed: ${response.status}" } return response.body() } +suspend fun HttpClient.login(username: String, password: String): SessionResponse { + val response = post("/api/v1/auth/sessions") { + basicAuth(username, password) + } + check(response.status == HttpStatusCode.Created) { "login failed: ${response.status}" } + return response.body() +} + +/** + * Registers a user and opens a session for it. + */ +suspend fun HttpClient.register(prefix: String): TestUser { + val user = createUser(prefix) + val session = login(user.username, TEST_PASSWORD) + return TestUser(user, TEST_PASSWORD, session.token) +} + +fun HttpRequestBuilder.auth(user: TestUser) = bearerAuth(user.token) + suspend fun HttpClient.createChat( - creator: User, + creator: TestUser, title: String, - memberIds: List, + memberIds: List, ): Chat { val response = post("/api/v1/chats") { - header("X-User-Id", creator.id) + auth(creator) contentType(ContentType.Application.Json) - setBody(CreateChatRequest(title = title, memberIds = memberIds)) + setBody(CreateChatRequest(title = title, memberIds = memberIds.map(UUID::toString))) } check(response.status == HttpStatusCode.Created) { "createChat failed: ${response.status}" } return response.body() } - -fun HttpResponse.header(name: String): String? = headers[name] - -val HttpResponse.requestId: String? - get() = headers[HttpHeaders.XRequestId] diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt new file mode 100644 index 00000000..c4897e8a --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt @@ -0,0 +1,24 @@ +package com.mtusi.messenger.main.support + +import org.testcontainers.containers.PostgreSQLContainer +import org.testcontainers.utility.DockerImageName + +/** + * One PostgreSQL container per test JVM, same image as compose.yaml. + * Tests share it and stay independent by using unique usernames. + */ +object TestDatabase { + + const val NAME = "messenger" + const val USERNAME = "messenger" + const val PASSWORD = "messenger" + + val container: PostgreSQLContainer<*> by lazy { + PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres")) + .withDatabaseName(NAME) + .withUsername(USERNAME) + .withPassword(PASSWORD) + .also { it.start() } + } + +} -- 2.54.0 From 6db9791b09d932ac61a600aaa076d5420ccd2a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=9A=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D1=8F=D0=B2=D0=B5=D0=BD=D0=BA=D0=BE?= <51+mraksimus@noreply.gitea.privcloud.tech> Date: Thu, 8 Oct 2026 20:35:46 +0300 Subject: [PATCH 3/7] delete dev file --- run/development/config/application.conf | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 run/development/config/application.conf diff --git a/run/development/config/application.conf b/run/development/config/application.conf deleted file mode 100644 index 845ad1f4..00000000 --- a/run/development/config/application.conf +++ /dev/null @@ -1,10 +0,0 @@ -ktor { - application { - modules = [com.mtusi.messenger.main.AppKt.module] - } - - deployment { - host = "127.0.0.1" - port = 8080 - } -} -- 2.54.0 From 0d831df2cfe35d3df7cad29e128f3919d3ca1130 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Thu, 8 Oct 2026 21:04:30 +0300 Subject: [PATCH 4/7] Add migration file generator --- build.gradle.kts | 10 ++ gradle/libs.versions.toml | 2 + .../models/authentication/SessionModel.kt | 6 +- .../models/chat/ChatMemberModel.kt | 8 +- .../models/message/MessageModel.kt | 8 +- .../mtusi/messenger/main/plugins/Database.kt | 99 +++++++++++++++++-- 6 files changed, 118 insertions(+), 15 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index cfb31b6c..5acf40ee 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -36,6 +36,8 @@ dependencies { implementation(libs.exposed.core) implementation(libs.exposed.jdbc) implementation(libs.exposed.kotlin.datetime) + implementation(libs.exposed.migration.core) + implementation(libs.exposed.migration.jdbc) implementation(libs.postgres) implementation(libs.hikaricp) @@ -100,4 +102,12 @@ tasks { args = configArgs workingDir = file("run/development") } + + register("generateMigration") { + group = "database" + description = "Generates a new migration" + + classpath = sourceSets["main"].runtimeClasspath + mainClass.set("com.mtusi.messenger.main.plugins.DatabaseKt") + } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ad76a4c8..7ca03d0a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -37,6 +37,8 @@ koin-test = { module = "io.insert-koin:koin-test", version.ref = "koin" } exposed-core = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" } exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "exposed" } exposed-kotlin-datetime = { module = "org.jetbrains.exposed:exposed-kotlin-datetime", version.ref = "exposed" } +exposed-migration-core = { module = "org.jetbrains.exposed:exposed-migration-core", version.ref = "exposed" } +exposed-migration-jdbc = { module = "org.jetbrains.exposed:exposed-migration-jdbc", version.ref = "exposed" } postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" } hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt index cfc1d7e3..6b847e59 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt @@ -6,8 +6,12 @@ import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable import org.jetbrains.exposed.v1.datetime.timestamp object SessionModel : UUIDTable("sessions") { - val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE) + val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "sessions_user_id_fkey") val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key") val createdAt = timestamp("created_at") val expiresAt = timestamp("expires_at") + + init { + index("sessions_user_id_idx", false, userId) + } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt index acbcb0fb..cd48d84d 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt @@ -5,9 +5,13 @@ import org.jetbrains.exposed.v1.core.ReferenceOption import org.jetbrains.exposed.v1.core.Table object ChatMemberModel : Table("chat_members") { - val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE) - val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE) + val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_chat_id_fkey") + val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_user_id_fkey") val position = integer("position") override val primaryKey = PrimaryKey(chatId, userId) + + init { + index("chat_members_user_id_idx", false, userId) + } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt index 9d90d600..301c59f6 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt @@ -9,8 +9,12 @@ import org.jetbrains.exposed.v1.datetime.timestamp const val MAX_MESSAGE_TEXT_LENGTH = 4000 object MessageModel : UUIDTable("messages") { - val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE) - val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE) + val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_chat_id_fkey") + val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_sender_id_fkey") val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH) val createdAt = timestamp("created_at") + + init { + index("messages_chat_id_created_at_id_idx", false, chatId, createdAt, id) + } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt index 74b55b5f..c1a459d8 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -1,34 +1,41 @@ package com.mtusi.messenger.main.plugins import com.mtusi.messenger.main.config.database.DatabaseConfig +import com.mtusi.messenger.main.config.database.SerialDatabaseConfig +import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel +import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.infrastructure.models.message.MessageModel +import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import com.typesafe.config.ConfigFactory import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import io.ktor.server.application.Application import io.ktor.server.application.ApplicationStopped +import io.ktor.server.config.HoconApplicationConfig +import io.ktor.server.config.getAs import kotlinx.coroutines.Dispatchers import org.flywaydb.core.Flyway +import org.jetbrains.exposed.v1.core.ExperimentalDatabaseMigrationApi +import org.jetbrains.exposed.v1.core.Table import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig import org.jetbrains.exposed.v1.jdbc.Database import org.jetbrains.exposed.v1.jdbc.JdbcTransaction import org.jetbrains.exposed.v1.jdbc.transactions.experimental.newSuspendedTransaction +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import org.jetbrains.exposed.v1.migration.jdbc.MigrationUtils import org.koin.ktor.ext.inject import java.io.File import javax.sql.DataSource +private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations" +private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf" + fun Application.configureDatabase() { val config by inject() - val dataSource = HikariDataSource( - HikariConfig().apply { - poolName = "messenger" - jdbcUrl = config.jdbcConnectionUrl - username = config.username - password = config.resolvePassword() - maximumPoolSize = config.maxPoolSize - connectionTimeout = config.connectionTimeoutMs - } - ) + val dataSource = config.createDataSource() Database.connect( datasource = dataSource, @@ -44,6 +51,19 @@ fun Application.configureDatabase() { } +private fun DatabaseConfig.createDataSource(): HikariDataSource { + return HikariDataSource( + HikariConfig().apply { + poolName = "messenger" + jdbcUrl = jdbcConnectionUrl + username = this@createDataSource.username + password = resolvePassword() + maximumPoolSize = maxPoolSize + connectionTimeout = connectionTimeoutMs + } + ) +} + private fun DatabaseConfig.resolvePassword(): String { return password ?: passwordFile?.let { File(it).readText().trim() } @@ -64,6 +84,65 @@ fun applyDatabaseMigrations( } +fun main(args: Array) { + generateMigration(args.joinToString("_")) +} + +@OptIn(ExperimentalDatabaseMigrationApi::class) +private fun generateMigration(description: String) { + require(description.isNotEmpty()) { "Description cannot be empty" } + + val tables: Array = arrayOf( + UserModel, + ChatModel, + ChatMemberModel, + MessageModel, + SessionModel + ) + + val config = HoconApplicationConfig(ConfigFactory.parseFile(File(DEVELOPMENT_DATABASE_CONFIG)).resolve()) + .property("database") + .getAs() + + config.createDataSource().use { dataSource -> + + Database.connect(dataSource) + applyDatabaseMigrations(dataSource) + + val migrations = File(MIGRATIONS_DIRECTORY).listFiles { it.extension == "sql" }.orEmpty() + + val latestVersion = migrations.maxOfOrNull { + it.name + .substringBefore("__") + .drop(1) + .toInt() + } + + val version = latestVersion?.inc() ?: 1 + + transaction { + + val statements = MigrationUtils.statementsRequiredForDatabaseMigration(*tables) + + if (statements.isEmpty()) { + println("Database schema is up to date, no migration generated") + return@transaction + } + + val script = MigrationUtils.generateMigrationScript( + tables = tables, + scriptDirectory = MIGRATIONS_DIRECTORY, + scriptName = "V${version}__$description" + ) + + println("Generated migration ${script.path}") + + } + + } + +} + suspend fun suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction( context = Dispatchers.IO, statement = statement -- 2.54.0 From 1632fe4b16bb33228278b72692dda8ea508d6f1d Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Fri, 9 Oct 2026 00:27:36 +0300 Subject: [PATCH 5/7] Completed for a grade of four --- build.gradle.kts | 2 + compose.yaml | 33 +++++ evidence/explain-history.txt | 66 +++++++++ gradle/libs.versions.toml | 3 + run/_template/config/redis.conf | 6 + scripts/explain-history.sh | 10 ++ scripts/init-secrets.sh | 19 +-- scripts/restart.sh | 6 +- scripts/sql/explain-history.sql | 100 +++++++++++++ .../kotlin/com/mtusi/messenger/main/App.kt | 2 + .../authentication/AuthenticationConfig.kt | 1 + .../SerialAuthenticationConfig.kt | 3 +- .../main/config/database/DatabaseConfig.kt | 1 + .../config/database/SerialDatabaseConfig.kt | 3 +- .../main/config/redis/DefaultRedisConfig.kt | 11 ++ .../main/config/redis/RedisConfig.kt | 15 ++ .../main/config/redis/SerialRedisConfig.kt | 14 ++ .../AuthenticationController.kt | 4 +- .../dto/authentication/Session.kt | 1 + .../repositories/_common/RedisConnection.kt | 88 ++++++++++++ .../session/ExposedSessionRepository.kt | 12 +- .../session/SessionRepository.kt | 3 +- .../session/cache/CachedSession.kt | 11 ++ .../cache/RedisSessionCacheRepository.kt | 86 ++++++++++++ .../session/cache/SessionCacheRepository.kt | 33 +++++ .../authentication/AuthenticationService.kt | 13 +- .../DefaultAuthenticationService.kt | 77 ++++++++-- .../mtusi/messenger/main/plugins/Database.kt | 12 +- .../com/mtusi/messenger/main/plugins/Redis.kt | 16 +++ .../messenger/main/plugins/StatusPages.kt | 14 +- .../plugins/authentication/Authentication.kt | 9 +- .../plugins/authentication/UserPrincipal.kt | 11 +- .../com/mtusi/messenger/main/utils/Secrets.kt | 13 ++ src/main/resources/application.conf | 13 ++ .../cache/RedisSessionCacheRepositoryTest.kt | 83 +++++++++++ .../main/plugins/DependencyFailureTest.kt | 132 ++++++++++++++++++ .../main/plugins/SessionCacheTest.kt | 65 +++++++++ .../mtusi/messenger/main/support/TestApp.kt | 40 ++++-- .../messenger/main/support/TestDatabase.kt | 10 +- .../mtusi/messenger/main/support/TestRedis.kt | 54 +++++++ 40 files changed, 1034 insertions(+), 61 deletions(-) create mode 100644 evidence/explain-history.txt create mode 100644 run/_template/config/redis.conf create mode 100755 scripts/explain-history.sh create mode 100644 scripts/sql/explain-history.sql create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/redis/DefaultRedisConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/redis/RedisConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/redis/SerialRedisConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/_common/RedisConnection.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/CachedSession.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Redis.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Secrets.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/plugins/SessionCacheTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/support/TestRedis.kt diff --git a/build.gradle.kts b/build.gradle.kts index 5acf40ee..0a5b5720 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -44,6 +44,8 @@ dependencies { implementation(libs.flyway) implementation(libs.flyway.postgresql) + implementation(libs.lettuce) + implementation(libs.bouncycastle) testImplementation(kotlin("test")) diff --git a/compose.yaml b/compose.yaml index 5e562850..0a80034a 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,6 +21,31 @@ services: start_period: 10s restart: unless-stopped + redis: + image: redis:8.4.0-alpine + container_name: mtusi-lab2-redis + # Session cache only, PostgreSQL is the source of truth: no RDB/AOF, a restart simply empties the cache. + # Every key carries a TTL, so under memory pressure volatile-lru evicts the least used sessions. + command: + - sh + - -c + - >- + exec docker-entrypoint.sh redis-server + --requirepass "$$(cat /run/secrets/redis_password)" + --save "" + --appendonly no + --maxmemory 64mb + --maxmemory-policy volatile-lru + secrets: + - redis_password + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_password)\" redis-cli ping | grep -q PONG"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + api: build: . image: mtusi-messenger:lab2 @@ -28,6 +53,8 @@ services: depends_on: postgres: condition: service_healthy + redis: + condition: service_healthy environment: APP_HOST: "0.0.0.0" APP_PORT: "8080" @@ -36,9 +63,13 @@ services: DB_NAME: messenger DB_USER: messenger DB_PASSWORD_FILE: /run/secrets/db_password + REDIS_HOST: redis + REDIS_PORT: "6379" + REDIS_PASSWORD_FILE: /run/secrets/redis_password SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} secrets: - db_password + - redis_password ports: - "127.0.0.1:8080:8080" restart: unless-stopped @@ -46,6 +77,8 @@ services: secrets: db_password: file: ./secrets/db_password + redis_password: + file: ./secrets/redis_password volumes: postgres-data: diff --git a/evidence/explain-history.txt b/evidence/explain-history.txt new file mode 100644 index 00000000..55f0e6dd --- /dev/null +++ b/evidence/explain-history.txt @@ -0,0 +1,66 @@ + +== Data volume + total_messages | target_chat_messages +----------------+---------------------- + 70006 | 20000 +(1 row) + + +== 1. First page: WHERE chat_id = ? ORDER BY created_at, id LIMIT 51 + QUERY PLAN +------------------------------------------------------------------------------------------------------------------ + Limit (actual time=0.005..0.022 rows=51 loops=1) + Buffers: shared hit=4 + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.005..0.020 rows=51 loops=1) + Index Cond: (chat_id = '00000000-0000-0000-0001-000000000000'::uuid) + Buffers: shared hit=4 + Planning: + Buffers: shared hit=6 + Planning Time: 0.045 ms + Execution Time: 0.029 ms +(9 rows) + + +== 2. Deep page after the 15 000th message: (created_at, id) > (?, ?) + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Limit (actual time=0.005..0.010 rows=51 loops=1) + Buffers: shared hit=4 + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.005..0.007 rows=51 loops=1) + Index Cond: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '5ec4eb0a-04cf-487e-9ec0-16b7367e29df'::uuid))) + Buffers: shared hit=4 + Planning Time: 0.027 ms + Execution Time: 0.025 ms +(7 rows) + + +== 3. Same deep page with OFFSET instead of a cursor (for comparison, not used by the API) + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------- + Limit (actual time=1.076..1.080 rows=51 loops=1) + Buffers: shared hit=296 + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.800 rows=15051 loops=1) + Index Cond: (chat_id = '00000000-0000-0000-0001-000000000000'::uuid) + Buffers: shared hit=296 + Planning Time: 0.025 ms + Execution Time: 1.093 ms +(7 rows) + + +== 4. Deep page without messages_chat_id_created_at_id_idx (index scans disabled for this query only) + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (actual time=2.151..2.154 rows=51 loops=1) + Buffers: shared hit=914 + -> Sort (actual time=2.151..2.152 rows=51 loops=1) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 31kB + Buffers: shared hit=914 + -> Seq Scan on messages (actual time=0.420..1.969 rows=5000 loops=1) + Filter: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '5ec4eb0a-04cf-487e-9ec0-16b7367e29df'::uuid))) + Rows Removed by Filter: 65006 + Buffers: shared hit=914 + Planning Time: 0.021 ms + Execution Time: 2.162 ms +(12 rows) + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7ca03d0a..ec020b4d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,6 +12,7 @@ exposed = "1.0.0" postgres = "42.7.3" hikaricp = "6.3.0" flyway = "11.9.0" +lettuce = "6.7.1.RELEASE" bouncycastle = "1.81" test-containers = "1.21.0" @@ -45,6 +46,8 @@ hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" } flyway = { module = "org.flywaydb:flyway-core", version.ref = "flyway" } flyway-postgresql = { module = "org.flywaydb:flyway-database-postgresql", version.ref = "flyway" } +lettuce = { module = "io.lettuce:lettuce-core", version.ref = "lettuce" } + bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } testContainers = { module = "org.testcontainers:testcontainers", version.ref = "test-containers" } diff --git a/run/_template/config/redis.conf b/run/_template/config/redis.conf new file mode 100644 index 00000000..f6a9b183 --- /dev/null +++ b/run/_template/config/redis.conf @@ -0,0 +1,6 @@ +redis { + host = "localhost" + port = 6379 + connectTimeoutMs = 500 + commandTimeoutMs = 500 +} diff --git a/scripts/explain-history.sh b/scripts/explain-history.sh new file mode 100755 index 00000000..fa0c07e0 --- /dev/null +++ b/scripts/explain-history.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Runs EXPLAIN (ANALYZE, BUFFERS) of the chat history query against the Compose PostgreSQL on 70 000 synthetic +# messages. The data is inserted and rolled back in one transaction; the plans are saved to evidence/. +set -eu +cd "$(dirname "$0")/.." + +mkdir -p evidence + +docker compose exec -T postgres psql -U messenger -d messenger -X -q < scripts/sql/explain-history.sql \ + | tee evidence/explain-history.txt diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh index 1700f205..70d9c47b 100755 --- a/scripts/init-secrets.sh +++ b/scripts/init-secrets.sh @@ -6,11 +6,14 @@ cd "$(dirname "$0")/.." mkdir -p secrets -if [ ! -s secrets/db_password ]; then - # Readable by the non-root users inside the api/postgres containers (bind-mounted as is). - umask 022 - openssl rand -hex 24 > secrets/db_password - echo "created secrets/db_password" -else - echo "secrets/db_password already exists, keeping it" -fi +# Readable by the non-root users inside the containers (bind-mounted as is). +umask 022 + +for name in db_password redis_password; do + if [ ! -s "secrets/$name" ]; then + openssl rand -hex 24 > "secrets/$name" + echo "created secrets/$name" + else + echo "secrets/$name already exists, keeping it" + fi +done diff --git a/scripts/restart.sh b/scripts/restart.sh index 6fd26f11..76c2bb0c 100755 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,7 +1,7 @@ #!/bin/sh -# Restarts the API and PostgreSQL, keeping the named volume (no `down -v`, no re-seed). +# Restarts the API, PostgreSQL and Redis, keeping the named volume (no `down -v`, no re-seed). set -eu cd "$(dirname "$0")/.." -docker compose stop api postgres -docker compose up -d --wait postgres api +docker compose stop api redis postgres +docker compose up -d --wait postgres redis api diff --git a/scripts/sql/explain-history.sql b/scripts/sql/explain-history.sql new file mode 100644 index 00000000..8467e137 --- /dev/null +++ b/scripts/sql/explain-history.sql @@ -0,0 +1,100 @@ +-- EXPLAIN (ANALYZE, BUFFERS) of the chat history query on synthetic data. +-- Everything runs in one transaction that is rolled back: the database is left untouched. +-- The queries are the ones ExposedMessageRepository.findPageByChatId generates (page size 50 + 1 look-ahead row). + +\set ON_ERROR_STOP on +\pset pager off + +BEGIN; + +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('00000000-0000-0000-0000-000000000001', 'explain_alice', 'Alice', 'not-a-hash', now()), + ('00000000-0000-0000-0000-000000000002', 'explain_bob', 'Bob', 'not-a-hash', now()); + +-- One large chat (20 000 messages) and 50 neighbours with 1 000 messages each: 70 000 rows in total, +-- so the plan has to skip foreign chats instead of reading a table that only holds the target chat. +INSERT INTO chats (id, title, created_at) +SELECT ('00000000-0000-0000-0001-' || lpad(n::text, 12, '0'))::uuid, 'explain chat ' || n, now() +FROM generate_series(0, 50) AS n; + +INSERT INTO chat_members (chat_id, user_id, position) +SELECT c.id, u.id, u.position +FROM chats c +CROSS JOIN (VALUES ('00000000-0000-0000-0000-000000000001'::uuid, 0), + ('00000000-0000-0000-0000-000000000002'::uuid, 1)) AS u (id, position) +WHERE c.title LIKE 'explain chat %'; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), + '00000000-0000-0000-0001-000000000000', + CASE WHEN n % 2 = 0 THEN '00000000-0000-0000-0000-000000000001'::uuid + ELSE '00000000-0000-0000-0000-000000000002'::uuid END, + 'message #' || n, + timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second' +FROM generate_series(1, 20000) AS n; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), + ('00000000-0000-0000-0001-' || lpad(c::text, 12, '0'))::uuid, + '00000000-0000-0000-0000-000000000001', + 'neighbour message #' || n, + timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second' +FROM generate_series(1, 50) AS c, generate_series(1, 1000) AS n; + +ANALYZE users, chats, chat_members, messages; + +\echo +\echo '== Data volume' +SELECT count(*) AS total_messages, + count(*) FILTER (WHERE chat_id = '00000000-0000-0000-0001-000000000000') AS target_chat_messages +FROM messages; + +-- Cursor of the 15 000th message: a deep page, where OFFSET pagination would have to skip 15 000 rows. +SELECT created_at AS cursor_created_at, id AS cursor_id +FROM messages +WHERE chat_id = '00000000-0000-0000-0001-000000000000' +ORDER BY created_at, id +OFFSET 14999 LIMIT 1 \gset + +\echo +\echo '== 1. First page: WHERE chat_id = ? ORDER BY created_at, id LIMIT 51' +EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) +SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = '00000000-0000-0000-0001-000000000000' +ORDER BY messages.created_at ASC, messages.id ASC +LIMIT 51; + +\echo +\echo '== 2. Deep page after the 15 000th message: (created_at, id) > (?, ?)' +EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) +SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE (messages.chat_id = '00000000-0000-0000-0001-000000000000') + AND ((messages.created_at, messages.id) > (:'cursor_created_at', :'cursor_id')) +ORDER BY messages.created_at ASC, messages.id ASC +LIMIT 51; + +\echo +\echo '== 3. Same deep page with OFFSET instead of a cursor (for comparison, not used by the API)' +EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) +SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = '00000000-0000-0000-0001-000000000000' +ORDER BY messages.created_at ASC, messages.id ASC +LIMIT 51 OFFSET 15000; + +\echo +\echo '== 4. Deep page without messages_chat_id_created_at_id_idx (index scans disabled for this query only)' +SET LOCAL enable_indexscan = off; +SET LOCAL enable_bitmapscan = off; +SET LOCAL enable_indexonlyscan = off; +EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) +SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE (messages.chat_id = '00000000-0000-0000-0001-000000000000') + AND ((messages.created_at, messages.id) > (:'cursor_created_at', :'cursor_id')) +ORDER BY messages.created_at ASC, messages.id ASC +LIMIT 51; + +ROLLBACK; diff --git a/src/main/kotlin/com/mtusi/messenger/main/App.kt b/src/main/kotlin/com/mtusi/messenger/main/App.kt index 31e47039..8ec647e2 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/App.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/App.kt @@ -6,6 +6,7 @@ import com.mtusi.messenger.main.plugins.configureContentNegotiation import com.mtusi.messenger.main.plugins.configureDatabase import com.mtusi.messenger.main.plugins.configureDefaultHeaders import com.mtusi.messenger.main.plugins.configureKoin +import com.mtusi.messenger.main.plugins.configureRedis import com.mtusi.messenger.main.plugins.configureRequestId import com.mtusi.messenger.main.plugins.configureRouting import com.mtusi.messenger.main.plugins.configureStatusPages @@ -18,6 +19,7 @@ fun Application.module() { configureKoin() configureDatabase() + configureRedis() configureContentNegotiation() configureDefaultHeaders() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt index bef24b8f..97752764 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt @@ -4,5 +4,6 @@ interface AuthenticationConfig { val realm: String val sessionTtlSeconds: Long + val sessionCacheTtlSeconds: Long } diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt index aa2f51cf..fbe89e1f 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt @@ -5,5 +5,6 @@ import kotlinx.serialization.Serializable @Serializable data class SerialAuthenticationConfig( override val realm: String, - override val sessionTtlSeconds: Long + override val sessionTtlSeconds: Long, + override val sessionCacheTtlSeconds: Long ) : AuthenticationConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt index e679f562..40d48c28 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt @@ -12,6 +12,7 @@ interface DatabaseConfig { val maxPoolSize: Int val connectionTimeoutMs: Long + val statementTimeoutMs: Long val jdbcConnectionUrl: String get() = "jdbc:postgresql://$host:$port/$name" diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt index c4f11b84..00c4890e 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt @@ -11,5 +11,6 @@ data class SerialDatabaseConfig( override val password: String? = null, override val passwordFile: String? = null, override val maxPoolSize: Int, - override val connectionTimeoutMs: Long + override val connectionTimeoutMs: Long, + override val statementTimeoutMs: Long ) : DatabaseConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/redis/DefaultRedisConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/redis/DefaultRedisConfig.kt new file mode 100644 index 00000000..9b7b168e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/redis/DefaultRedisConfig.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.config.redis + +import io.ktor.server.application.Application +import io.ktor.server.config.getAs +import org.koin.core.annotation.Provided +import org.koin.core.annotation.Single + +@Single +class DefaultRedisConfig( + @Provided app: Application +) : RedisConfig by app.environment.config.property("redis").getAs() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/redis/RedisConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/redis/RedisConfig.kt new file mode 100644 index 00000000..4393403d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/redis/RedisConfig.kt @@ -0,0 +1,15 @@ +package com.mtusi.messenger.main.config.redis + +interface RedisConfig { + + val host: String + val port: Int + + val username: String? + val password: String? + val passwordFile: String? + + val connectTimeoutMs: Long + val commandTimeoutMs: Long + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/redis/SerialRedisConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/redis/SerialRedisConfig.kt new file mode 100644 index 00000000..fddb8ed2 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/redis/SerialRedisConfig.kt @@ -0,0 +1,14 @@ +package com.mtusi.messenger.main.config.redis + +import kotlinx.serialization.Serializable + +@Serializable +data class SerialRedisConfig( + override val host: String, + override val port: Int, + override val username: String? = null, + override val password: String? = null, + override val passwordFile: String? = null, + override val connectTimeoutMs: Long, + override val commandTimeoutMs: Long +) : RedisConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt index 90f6e012..757f629b 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt @@ -44,9 +44,7 @@ fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") { authenticate(SESSION_AUTH) { delete("current") { - suspendedTransaction { - authenticationService.revokeSession(call.currentUser.sessionId) - } + authenticationService.revokeSession(call.currentUser.session) call.respond(HttpStatusCode.NoContent) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt index 4734da86..a56336f7 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt @@ -6,6 +6,7 @@ import kotlin.time.Instant data class Session( val id: UUID, val userId: UUID, + val tokenHash: String, val createdAt: Instant, val expiresAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/_common/RedisConnection.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/_common/RedisConnection.kt new file mode 100644 index 00000000..03d38375 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/_common/RedisConnection.kt @@ -0,0 +1,88 @@ +package com.mtusi.messenger.main.infrastructure.repositories._common + +import com.mtusi.messenger.main.config.redis.RedisConfig +import com.mtusi.messenger.main.utils.resolveSecret +import io.lettuce.core.ClientOptions +import io.lettuce.core.RedisClient +import io.lettuce.core.RedisConnectionException +import io.lettuce.core.RedisURI +import io.lettuce.core.SocketOptions +import io.lettuce.core.TimeoutOptions +import io.lettuce.core.api.StatefulRedisConnection +import io.lettuce.core.api.async.RedisAsyncCommands +import io.lettuce.core.codec.StringCodec +import kotlinx.coroutines.future.await +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.koin.core.annotation.Single +import java.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource + +private val RECONNECT_BACKOFF = 1.seconds + +/** + * Lazily connected Redis client. The application must start and serve requests without Redis, so the connection + * is opened on first use, a failed attempt is not retried for [RECONNECT_BACKOFF], and commands issued while + * disconnected fail immediately instead of queueing behind the reconnect. + */ +@Single +class RedisConnection( + config: RedisConfig +) : AutoCloseable { + + private val uri = RedisURI.builder() + .withHost(config.host) + .withPort(config.port) + .withTimeout(Duration.ofMillis(config.commandTimeoutMs)) + .apply { + val password = resolveSecret(config.password, config.passwordFile) + if (password != null) { + if (config.username != null) withAuthentication(config.username, password) else withPassword(password.toCharArray()) + } + } + .build() + + private val client = RedisClient.create().apply { + options = ClientOptions.builder() + .autoReconnect(true) + .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS) + .timeoutOptions(TimeoutOptions.enabled(Duration.ofMillis(config.commandTimeoutMs))) + .socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(config.connectTimeoutMs)).build()) + .build() + } + + private val mutex = Mutex() + + @Volatile + private var connection: StatefulRedisConnection? = null + + @Volatile + private var nextAttempt = TimeSource.Monotonic.markNow() + + suspend fun commands(): RedisAsyncCommands { + return (connection ?: connect()).async() + } + + private suspend fun connect(): StatefulRedisConnection = mutex.withLock { + + connection?.let { return it } + + if (nextAttempt.hasNotPassedNow()) { + throw RedisConnectionException("Redis is unavailable, next connection attempt is postponed") + } + + return try { + client.connectAsync(StringCodec.UTF8, uri).await().also { connection = it } + } catch (e: Exception) { + nextAttempt = TimeSource.Monotonic.markNow() + RECONNECT_BACKOFF + throw e as? RedisConnectionException ?: RedisConnectionException("Unable to connect to Redis", e) + } + } + + override fun close() { + connection?.close() + client.shutdown() + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt index 41f87e76..080b14e3 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt @@ -13,6 +13,7 @@ import org.jetbrains.exposed.v1.jdbc.selectAll import org.koin.core.annotation.Single import java.util.UUID import kotlin.time.Clock +import kotlin.time.Duration import kotlin.time.Instant @Single @@ -21,20 +22,24 @@ class ExposedSessionRepository : SessionRepository { override fun create( userId: UUID, tokenHash: String, - expiresAt: Instant + ttl: Duration ): Session { + val createdAt = Clock.System.nowMicros() + val expiresAt = createdAt + ttl + val insertedRow = SessionModel.insert { it[this.userId] = userId it[this.tokenHash] = tokenHash - it[this.createdAt] = Clock.System.nowMicros() + it[this.createdAt] = createdAt it[this.expiresAt] = expiresAt } return Session( id = insertedRow[SessionModel.id].value, userId = userId, - createdAt = insertedRow[SessionModel.createdAt], + tokenHash = tokenHash, + createdAt = createdAt, expiresAt = expiresAt ) } @@ -60,6 +65,7 @@ class ExposedSessionRepository : SessionRepository { private fun ResultRow.toSession() = Session( id = this[SessionModel.id].value, userId = this[SessionModel.userId].value, + tokenHash = this[SessionModel.tokenHash], createdAt = this[SessionModel.createdAt], expiresAt = this[SessionModel.expiresAt] ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt index d5bb2256..e693c339 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt @@ -3,6 +3,7 @@ package com.mtusi.messenger.main.infrastructure.repositories.authentication.sess import com.mtusi.messenger.main.infrastructure.dto.authentication.Session import com.mtusi.messenger.main.infrastructure.repositories.Repository import java.util.UUID +import kotlin.time.Duration import kotlin.time.Instant interface SessionRepository : Repository { @@ -10,7 +11,7 @@ interface SessionRepository : Repository { fun create( userId: UUID, tokenHash: String, - expiresAt: Instant + ttl: Duration ): Session fun findActiveByTokenHash( diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/CachedSession.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/CachedSession.kt new file mode 100644 index 00000000..86be49d5 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/CachedSession.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache + +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session + +sealed class CachedSession { + + data class Active(val session: Session) : CachedSession() + + data object Revoked : CachedSession() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt new file mode 100644 index 00000000..2035dd4a --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt @@ -0,0 +1,86 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache + +import com.mtusi.messenger.main.compat.serializers.SerialUUID +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection +import io.lettuce.core.SetArgs +import kotlinx.coroutines.future.await +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import org.koin.core.annotation.Single +import kotlin.time.Instant + +private const val KEY_PREFIX = "session:" +private const val REVOKED = "revoked" + +@Single +class RedisSessionCacheRepository( + private val redis: RedisConnection +) : SessionCacheRepository { + + override suspend fun find( + tokenHash: String + ): CachedSession? { + + val value = redis.commands().get(key(tokenHash)).await() ?: return null + + if (value == REVOKED) { + return CachedSession.Revoked + } + + return CachedSession.Active( + Json.decodeFromString(value).toSession(tokenHash) + ) + } + + override suspend fun putIfAbsent( + session: Session, + cachedUntil: Instant + ) { + redis.commands().set( + key(session.tokenHash), + Json.encodeToString(SessionEntry.from(session)), + SetArgs.Builder.nx().pxAt(cachedUntil.toEpochMilliseconds()) + ).await() + } + + override suspend fun revoke( + session: Session + ) { + redis.commands().set( + key(session.tokenHash), + REVOKED, + SetArgs.Builder.pxAt(session.expiresAt.toEpochMilliseconds()) + ).await() + } + + private fun key(tokenHash: String) = KEY_PREFIX + tokenHash + + @Serializable + private data class SessionEntry( + val id: SerialUUID, + val userId: SerialUUID, + val createdAt: Instant, + val expiresAt: Instant + ) { + + fun toSession(tokenHash: String) = Session( + id = id, + userId = userId, + tokenHash = tokenHash, + createdAt = createdAt, + expiresAt = expiresAt + ) + + companion object { + fun from(session: Session) = SessionEntry( + id = session.id, + userId = session.userId, + createdAt = session.createdAt, + expiresAt = session.expiresAt + ) + } + + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt new file mode 100644 index 00000000..c35340c1 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt @@ -0,0 +1,33 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache + +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories.Repository +import kotlin.time.Instant + +/** + * Cache-aside copy of [com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository]. + * PostgreSQL stays the source of truth: losing every key only costs a database lookup. + */ +interface SessionCacheRepository : Repository { + + suspend fun find( + tokenHash: String + ): CachedSession? + + /** + * Stores the session until [cachedUntil] unless the key already exists, so a lookup racing with a logout + * cannot overwrite the tombstone written by [revoke]. + */ + suspend fun putIfAbsent( + session: Session, + cachedUntil: Instant + ) + + /** + * Replaces the entry with a tombstone that lives until the session would have expired. + */ + suspend fun revoke( + session: Session + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt index 6ef710d0..dd86fe0d 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt @@ -16,12 +16,19 @@ interface AuthenticationService { userId: UUID ): IssuedSession - fun findSessionByToken( + /** + * Opens its own transaction only on a cache miss, so it must not be called inside one. + */ + suspend fun findSessionByToken( token: String ): Session? - fun revokeSession( - sessionId: UUID + /** + * Deletes the session in PostgreSQL, then replaces its cached copy with a tombstone. Without Redis only the + * database is updated: a copy cached before the outage can then live for at most the cache TTL. + */ + suspend fun revokeSession( + session: Session ): Boolean } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt index 960be0ad..cd5cd316 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt @@ -5,16 +5,21 @@ import com.mtusi.messenger.main.infrastructure.dto.User import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession import com.mtusi.messenger.main.infrastructure.dto.authentication.Session import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import com.mtusi.messenger.main.plugins.suspendedTransaction import com.mtusi.messenger.main.utils.computeSha256 -import com.mtusi.messenger.main.utils.nowMicros +import io.lettuce.core.RedisException import org.koin.core.annotation.Single +import org.slf4j.LoggerFactory import java.security.SecureRandom import java.util.Base64 import java.util.UUID import kotlin.time.Clock +import kotlin.time.Instant import kotlin.time.Duration.Companion.seconds private const val TOKEN_BYTES = 32 @@ -23,10 +28,13 @@ private const val TOKEN_BYTES = 32 class DefaultAuthenticationService( private val userRepository: UserRepository, private val sessionRepository: SessionRepository, + private val sessionCacheRepository: SessionCacheRepository, private val hashingService: HashingService, private val config: AuthenticationConfig ) : AuthenticationService { + private val logger = LoggerFactory.getLogger(DefaultAuthenticationService::class.java) + private val random = SecureRandom() private val dummyPasswordHash by lazy { @@ -64,7 +72,7 @@ class DefaultAuthenticationService( val session = sessionRepository.create( userId = userId, tokenHash = token.toByteArray().computeSha256(), - expiresAt = Clock.System.nowMicros() + config.sessionTtlSeconds.seconds + ttl = config.sessionTtlSeconds.seconds ) return IssuedSession( @@ -73,19 +81,68 @@ class DefaultAuthenticationService( ) } - override fun findSessionByToken( + override suspend fun findSessionByToken( token: String ): Session? { - return sessionRepository.findActiveByTokenHash( - tokenHash = token.toByteArray().computeSha256(), - now = Clock.System.now() - ) + + val tokenHash = token.toByteArray().computeSha256() + val now = Clock.System.now() + + when (val cached = findCachedSession(tokenHash)) { + is CachedSession.Revoked -> return null + is CachedSession.Active -> return cached.session.takeIf { it.expiresAt > now } + null -> Unit + } + + val session = suspendedTransaction { + sessionRepository.findActiveByTokenHash(tokenHash, now) + } ?: return null + + cacheSession(session, now) + + return session } - override fun revokeSession( - sessionId: UUID + override suspend fun revokeSession( + session: Session ): Boolean { - return sessionRepository.deleteById(sessionId) + + val isDeleted = suspendedTransaction { + sessionRepository.deleteById(session.id) + } + + try { + sessionCacheRepository.revoke(session) + } catch (e: RedisException) { + logger.warn("Session cache is unavailable, revoked session is not tombstoned: ${e.message}") + } + + return isDeleted + } + + private suspend fun findCachedSession( + tokenHash: String + ): CachedSession? { + return try { + sessionCacheRepository.find(tokenHash) + } catch (e: RedisException) { + logger.warn("Session cache is unavailable, reading from the database: ${e.message}") + null + } + } + + private suspend fun cacheSession( + session: Session, + now: Instant + ) { + try { + sessionCacheRepository.putIfAbsent( + session = session, + cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds) + ) + } catch (e: RedisException) { + logger.warn("Session cache is unavailable, session is not cached: ${e.message}") + } } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt index c1a459d8..f3ea24ed 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -7,6 +7,7 @@ import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel import com.mtusi.messenger.main.infrastructure.models.message.MessageModel import com.mtusi.messenger.main.infrastructure.models.user.UserModel +import com.mtusi.messenger.main.utils.resolveSecret import com.typesafe.config.ConfigFactory import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource @@ -30,6 +31,7 @@ import javax.sql.DataSource private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations" private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf" +private const val VALIDATION_TIMEOUT_MS = 1000L fun Application.configureDatabase() { @@ -57,19 +59,15 @@ private fun DatabaseConfig.createDataSource(): HikariDataSource { poolName = "messenger" jdbcUrl = jdbcConnectionUrl username = this@createDataSource.username - password = resolvePassword() + password = resolveSecret(this@createDataSource.password, passwordFile).orEmpty() maximumPoolSize = maxPoolSize connectionTimeout = connectionTimeoutMs + validationTimeout = minOf(VALIDATION_TIMEOUT_MS, connectionTimeoutMs - 1) + addDataSourceProperty("options", "-c statement_timeout=$statementTimeoutMs") } ) } -private fun DatabaseConfig.resolvePassword(): String { - return password - ?: passwordFile?.let { File(it).readText().trim() } - ?: "" -} - fun applyDatabaseMigrations( dataSource: DataSource ) { diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Redis.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Redis.kt new file mode 100644 index 00000000..d0aaea25 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Redis.kt @@ -0,0 +1,16 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection +import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationStopped +import org.koin.ktor.ext.get + +fun Application.configureRedis() { + + val redisConnection = get() + + monitor.subscribe(ApplicationStopped) { + redisConnection.close() + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt index 41d58395..3b39bc99 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt @@ -12,12 +12,16 @@ import io.ktor.server.plugins.BadRequestException import io.ktor.server.plugins.NotFoundException import io.ktor.server.plugins.UnsupportedMediaTypeException import io.ktor.server.plugins.statuspages.StatusPages +import io.lettuce.core.RedisException import kotlinx.serialization.SerializationException import java.sql.SQLException import java.sql.SQLTransientConnectionException private const val CONNECTION_ERROR_SQL_STATE_CLASS = "08" +// admin_shutdown, crash_shutdown, cannot_connect_now: the server is going down or still starting. +private const val SERVER_SHUTDOWN_SQL_STATE_PREFIX = "57P" + fun Application.configureStatusPages() = install(StatusPages) { exception { call, cause -> call.respondError(cause.code, cause.message ?: cause.code.wire) @@ -46,6 +50,10 @@ fun Application.configureStatusPages() = install(StatusPages) { call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") } } + exception { call, cause -> + call.application.log.warn("Redis unavailable: ${cause.message}") + call.respondError(ErrorCode.UNAVAILABLE, "service temporarily unavailable") + } exception { call, cause -> call.application.log.error("Unhandled error", cause) call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") @@ -61,6 +69,10 @@ fun Application.configureStatusPages() = install(StatusPages) { private fun SQLException.isConnectionFailure(): Boolean { return generateSequence(this) { it.cause }.any { it is SQLTransientConnectionException || - (it is SQLException && it.sqlState?.startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) == true) + (it is SQLException && it.sqlState.isUnavailableState()) } } + +private fun String?.isUnavailableState(): Boolean { + return this != null && (startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) || startsWith(SERVER_SHUTDOWN_SQL_STATE_PREFIX)) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt index e0d7b8e3..378524eb 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt @@ -32,14 +32,9 @@ fun Application.configureAuthentication() { bearerSession(SESSION_AUTH) { authenticate { token -> - val session = suspendedTransaction { - authenticationService.findSessionByToken(token) - } ?: return@authenticate null + val session = authenticationService.findSessionByToken(token) ?: return@authenticate null - return@authenticate UserPrincipal( - id = session.userId, - sessionId = session.id - ) + return@authenticate UserPrincipal(session) } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt index b8870e9c..4ac42fa8 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt @@ -1,8 +1,13 @@ package com.mtusi.messenger.main.plugins.authentication +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session import java.util.UUID data class UserPrincipal( - val id: UUID, - val sessionId: UUID -) + val session: Session +) { + + val id: UUID + get() = session.userId + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Secrets.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Secrets.kt new file mode 100644 index 00000000..e0b30312 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Secrets.kt @@ -0,0 +1,13 @@ +package com.mtusi.messenger.main.utils + +import java.io.File + +/** + * Secrets come either inline (local development) or as a mounted file (Docker secrets), the inline value wins. + */ +fun resolveSecret( + value: String?, + file: String? +): String? { + return value ?: file?.let { File(it).readText().trim() } +} diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf index dc393054..0927c5d7 100644 --- a/src/main/resources/application.conf +++ b/src/main/resources/application.conf @@ -27,10 +27,23 @@ database { maxPoolSize = 10 maxPoolSize = ${?DB_MAX_POOL_SIZE} connectionTimeoutMs = 2000 + statementTimeoutMs = 5000 +} + +redis { + host = "localhost" + host = ${?REDIS_HOST} + port = 6379 + port = ${?REDIS_PORT} + password = ${?REDIS_PASSWORD} + passwordFile = ${?REDIS_PASSWORD_FILE} + connectTimeoutMs = 500 + commandTimeoutMs = 500 } authentication { realm = "messenger" sessionTtlSeconds = 3600 sessionTtlSeconds = ${?SESSION_TTL_SECONDS} + sessionCacheTtlSeconds = 60 } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt new file mode 100644 index 00000000..ed2007dc --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt @@ -0,0 +1,83 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache + +import com.mtusi.messenger.main.config.redis.SerialRedisConfig +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection +import com.mtusi.messenger.main.support.TestRedis +import com.mtusi.messenger.main.utils.nowMicros +import kotlinx.coroutines.test.runTest +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes + +class RedisSessionCacheRepositoryTest { + + private fun withRepository(block: suspend (RedisSessionCacheRepository) -> Unit) = runTest { + val endpoint = TestRedis.endpoint() + val connection = RedisConnection( + SerialRedisConfig( + host = endpoint.host, + port = endpoint.port, + password = TestRedis.PASSWORD, + connectTimeoutMs = 2000, + commandTimeoutMs = 2000 + ) + ) + connection.use { block(RedisSessionCacheRepository(it)) } + } + + private fun session(ttl: Duration = 10.minutes): Session { + val now = Clock.System.nowMicros() + return Session( + id = UUID.randomUUID(), + userId = UUID.randomUUID(), + tokenHash = UUID.randomUUID().toString().replace("-", ""), + createdAt = now, + expiresAt = now + ttl + ) + } + + private fun ttlSeconds(session: Session): Long { + return TestRedis.cli(TestRedis.container, "TTL", "session:${session.tokenHash}").toLong() + } + + @Test + fun `cached session round-trips and expires together with the session`() = withRepository { repository -> + val session = session() + + assertNull(repository.find(session.tokenHash)) + + repository.putIfAbsent(session, cachedUntil = session.expiresAt) + + assertEquals(CachedSession.Active(session), repository.find(session.tokenHash)) + assertTrue(ttlSeconds(session) in 590..600, "key must expire at cachedUntil") + } + + @Test + fun `revoke replaces a cached session with a tombstone`() = withRepository { repository -> + val session = session() + repository.putIfAbsent(session, cachedUntil = session.expiresAt) + + repository.revoke(session) + + assertEquals(CachedSession.Revoked, repository.find(session.tokenHash)) + assertTrue(ttlSeconds(session) in 590..600, "tombstone must live until the session would expire") + } + + @Test + fun `late cache fill cannot overwrite a tombstone`() = withRepository { repository -> + val session = session() + + // A lookup read the session from PostgreSQL before logout and stores it after the logout finished. + repository.revoke(session) + repository.putIfAbsent(session, cachedUntil = session.expiresAt) + + assertEquals(CachedSession.Revoked, repository.find(session.tokenHash)) + } + +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt b/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt new file mode 100644 index 00000000..eaec7e10 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt @@ -0,0 +1,132 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.support.TestDatabase +import com.mtusi.messenger.main.support.TestRedis +import com.mtusi.messenger.main.support.auth +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import com.mtusi.messenger.main.utils.computeSha256 +import io.ktor.client.HttpClient +import io.ktor.client.call.body +import io.ktor.client.request.basicAuth +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.statement.HttpResponse +import io.ktor.http.HttpStatusCode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource + +class DependencyFailureTest { + + /** + * An unknown token can only be checked against PostgreSQL, so without it the answer is 503, never a success. + */ + private suspend fun HttpClient.assertAnonymousRejected( + unknownTokenStatus: HttpStatusCode = HttpStatusCode.Unauthorized + ) { + assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me").status) + assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me") { header("X-User-Id", "1") }.status) + assertEquals( + unknownTokenStatus, + get("/api/v1/users/me") { header("Authorization", "Bearer never-issued-token") }.status + ) + } + + private suspend fun assertUnavailable(response: HttpResponse) { + assertEquals(HttpStatusCode.ServiceUnavailable, response.status) + assertEquals("unavailable", response.body().error.code) + } + + @Test + fun `without Redis requests bypass the cache`() = runApp( + redis = TestRedis.unreachableEndpoint() + ) { client -> + assertEquals(HttpStatusCode.OK, client.get("/health/ready").status) + + val alice = client.register("alice") + val bob = client.register("bob") + + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + client.createChat(alice, "no redis", listOf(alice.id, bob.id)) + + client.assertAnonymousRejected() + + // PostgreSQL is the source of truth: logout still works and is visible immediately. + assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + } + + @Test + fun `hanging Redis costs one command timeout and recovers`() { + val redis = TestRedis.create().also { it.start() } + val docker = redis.dockerClient + + try { + runApp(redis = TestRedis.endpoint(redis)) { client -> + val alice = client.register("alice") + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + + docker.pauseContainerCmd(redis.containerId).exec() + + val started = TimeSource.Monotonic.markNow() + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + assertTrue(started.elapsedNow() < 2.seconds, "cache lookup must be bounded by the command timeout") + + client.assertAnonymousRejected() + + assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + + docker.unpauseContainerCmd(redis.containerId).exec() + + // The copy cached before the pause is replaced by the delayed tombstone, not resurrected. + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + + val bob = client.register("bob") + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(bob) }.status) + assertTrue( + TestRedis.cli(redis, "EXISTS", "session:${bob.token.toByteArray().computeSha256()}") == "1", + "cache is used again after recovery" + ) + } + } finally { + redis.stop() + } + } + + @Test + fun `without PostgreSQL requests fail with a bounded 503`() { + val database = TestDatabase.create().also { it.start() } + + try { + runApp(database = database, databaseConnectionTimeoutMs = 2000) { client -> + val alice = client.register("alice") + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + + database.dockerClient.stopContainerCmd(database.containerId).exec() + + val started = TimeSource.Monotonic.markNow() + + // The session itself is still served from Redis, the user lookup needs PostgreSQL. + assertUnavailable(client.get("/api/v1/users/me") { auth(alice) }) + assertUnavailable(client.post("/api/v1/auth/sessions") { basicAuth(alice.user.username, alice.password) }) + assertEquals(HttpStatusCode.ServiceUnavailable, client.get("/health/ready").status) + assertEquals(HttpStatusCode.OK, client.get("/health/live").status) + + assertTrue(started.elapsedNow() < 15.seconds, "every request must fail within the pool timeout") + + client.assertAnonymousRejected(unknownTokenStatus = HttpStatusCode.ServiceUnavailable) + } + } finally { + database.stop() + } + } + +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/plugins/SessionCacheTest.kt b/src/test/kotlin/com/mtusi/messenger/main/plugins/SessionCacheTest.kt new file mode 100644 index 00000000..d4523641 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/plugins/SessionCacheTest.kt @@ -0,0 +1,65 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.support.TestRedis +import com.mtusi.messenger.main.support.TestUser +import com.mtusi.messenger.main.support.auth +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import com.mtusi.messenger.main.utils.computeSha256 +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.http.HttpStatusCode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class SessionCacheTest { + + private val redis = TestRedis.container + + private fun cached(user: TestUser): String { + return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}") + } + + @Test + fun `first authenticated request fills the cache`() = runApp { client -> + val alice = client.register("alice") + + assertEquals("", cached(alice), "login does not write to the cache") + + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + + assertTrue(cached(alice).contains(alice.id.toString())) + + // The session lives for an hour, its cached copy at most sessionCacheTtlSeconds. + val ttl = TestRedis.cli(redis, "TTL", "session:${alice.token.toByteArray().computeSha256()}").toLong() + assertTrue(ttl in 1..60, "cached copy TTL was $ttl") + } + + @Test + fun `logout leaves a tombstone and the token is rejected`() = runApp { client -> + val alice = client.register("alice") + client.get("/api/v1/users/me") { auth(alice) } + + assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + + assertEquals("revoked", cached(alice)) + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + } + + @Test + fun `emptied cache falls back to PostgreSQL`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + client.get("/api/v1/users/me") { auth(alice) } + client.delete("/api/v1/auth/sessions/current") { auth(bob) } + + TestRedis.cli(redis, "FLUSHALL") + + // PostgreSQL is the source of truth: the live session survives, the revoked one stays revoked. + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(bob) }.status) + assertTrue(cached(alice).contains(alice.id.toString()), "cache is filled again") + } + +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt index 4917d5f5..c502993b 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt @@ -25,6 +25,7 @@ import io.ktor.server.testing.testApplication import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonNamingStrategy +import org.testcontainers.containers.PostgreSQLContainer import java.util.UUID @OptIn(ExperimentalSerializationApi::class) @@ -45,28 +46,51 @@ data class TestUser( get() = user.id } -private fun testConfig(sessionTtlSeconds: Long) = HoconApplicationConfig( +data class RedisEndpoint( + val host: String, + val port: Int, +) + +private fun testConfig( + sessionTtlSeconds: Long, + database: PostgreSQLContainer<*>, + databaseConnectionTimeoutMs: Long, + redis: RedisEndpoint, +) = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( - "database.host" to TestDatabase.container.host, - "database.port" to TestDatabase.container.firstMappedPort, - "database.name" to TestDatabase.NAME, - "database.username" to TestDatabase.USERNAME, - "database.password" to TestDatabase.PASSWORD, + "database.host" to database.host, + "database.port" to database.firstMappedPort, + "database.name" to database.databaseName, + "database.username" to database.username, + "database.password" to database.password, "database.maxPoolSize" to 10, - "database.connectionTimeoutMs" to 10000, + "database.connectionTimeoutMs" to databaseConnectionTimeoutMs, + "database.statementTimeoutMs" to 5000, + "redis.host" to redis.host, + "redis.port" to redis.port, + "redis.password" to TestRedis.PASSWORD, + "redis.connectTimeoutMs" to 500, + "redis.commandTimeoutMs" to 500, "authentication.realm" to "messenger", "authentication.sessionTtlSeconds" to sessionTtlSeconds, + "authentication.sessionCacheTtlSeconds" to 60, ) ) ) +/** + * Docker Desktop can be slow to accept the first connection, hence the generous default database timeout. + */ fun runApp( sessionTtlSeconds: Long = 3600, + database: PostgreSQLContainer<*> = TestDatabase.container, + databaseConnectionTimeoutMs: Long = 10000, + redis: RedisEndpoint = TestRedis.endpoint(), block: suspend ApplicationTestBuilder.(HttpClient) -> Unit ) = testApplication { environment { - config = testConfig(sessionTtlSeconds) + config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis) } application { module() diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt index c4897e8a..e9a29cd4 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt @@ -14,11 +14,17 @@ object TestDatabase { const val PASSWORD = "messenger" val container: PostgreSQLContainer<*> by lazy { - PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres")) + create().also { it.start() } + } + + /** + * A separate, not yet started container for tests that stop the database. + */ + fun create(): PostgreSQLContainer<*> { + return PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres")) .withDatabaseName(NAME) .withUsername(USERNAME) .withPassword(PASSWORD) - .also { it.start() } } } diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestRedis.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestRedis.kt new file mode 100644 index 00000000..d5a5b6ef --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestRedis.kt @@ -0,0 +1,54 @@ +package com.mtusi.messenger.main.support + +import org.testcontainers.containers.GenericContainer +import org.testcontainers.utility.DockerImageName +import java.net.ServerSocket + +/** + * One Redis container per test JVM, same image and memory settings as compose.yaml. + */ +object TestRedis { + + const val PASSWORD = "messenger" + + private const val PORT = 6379 + + val container: GenericContainer<*> by lazy { + create().also { it.start() } + } + + /** + * A separate, not yet started container for tests that pause or flush Redis. + */ + fun create(): GenericContainer<*> { + return GenericContainer(DockerImageName.parse("redis:8.4.0-alpine")) + .withExposedPorts(PORT) + .withCommand( + "redis-server", + "--requirepass", PASSWORD, + "--save", "", + "--appendonly", "no", + "--maxmemory-policy", "volatile-lru" + ) + } + + fun endpoint(container: GenericContainer<*> = this.container) = RedisEndpoint( + host = container.host, + port = container.getMappedPort(PORT) + ) + + /** + * An endpoint nobody listens on: connections are refused immediately. + */ + fun unreachableEndpoint(): RedisEndpoint { + val port = ServerSocket(0).use { it.localPort } + return RedisEndpoint(host = "127.0.0.1", port = port) + } + + fun cli(container: GenericContainer<*>, vararg command: String): String { + val result = container.execInContainer("redis-cli", "--no-auth-warning", "-a", PASSWORD, *command) + check(result.exitCode == 0) { "redis-cli failed: ${result.stderr}" } + return result.stdout.trim() + } + +} -- 2.54.0 From dc5abb6fffd7fb2d69d4e0ab60d9f57d4abcae67 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Fri, 9 Oct 2026 11:50:01 +0300 Subject: [PATCH 6/7] Completed for a grade of five --- REPORT.md | 261 +++++++++++++++++- compose.yaml | 3 + evidence/clean-start.txt | 34 +++ evidence/explain-history.txt | 42 +-- evidence/failures.txt | 38 +++ evidence/gradle-tests.txt | 72 +++++ evidence/persistence.txt | 27 ++ evidence/smoke.txt | 4 + evidence/storage.txt | 23 ++ .../read-after-write/off_redis-down.json | 11 + .../track1/read-after-write/off_redis-up.json | 11 + .../read-after-write/on_redis-down.json | 11 + .../track1/read-after-write/on_redis-up.json | 11 + evidence/track1/redis-restart-runs.csv | 11 + .../redis-restart/off/t50_r1/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/off/t50_r1/per-second.csv | 31 +++ .../track1/redis-restart/off/t50_r1/run.json | 4 + .../redis-restart/off/t50_r1/samples.csv | 31 +++ .../redis-restart/off/t50_r2/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/off/t50_r2/per-second.csv | 31 +++ .../track1/redis-restart/off/t50_r2/run.json | 4 + .../redis-restart/off/t50_r2/samples.csv | 31 +++ .../redis-restart/off/t50_r3/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/off/t50_r3/per-second.csv | 31 +++ .../track1/redis-restart/off/t50_r3/run.json | 4 + .../redis-restart/off/t50_r3/samples.csv | 31 +++ .../redis-restart/off/t50_r4/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/off/t50_r4/per-second.csv | 31 +++ .../track1/redis-restart/off/t50_r4/run.json | 4 + .../redis-restart/off/t50_r4/samples.csv | 31 +++ .../redis-restart/off/t50_r5/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/off/t50_r5/per-second.csv | 31 +++ .../track1/redis-restart/off/t50_r5/run.json | 4 + .../redis-restart/off/t50_r5/samples.csv | 31 +++ .../redis-restart/on/t50_r1/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/on/t50_r1/per-second.csv | 31 +++ .../track1/redis-restart/on/t50_r1/run.json | 4 + .../redis-restart/on/t50_r1/samples.csv | 31 +++ .../redis-restart/on/t50_r2/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/on/t50_r2/per-second.csv | 31 +++ .../track1/redis-restart/on/t50_r2/run.json | 4 + .../redis-restart/on/t50_r2/samples.csv | 31 +++ .../redis-restart/on/t50_r3/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/on/t50_r3/per-second.csv | 31 +++ .../track1/redis-restart/on/t50_r3/run.json | 4 + .../redis-restart/on/t50_r3/samples.csv | 31 +++ .../redis-restart/on/t50_r4/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/on/t50_r4/per-second.csv | 31 +++ .../track1/redis-restart/on/t50_r4/run.json | 4 + .../redis-restart/on/t50_r4/samples.csv | 31 +++ .../redis-restart/on/t50_r5/k6-summary.json | 245 ++++++++++++++++ .../redis-restart/on/t50_r5/per-second.csv | 31 +++ .../track1/redis-restart/on/t50_r5/run.json | 4 + .../redis-restart/on/t50_r5/samples.csv | 31 +++ evidence/track1/stampede-runs.csv | 15 + .../stampede/off/t10_f1_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t10_f1_r1/redis-stats.txt | 2 + .../track1/stampede/off/t10_f1_r1/run.json | 3 + .../stampede/off/t10_f1_r1/sql-calls.csv | 1 + .../stampede/off/t10_f1_r1/top-queries.txt | 3 + .../stampede/off/t10_f1_r2/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t10_f1_r2/redis-stats.txt | 2 + .../track1/stampede/off/t10_f1_r2/run.json | 3 + .../stampede/off/t10_f1_r2/sql-calls.csv | 1 + .../stampede/off/t10_f1_r2/top-queries.txt | 3 + .../stampede/off/t10_f1_r3/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t10_f1_r3/redis-stats.txt | 2 + .../track1/stampede/off/t10_f1_r3/run.json | 3 + .../stampede/off/t10_f1_r3/sql-calls.csv | 1 + .../stampede/off/t10_f1_r3/top-queries.txt | 3 + .../stampede/off/t50_f0_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t50_f0_r1/redis-stats.txt | 2 + .../track1/stampede/off/t50_f0_r1/run.json | 3 + .../stampede/off/t50_f0_r1/sql-calls.csv | 1 + .../stampede/off/t50_f0_r1/top-queries.txt | 2 + .../stampede/off/t50_f1_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t50_f1_r1/redis-stats.txt | 2 + .../track1/stampede/off/t50_f1_r1/run.json | 3 + .../stampede/off/t50_f1_r1/sql-calls.csv | 1 + .../stampede/off/t50_f1_r1/top-queries.txt | 3 + .../stampede/off/t50_f1_r2/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t50_f1_r2/redis-stats.txt | 2 + .../track1/stampede/off/t50_f1_r2/run.json | 3 + .../stampede/off/t50_f1_r2/sql-calls.csv | 1 + .../stampede/off/t50_f1_r2/top-queries.txt | 3 + .../stampede/off/t50_f1_r3/k6-summary.json | 245 ++++++++++++++++ .../stampede/off/t50_f1_r3/redis-stats.txt | 2 + .../track1/stampede/off/t50_f1_r3/run.json | 3 + .../stampede/off/t50_f1_r3/sql-calls.csv | 1 + .../stampede/off/t50_f1_r3/top-queries.txt | 3 + .../stampede/on/t10_f1_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t10_f1_r1/redis-stats.txt | 2 + .../track1/stampede/on/t10_f1_r1/run.json | 3 + .../stampede/on/t10_f1_r1/sql-calls.csv | 1 + .../stampede/on/t10_f1_r1/top-queries.txt | 3 + .../stampede/on/t10_f1_r2/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t10_f1_r2/redis-stats.txt | 2 + .../track1/stampede/on/t10_f1_r2/run.json | 3 + .../stampede/on/t10_f1_r2/sql-calls.csv | 1 + .../stampede/on/t10_f1_r2/top-queries.txt | 3 + .../stampede/on/t10_f1_r3/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t10_f1_r3/redis-stats.txt | 2 + .../track1/stampede/on/t10_f1_r3/run.json | 3 + .../stampede/on/t10_f1_r3/sql-calls.csv | 1 + .../stampede/on/t10_f1_r3/top-queries.txt | 3 + .../stampede/on/t50_f0_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t50_f0_r1/redis-stats.txt | 2 + .../track1/stampede/on/t50_f0_r1/run.json | 3 + .../stampede/on/t50_f0_r1/sql-calls.csv | 1 + .../stampede/on/t50_f0_r1/top-queries.txt | 2 + .../stampede/on/t50_f1_r1/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t50_f1_r1/redis-stats.txt | 2 + .../track1/stampede/on/t50_f1_r1/run.json | 3 + .../stampede/on/t50_f1_r1/sql-calls.csv | 1 + .../stampede/on/t50_f1_r1/top-queries.txt | 3 + .../stampede/on/t50_f1_r2/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t50_f1_r2/redis-stats.txt | 2 + .../track1/stampede/on/t50_f1_r2/run.json | 3 + .../stampede/on/t50_f1_r2/sql-calls.csv | 1 + .../stampede/on/t50_f1_r2/top-queries.txt | 3 + .../stampede/on/t50_f1_r3/k6-summary.json | 245 ++++++++++++++++ .../stampede/on/t50_f1_r3/redis-stats.txt | 2 + .../track1/stampede/on/t50_f1_r3/run.json | 3 + .../stampede/on/t50_f1_r3/sql-calls.csv | 1 + .../stampede/on/t50_f1_r3/top-queries.txt | 3 + evidence/track1/summary.md | 30 ++ scripts/track1/aggregate.py | 167 +++++++++++ scripts/track1/per_second.py | 39 +++ scripts/track1/prepare_sessions.py | 42 +++ scripts/track1/read-after-write.sh | 34 +++ scripts/track1/read_after_write.py | 121 ++++++++ scripts/track1/redis-restart.sh | 89 ++++++ scripts/track1/run-all.sh | 40 +++ scripts/track1/stampede.js | 41 +++ scripts/track1/stampede.sh | 83 ++++++ .../authentication/AuthenticationConfig.kt | 1 + .../SerialAuthenticationConfig.kt | 3 +- .../DefaultAuthenticationService.kt | 110 ++++++-- src/main/resources/application.conf | 3 + .../controllers/chat/ChatControllerTest.kt | 2 +- .../chat/ExposedChatRepositoryTest.kt | 62 +++++ .../SessionLookupSingleFlightTest.kt | 159 +++++++++++ 142 files changed, 8207 insertions(+), 57 deletions(-) create mode 100644 evidence/clean-start.txt create mode 100644 evidence/failures.txt create mode 100644 evidence/gradle-tests.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/storage.txt create mode 100644 evidence/track1/read-after-write/off_redis-down.json create mode 100644 evidence/track1/read-after-write/off_redis-up.json create mode 100644 evidence/track1/read-after-write/on_redis-down.json create mode 100644 evidence/track1/read-after-write/on_redis-up.json create mode 100644 evidence/track1/redis-restart-runs.csv create mode 100644 evidence/track1/redis-restart/off/t50_r1/k6-summary.json create mode 100644 evidence/track1/redis-restart/off/t50_r1/per-second.csv create mode 100644 evidence/track1/redis-restart/off/t50_r1/run.json create mode 100644 evidence/track1/redis-restart/off/t50_r1/samples.csv create mode 100644 evidence/track1/redis-restart/off/t50_r2/k6-summary.json create mode 100644 evidence/track1/redis-restart/off/t50_r2/per-second.csv create mode 100644 evidence/track1/redis-restart/off/t50_r2/run.json create mode 100644 evidence/track1/redis-restart/off/t50_r2/samples.csv create mode 100644 evidence/track1/redis-restart/off/t50_r3/k6-summary.json create mode 100644 evidence/track1/redis-restart/off/t50_r3/per-second.csv create mode 100644 evidence/track1/redis-restart/off/t50_r3/run.json create mode 100644 evidence/track1/redis-restart/off/t50_r3/samples.csv create mode 100644 evidence/track1/redis-restart/off/t50_r4/k6-summary.json create mode 100644 evidence/track1/redis-restart/off/t50_r4/per-second.csv create mode 100644 evidence/track1/redis-restart/off/t50_r4/run.json create mode 100644 evidence/track1/redis-restart/off/t50_r4/samples.csv create mode 100644 evidence/track1/redis-restart/off/t50_r5/k6-summary.json create mode 100644 evidence/track1/redis-restart/off/t50_r5/per-second.csv create mode 100644 evidence/track1/redis-restart/off/t50_r5/run.json create mode 100644 evidence/track1/redis-restart/off/t50_r5/samples.csv create mode 100644 evidence/track1/redis-restart/on/t50_r1/k6-summary.json create mode 100644 evidence/track1/redis-restart/on/t50_r1/per-second.csv create mode 100644 evidence/track1/redis-restart/on/t50_r1/run.json create mode 100644 evidence/track1/redis-restart/on/t50_r1/samples.csv create mode 100644 evidence/track1/redis-restart/on/t50_r2/k6-summary.json create mode 100644 evidence/track1/redis-restart/on/t50_r2/per-second.csv create mode 100644 evidence/track1/redis-restart/on/t50_r2/run.json create mode 100644 evidence/track1/redis-restart/on/t50_r2/samples.csv create mode 100644 evidence/track1/redis-restart/on/t50_r3/k6-summary.json create mode 100644 evidence/track1/redis-restart/on/t50_r3/per-second.csv create mode 100644 evidence/track1/redis-restart/on/t50_r3/run.json create mode 100644 evidence/track1/redis-restart/on/t50_r3/samples.csv create mode 100644 evidence/track1/redis-restart/on/t50_r4/k6-summary.json create mode 100644 evidence/track1/redis-restart/on/t50_r4/per-second.csv create mode 100644 evidence/track1/redis-restart/on/t50_r4/run.json create mode 100644 evidence/track1/redis-restart/on/t50_r4/samples.csv create mode 100644 evidence/track1/redis-restart/on/t50_r5/k6-summary.json create mode 100644 evidence/track1/redis-restart/on/t50_r5/per-second.csv create mode 100644 evidence/track1/redis-restart/on/t50_r5/run.json create mode 100644 evidence/track1/redis-restart/on/t50_r5/samples.csv create mode 100644 evidence/track1/stampede-runs.csv create mode 100644 evidence/track1/stampede/off/t10_f1_r1/k6-summary.json create mode 100644 evidence/track1/stampede/off/t10_f1_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t10_f1_r1/run.json create mode 100644 evidence/track1/stampede/off/t10_f1_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t10_f1_r1/top-queries.txt create mode 100644 evidence/track1/stampede/off/t10_f1_r2/k6-summary.json create mode 100644 evidence/track1/stampede/off/t10_f1_r2/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t10_f1_r2/run.json create mode 100644 evidence/track1/stampede/off/t10_f1_r2/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t10_f1_r2/top-queries.txt create mode 100644 evidence/track1/stampede/off/t10_f1_r3/k6-summary.json create mode 100644 evidence/track1/stampede/off/t10_f1_r3/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t10_f1_r3/run.json create mode 100644 evidence/track1/stampede/off/t10_f1_r3/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t10_f1_r3/top-queries.txt create mode 100644 evidence/track1/stampede/off/t50_f0_r1/k6-summary.json create mode 100644 evidence/track1/stampede/off/t50_f0_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t50_f0_r1/run.json create mode 100644 evidence/track1/stampede/off/t50_f0_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t50_f0_r1/top-queries.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r1/k6-summary.json create mode 100644 evidence/track1/stampede/off/t50_f1_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r1/run.json create mode 100644 evidence/track1/stampede/off/t50_f1_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t50_f1_r1/top-queries.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r2/k6-summary.json create mode 100644 evidence/track1/stampede/off/t50_f1_r2/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r2/run.json create mode 100644 evidence/track1/stampede/off/t50_f1_r2/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t50_f1_r2/top-queries.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r3/k6-summary.json create mode 100644 evidence/track1/stampede/off/t50_f1_r3/redis-stats.txt create mode 100644 evidence/track1/stampede/off/t50_f1_r3/run.json create mode 100644 evidence/track1/stampede/off/t50_f1_r3/sql-calls.csv create mode 100644 evidence/track1/stampede/off/t50_f1_r3/top-queries.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r1/k6-summary.json create mode 100644 evidence/track1/stampede/on/t10_f1_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r1/run.json create mode 100644 evidence/track1/stampede/on/t10_f1_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t10_f1_r1/top-queries.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r2/k6-summary.json create mode 100644 evidence/track1/stampede/on/t10_f1_r2/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r2/run.json create mode 100644 evidence/track1/stampede/on/t10_f1_r2/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t10_f1_r2/top-queries.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r3/k6-summary.json create mode 100644 evidence/track1/stampede/on/t10_f1_r3/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t10_f1_r3/run.json create mode 100644 evidence/track1/stampede/on/t10_f1_r3/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t10_f1_r3/top-queries.txt create mode 100644 evidence/track1/stampede/on/t50_f0_r1/k6-summary.json create mode 100644 evidence/track1/stampede/on/t50_f0_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t50_f0_r1/run.json create mode 100644 evidence/track1/stampede/on/t50_f0_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t50_f0_r1/top-queries.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r1/k6-summary.json create mode 100644 evidence/track1/stampede/on/t50_f1_r1/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r1/run.json create mode 100644 evidence/track1/stampede/on/t50_f1_r1/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t50_f1_r1/top-queries.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r2/k6-summary.json create mode 100644 evidence/track1/stampede/on/t50_f1_r2/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r2/run.json create mode 100644 evidence/track1/stampede/on/t50_f1_r2/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t50_f1_r2/top-queries.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r3/k6-summary.json create mode 100644 evidence/track1/stampede/on/t50_f1_r3/redis-stats.txt create mode 100644 evidence/track1/stampede/on/t50_f1_r3/run.json create mode 100644 evidence/track1/stampede/on/t50_f1_r3/sql-calls.csv create mode 100644 evidence/track1/stampede/on/t50_f1_r3/top-queries.txt create mode 100644 evidence/track1/summary.md create mode 100644 scripts/track1/aggregate.py create mode 100755 scripts/track1/per_second.py create mode 100755 scripts/track1/prepare_sessions.py create mode 100755 scripts/track1/read-after-write.sh create mode 100755 scripts/track1/read_after_write.py create mode 100755 scripts/track1/redis-restart.sh create mode 100755 scripts/track1/run-all.sh create mode 100644 scripts/track1/stampede.js create mode 100755 scripts/track1/stampede.sh create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepositoryTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt diff --git a/REPORT.md b/REPORT.md index e42f2b05..b711f71d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,270 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Автор, группа: Кучерявенко Максим, БВТ2303 +- Целевая оценка; выбранный трек 5, если нужен: 5, трек 1 (согласованность кэша) - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники, библиотеки и помощь ИИ: Kotlin 2.3.20, Ktor 3.3.0 (Netty, Auth, ContentNegotiation, StatusPages, CallLogging, Swagger UI), Koin 4.1 с аннотациями и KSP, Exposed 1.0 (+ exposed-migration для генерации миграций), HikariCP 6.3, Flyway 11.9, PostgreSQL JDBC 42.7, Lettuce 6.7 (клиент Redis), BouncyCastle 1.81 (Argon2id), kotlinx-serialization 1.10. Тесты на kotlin.test + JUnit 5, Ktor `testApplication` и Testcontainers 1.21. ИИ (Claude) использовал как парного разработчика. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker 24+ с Compose v2, Python 3.9+ для публичных тестов, `openssl` для генерации секретов. Для `./gradlew test` дополнительно нужна JDK 21+ и запущенный Docker (тесты поднимают PostgreSQL и Redis через Testcontainers). Я всё запускал на Docker 28.4, Compose 2.39, JDK 24. + +```sh +# один раз: пароли для PostgreSQL и Redis в secrets/ (папка в .gitignore, существующие файлы не перезаписываются) +./scripts/init-secrets.sh + +# сборка образа и запуск api + postgres + redis, --wait ждёт healthcheck всех трёх +docker compose up -d --build --wait + +# миграции Flyway применяются сами при старте API, руками ничего делать не надо +make check +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh + +# свои тесты (нужен Docker) +./gradlew test + +# план запроса истории на 70 000 сообщений, результат в evidence/explain-history.txt +./scripts/explain-history.sh + +# трек 1: вся матрица экспериментов (~25 минут, нужен k6), сводка в evidence/track1/summary.md +./scripts/track1/run-all.sh + +# остановка с сохранением данных +docker compose stop # или docker compose down, volume при этом остаётся + +# намеренное удаление всех учебных данных (volume postgres-data) +docker compose down -v +``` + +Короткий TTL сессии для ручной проверки: `SESSION_TTL_SECONDS=5 docker compose up -d --wait api`, вернуть обратно: `docker compose up -d --wait api`. + +Локально без Docker: `./gradlew run`. Конфиг берётся из `run/development/config/*.conf` (локальный PostgreSQL, база `messenger`), API слушает `127.0.0.1:8081`, чтобы не мешать контейнеру на 8080. Если локального Redis нет, приложение всё равно работает, просто без кэша. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +клиент ──HTTP──▶ api (Ktor, :8080) ──JDBC, пул ≤10──▶ postgres (volume postgres-data) ← источник истины + │ + └──RESP, таймаут 500 мс──▶ redis (без persistence) ← кэш сессий +``` + +Три контейнера в `compose.yaml`: `api` (мой образ), `postgres:17.6-alpine3.22`, `redis:8.4.0-alpine`. Наружу опубликован только API и только на `127.0.0.1`. API стартует после того, как PostgreSQL и Redis прошли healthcheck. Пароли передаются через Docker secrets из `secrets/`, в переменных окружения и в Git их нет. + +**Что перенёс из lab1.** Весь API и контракт, формат ошибок, `X-Request-Id`, курсорную пагинацию со scope внутри курсора, валидацию, Dockerfile (multi-stage, non-root, healthcheck), Swagger UI на `/docs`. + +**Что поменял.** +- Хранилище в памяти заменил на PostgreSQL. Таблицы `users`, `chats`, `chat_members`, `messages`, `sessions`, миграция `src/main/resources/migrations/V1__init.sql`. Первичные ключи UUID, внешние ключи с `ON DELETE CASCADE`, `username` уникальный (`users_username_key`) и проверяется `CHECK` по формату, время везде `timestamptz` с точностью до микросекунд. +- Добавил Koin (модули конфигов, репозиториев и сервисов собираются из аннотаций через KSP) и Exposed. Все запросы идут через DSL Exposed, то есть параметризованы, SQL руками не склеивается. +- Миграции можно генерировать: `./gradlew generateMigration --args="add_something"` сравнивает модели Exposed со схемой локальной базы и пишет `V__add_something.sql`. Модели совпадают с `V1`, генератор на текущем коде отвечает «schema is up to date». +- Аутентификация по контракту. Регистрация с паролем, `POST /api/v1/auth/sessions` по Basic, все остальные бизнес-запросы по Bearer, `X-User-Id` больше ничего не значит. Пароль хешируется Argon2id (m=19456, t=2, p=1, соль 16 байт). bcrypt не подходил, потому что обрезает пароль до 72 байт. Для несуществующего логина хеш всё равно считается, чтобы по времени ответа нельзя было понять, есть ли такой пользователь. +- Токен сессии — 32 случайных байта из `SecureRandom` в base64url. В базе хранится только SHA-256 токена и `expires_at`. TTL задаётся `SESSION_TTL_SECONDS`, logout удаляет строку сессии. +- Basic и Bearer сделаны своими маленькими провайдерами (`plugins/authentication/providers`), потому что встроенные в Ktor пишут `realm` без кавычек и добавляют свой `WWW-Authenticate`, а в контракте точный формат заголовка. + +**Транзакционные границы.** +- Создание чата — одна транзакция: проверка участников, вставка в `chats`, пачка вставок в `chat_members`. Если что-то падает, откатывается всё (это проверяет `ExposedChatRepositoryTest`). +- Регистрация — `INSERT ... ON CONFLICT DO NOTHING` по уникальному `username`. Из двух одновременных запросов вставится один, второй получит 409, без исключения и без гонки «проверил, потом вставил». +- Отправка сообщения — проверка членства и вставка в одной транзакции. +- Каждый HTTP-запрос открывает транзакцию только на свою операцию (`suspendedTransaction` на `Dispatchers.IO`). Обращения к Redis идут вне транзакции, чтобы не держать соединение из пула, пока ждём кэш. + +**Пагинация.** Курсор `(created_at, id)` вместо offset. Запрос страницы — `WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT 51`, под него индекс `messages_chat_id_created_at_id_idx (chat_id, created_at, id)`. Каждая страница читает из индекса ровно 51 строку, сколько бы сообщений ни было до неё. Для списка чатов отдельный индекс `chat_members_user_id_idx`, потому что первичный ключ `chat_members` начинается с `chat_id`. + +**Redis: кэш сессий.** Источник истины — PostgreSQL, Redis только ускоряет проверку Bearer-токена, которая есть в каждом запросе. +- Ключ `session:`, значение — JSON с id сессии, пользователем и сроками. +- Чтение по схеме cache-aside: сначала Redis, если ключа нет — PostgreSQL, потом запись в Redis через `SET ... NX PXAT`. +- Срок жизни ключа — меньшее из `expires_at` сессии и 60 секунд (`sessionCacheTtlSeconds`). Срок сессии к тому же сверяется в коде при каждом запросе, так что просроченная сессия не пройдёт, даже если ключ ещё жив. +- Logout сначала удаляет сессию в PostgreSQL, потом пишет в ключ метку `revoked` до `expires_at`. Заполнение кэша идёт только через `NX`, поэтому запрос, который прочитал сессию из базы до logout и пишет её в кэш после, метку не перетрёт. +- Если Redis недоступен (отказ соединения или таймаут 500 мс), чтение идёт мимо кэша в PostgreSQL, logout тоже работает: он нужен только базе. После неудачного подключения следующая попытка не раньше чем через секунду, а команды без соединения сразу отклоняются, поэтому лежащий Redis не тормозит запросы. +- Промахи по одному токену схлопываются (single-flight): если поиск сессии в базе для этого токена уже идёт, следующие запросы ждут его результат, а не отправляют свой SELECT. Это защита от cache stampede, подробно в треке 1. Включается `SESSION_CACHE_SINGLE_FLIGHT` (по умолчанию `true`), выключатель оставлен для сравнения в эксперименте. +- В лог пишется только смена состояния кэша («unavailable» и «available again»), а не каждый промах. Иначе при лежащем Redis API пишет по предупреждению на запрос. +- Persistence у Redis выключен (`--save ""`, `--appendonly no`). Это осознанно: Redis не единственное хранилище сессий, после его рестарта кэш просто заполняется заново из базы. Лимит памяти 64 МБ, вытеснение `volatile-lru` (у всех ключей есть TTL). + +**Пул и таймауты.** HikariCP: максимум 10 соединений, ожидание свободного соединения 2 с, проверка соединения 1 с, `statement_timeout` 5 с на стороне PostgreSQL. Exposed не повторяет транзакцию (`defaultMaxAttempts = 1`), иначе при лежащей базе запрос висел бы втрое дольше. Redis: подключение и команда по 500 мс. Если база недоступна (SQLSTATE `08*` или `57P*`, таймаут пула), API отвечает 503 `unavailable` в общем формате ошибок. `/health/live` при этом 200, `/health/ready` делает `SELECT 1` и отвечает 503. + +**Переменные окружения.** `.env.example` описывает роли, реальные имена у меня такие: + +| В `.env.example` | У меня | Где задаётся | +| --- | --- | --- | +| `APP_HOST`, `APP_PORT` | так же | `compose.yaml`, по умолчанию `0.0.0.0:8080` | +| `SESSION_TTL_SECONDS` | так же | `compose.yaml`, берётся из окружения или `.env`, по умолчанию 3600 | +| `DATABASE_URL_FILE` | `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER` + `DB_PASSWORD_FILE` | `compose.yaml`, пароль — Docker secret `db_password` | +| `SESSION_STORE`, `CACHE_URL_FILE` | `REDIS_HOST`, `REDIS_PORT` + `REDIS_PASSWORD_FILE` | `compose.yaml`, пароль — Docker secret `redis_password`. Сессии всегда в PostgreSQL, Redis всегда кэш, переключателя нет | +| — | `SESSION_CACHE_SINGLE_FLIGHT` | `compose.yaml`, по умолчанию `true`; `false` только для сравнения в треке 1 | +| `APP_ENV` | не используется | — | + +`.env` для запуска не обязателен, все значения по умолчанию есть в `compose.yaml`. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `make check`, `make test` на только что поднятом стенде | `PASS: offline skeleton structure...`, `PASS: lab2 public API scenario` | evidence/smoke.txt | +| Миграции с нуля | `docker compose down -v`, затем `up -d --build --wait` | в `flyway_schema_history` версия 1 `init`, success = t, созданы все 5 таблиц | evidence/clean-start.txt | +| Повторный запуск миграций без дублей | рестарт API на той же базе; `DatabaseMigrationTest` | в логе `Schema "public" is up to date. No migration necessary`; тест прогоняет миграции второй раз и проверяет, что данные на месте | evidence/persistence.txt, evidence/gradle-tests.txt | +| Ключи, уникальность username | `\d sessions` и т.д.; `UserControllerTest` | PK, FK `ON DELETE CASCADE`, `users_username_key`, повторный username — 409 | src/main/resources/migrations/V1__init.sql, evidence/storage.txt | +| Данные и сессии переживают рестарт API и хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS. У всех трёх контейнеров новый `StartedAt` (api, postgres и redis перезапущены), volume `postgres-data` тот же | evidence/persistence.txt | +| Атомарное создание чата | `ExposedChatRepositoryTest`: второй участник не существует, вставка участников падает на FK | исключение с SQLSTATE 23503, строки в `chats` и `chat_members` не остались | src/test/.../repositories/chat/ExposedChatRepositoryTest.kt | +| Пароли через KDF | смотрел `users.password_hash` | все хеши `$argon2id$v=19$m=19456,t=2,p=1$...`; тест: пароли, отличающиеся после 72-го байта, различаются | evidence/storage.txt, DefaultHashingServiceTest | +| Basic только на создании сессии, Bearer на остальном | curl на живом стенде; `UserControllerTest`, `AuthenticationControllerTest` | Basic на `/users/me` — 401, Bearer на `POST /auth/sessions` — 401, без токена — 401 с `WWW-Authenticate: Bearer realm="messenger"` | evidence/failures.txt | +| `X-User-Id` не даёт доступ | curl с одним `X-User-Id`; тесты `X-User-Id alone gives no access`, `X-User-Id does not override bearer identity` | 401; при Bearer + чужой `X-User-Id` отвечает владелец токена | evidence/failures.txt | +| Opaque-токен ≥ 256 бит, в базе только хеш | код `DefaultAuthenticationService`, `\d sessions` | 32 байта из SecureRandom, `token_hash` длиной 64 (hex SHA-256), самого токена в базе нет | evidence/storage.txt | +| Logout | curl; `logout revokes only the current token` | 204, тот же токен потом 401, вторая сессия того же пользователя работает | evidence/failures.txt | +| Expiry при коротком TTL | `SESSION_TTL_SECONDS=5`, ждал 6 с; тест `session expires after SESSION_TTL_SECONDS` (TTL 2 с) | сразу после входа 200, через 6 с 401 | evidence/failures.txt | +| Неверный пароль | curl; тест `wrong password and unknown user get the same 401` | 401, ответ одинаковый для неверного пароля и несуществующего пользователя | evidence/failures.txt | +| Secrets и volumes не в Git | `git check-ignore`, `git ls-files secrets` | `secrets/` в `.gitignore`, отслеживаемых файлов 0, данные только в docker volume | evidence/storage.txt | +| Redis реально используется | curl + `redis-cli` на живом стенде; `SessionCacheTest` | после первого запроса в Redis появляется `session:` с TTL 60 с; после logout значение `revoked` с TTL ≈ 3600 с | evidence/failures.txt | +| Источник истины, expiry и инвалидация кэша | `SessionCacheTest`, `RedisSessionCacheRepositoryTest` | после `FLUSHALL` живая сессия работает, отозванная остаётся отозванной; запоздавшее заполнение кэша не перетирает метку `revoked` | evidence/gradle-tests.txt | +| Параметризованные запросы, ограниченный пул, таймауты | код `plugins/Database.kt`, `RedisConnection.kt` | Exposed DSL; пул ≤ 10, ожидание 2 с, `statement_timeout` 5 с; Redis 500 мс | src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt | +| Гонка регистрации одного username | `concurrent registrations of one username create exactly one user`: 10 параллельных запросов | ровно один 201 и девять 409 | evidence/gradle-tests.txt | +| Rollback составной операции | `chat row is rolled back when inserting members fails` | см. строку про атомарность выше | evidence/gradle-tests.txt | +| Индекс истории и EXPLAIN на ≥ 10 000 сообщений | `./scripts/explain-history.sh` | 70 000 сообщений, глубокая страница по курсору: Index Scan, 4 буфера, 0,03 мс. Без индекса: Seq Scan, 914 буферов. Разбор ниже | evidence/explain-history.txt | +| Недоступность Redis | `docker compose stop redis`; `DependencyFailureTest` (отказ соединения и `docker pause`) | запросы с токеном 200, вход 201, logout 204 и токен сразу 401, анонимный запрос 401; при зависшем Redis запрос дольше максимум на один таймаут | evidence/failures.txt, evidence/gradle-tests.txt | +| Недоступность БД | `docker compose stop postgres`; `DependencyFailureTest` | `/health/live` 200, `/health/ready` 503, запросы с токеном и вход — 503 `unavailable` примерно за 2 с, без токена и с `X-User-Id` — 401. После старта базы тот же токен снова 200 | evidence/failures.txt | +| Свои автотесты | `./gradlew test` | 56 тестов, все проходят | evidence/gradle-tests.txt | +| Трек 1: cache stampede на конкурентном сценарии | `./scripts/track1/stampede.sh` с `VARIANT=off`, 200 VU, `FLUSHALL` раз в секунду | на каждую сессию за один сброс кэша в базу уходит 3,1 SELECT при 50 сессиях и 10,5 при 10 сессиях; запросов к `sessions` 4 651 и 3 138 за 30 с | evidence/track1/summary.md, evidence/track1/stampede/off/ | +| Трек 1: защита и измерение до/после | то же с `VARIANT=on` (single-flight) | 0,97 SELECT на сессию за сброс в обоих случаях: запросов к `sessions` в 3,2 и 10,8 раза меньше. RPS и p50/p95/p99 в пределах шума | evidence/track1/summary.md, evidence/track1/stampede-runs.csv | +| Трек 1: read-after-write из контракта | `./scripts/track1/read-after-write.sh`: 300 итераций, 16 параллельных читателей, logout посреди первого заполнения кэша; с защитой и без, Redis работает и остановлен | 1 200 итераций, 1,53 млн запросов, начатых после ответа 204 на logout: ни одного 200. Первый запрос после входа всегда 200. Через секунду ни один отозванный токен не ожил | evidence/track1/read-after-write/ | +| Трек 1: восстановление после рестарта кэша | `./scripts/track1/redis-restart.sh`: `docker compose restart redis` на 10-й секунде замера под 200 VU, 5 повторов на вариант | 0 ответов не 200 за 10 рестартов, кэш недоступен ~0,7 с по логу API, p99 в секунду рестарта ~71–76 мс против ~36 мс до. Первая версия кода на этом сценарии отдавала один 500 на рестарт, разбор ниже | evidence/track1/redis-restart/ | +| Трек 1: тесты single-flight | `SessionLookupSingleFlightTest` | 50 одновременных промахов: 50 запросов в базу без защиты и 1 с защитой; запрос, пришедший после logout, не присоединяется к поиску, начатому до него | evidence/gradle-tests.txt | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### План запроса истории + +`scripts/explain-history.sh` в одной транзакции заливает в стенд 70 000 сообщений: один большой чат на 20 000 и 50 соседних чатов по 1 000, потом делает `ANALYZE`, снимает `EXPLAIN (ANALYZE, BUFFERS)` и откатывает транзакцию, так что реальные данные не меняются. Соседние чаты нужны, чтобы планировщику было что пропускать, иначе таблица состояла бы из одного чата. Запросы те же, что строит Exposed в `ExposedMessageRepository.findPageByChatId`. Стенд — ноутбук Apple M4, 10 ядер, 16 ГБ, PostgreSQL 17.6 в Docker, данные целиком в shared buffers. + +| Запрос | План | Buffers | Время выполнения | +| --- | --- | ---: | ---: | +| Первая страница, `LIMIT 51` | Index Scan по `messages_chat_id_created_at_id_idx`, условие `chat_id` | 4 | 0,02 мс | +| Страница после 15 000-го сообщения, курсор `(created_at, id) > (?, ?)` | тот же Index Scan, условие на курсор тоже внутри индекса | 4 | 0,03 мс | +| Та же страница через `OFFSET 15000` (для сравнения, API так не делает) | Index Scan, прочитано 15 051 строка, отдано 51 | 296 | 1,0 мс | +| Курсор, но индексы запрещены (`enable_indexscan = off` и т.д.) | Seq Scan всей таблицы, отброшено 65 003 строки, затем top-N sort | 914 | 2,1 мс | + +Главное здесь не миллисекунды (на 70 000 строк всё и так быстро), а то, как растёт работа. С курсором страница всегда стоит 4 буфера, хоть первая, хоть пятнадцатитысячная. С offset стоимость растёт с номером страницы, без индекса — с размером всей таблицы, включая чужие чаты. Сортировки в плане с индексом нет: строки идут из индекса уже в нужном порядке, и `LIMIT` останавливает чтение на 51-й. + +Индекс именно `(chat_id, created_at, id)`: первым столбцом равенство по чату, дальше ровно порядок сортировки, и `id` в конце нужен, чтобы курсор был однозначным, когда у двух сообщений совпадает `created_at`. + +### Отказы + +Всё проверял на живом стенде, вывод в `evidence/failures.txt` и `evidence/persistence.txt`. Те же сценарии есть в автотестах (`DependencyFailureTest`). | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `scripts/restart.sh`: stop api, redis, postgres, затем up --wait | данные и сессии на месте, тот же токен работает | `make test-persistence` PASS, у всех трёх контейнеров новый `StartedAt`, Redis поднялся пустым и заполнился заново | API стартовал через 5 с после PostgreSQL и Redis (ждал их healthcheck), весь hook занял несколько секунд; потерь нет | +| `docker compose stop redis` | работаем без кэша, анонимов не пускаем | `/me` с токеном 200 за 7 мс, вход 201, logout 204 и токен сразу 401, без токена 401, `/health/ready` 200. В логе предупреждение `Session cache is unavailable` | после `start redis` кэш используется снова сам, без рестарта API; потерь нет | +| Redis завис (`docker pause` в тесте) | запрос замедляется не больше чем на таймаут команды | `/me` 200 менее чем за 2 с (таймауты 500 мс на чтение и на запись в кэш), logout 204; после `unpause` отозванная сессия не вернулась, кэш снова работает | сразу после `unpause`; потерь нет | +| `docker compose stop postgres` | ограниченная ошибка, анонимов не пускаем | `/health/live` 200, `/health/ready` 503 сразу, `/me` с токеном и вход 503 `unavailable` за 2,0 с (таймаут пула), без токена и с `X-User-Id` 401, неизвестный токен 503 | после `start postgres` тот же токен 200 без рестарта API; подтверждённые данные не теряются, неподтверждённые запросы клиент должен повторить | +| `SESSION_TTL_SECONDS=5` | сессия истекает | 200 сразу после входа, 401 через 6 с | — | + +### Трек 1. Согласованность кэша + +Кэш у меня один — сессии в Redis, и через него проходит каждый запрос с Bearer-токеном. Поэтому смотрел на две вещи: что происходит с базой, когда ключи пропадают все разом (cache stampede), и не ломает ли кэш гарантии контракта про logout. + +**Гипотеза.** Когда кэш сессий сбрасывается (истёк TTL, `FLUSHALL`, рестарт Redis), все запросы, которые в этот момент летят с одним токеном, одновременно промахиваются и каждый идёт в PostgreSQL за одной и той же строкой `sessions`. Ожидал, что лишних SELECT будет примерно столько, сколько параллельных запросов на один токен, и что single-flight (один поиск на токен, остальные ждут его результат) срежет их до одного на сессию. Про latency заранее не был уверен: поиск сессии — это запрос по уникальному индексу, он дешёвый. + +#### Как мерил + +Стенд — тот же ноутбук: Apple M4 (10 ядер), 16 ГБ, macOS 27. Docker Desktop, виртуалке выделено 10 CPU и 8 ГБ, лимитов на контейнеры нет. Образы и конфиг те же, что в `compose.yaml`: пул PostgreSQL 10 соединений, таймаут Redis 500 мс, TTL копии сессии в кэше 60 с. k6 2.3 на той же машине. Варианты «до» и «после» — это один и тот же образ, разница только в `SESSION_CACHE_SINGLE_FLIGHT=false/true`, и перед каждым прогоном API пересоздаётся (`--force-recreate`), чтобы не тянуть состояние JVM из прошлого прогона. + +Что считал: +- SQL — через `pg_stat_statements` (включил в `compose.yaml`). Счётчики сбрасываются на границе прогрева и замера, потом берётся число вызовов SELECT по `sessions` и всех запросов вообще. +- Промахи и попадания Redis — `INFO stats` (`keyspace_misses`, `keyspace_hits`), тоже со сбросом перед замером. +- Latency и RPS — k6, только фаза замера. Прогрев и замер — один сценарий k6, иначе на старте замера k6 заново открывает 200 соединений через проброс порта Docker Desktop и часть из них рвётся (это то же, что я видел в lab1). + +Все прогоны запускает `scripts/track1/run-all.sh`. Повторы идут по кругу: сначала все комбинации по разу, потом второй круг, потом третий. Сводка — `evidence/track1/summary.md`, сырые данные по каждому прогону — в `evidence/track1/<эксперимент>/<вариант>/...`. Токены живут только во временном файле с правами 600, который удаляется после прогона. + +#### Эксперимент 1. Stampede при массовом сбросе кэша + +`scripts/track1/stampede.sh`. Перед прогоном создаётся N пользователей с одной сессией у каждого. Дальше 200 VU без пауз дёргают `GET /api/v1/users/me`, каждый VU всегда со своим токеном из N, то есть на одну сессию одновременно приходится 200/N запросов. 5 с прогрев, 30 с замер. Во время замера внутри контейнера Redis раз в секунду выполняется `FLUSHALL`, это имитирует одновременное истечение всех ключей или рестарт кэша. N = 50 (по 4 запроса на сессию, как у клиента, который параллельно грузит несколько экранов) и N = 10 (по 20, например общий служебный токен). Плюс контрольный прогон без сбросов. По 3 повтора, медиана, в скобках минимум и максимум: + +| Сессий | Single-flight | Запросов к `sessions` за 30 с | На сессию за один сброс | Промахов Redis | Всего SQL | RPS | p50 / p95 / p99, мс | max, мс | +| ---: | --- | ---: | ---: | ---: | ---: | ---: | --- | ---: | +| 50 | нет | 4 651 (4 622–4 689) | 3,10 | 4 651 | 492 085 | 16 270 | 11,2 / 22,9 / 31,6 | 86 | +| 50 | да | 1 451 (1 450–1 451) | 0,97 | 4 653 | 483 729 | 16 106 | 11,5 / 22,6 / 29,9 | 84 | +| 10 | нет | 3 138 (2 893–3 500) | 10,46 | 3 138 | 474 008 | 15 719 | 11,7 / 23,4 / 32,0 | 84 | +| 10 | да | 291 (291–292) | 0,97 | 4 037 | 470 144 | 15 719 | 11,8 / 23,1 / 31,6 | 87 | +| 50, без сбросов | нет / да | 0 / 0 | — | 0 / 0 | 477 952 / 486 664 | 15 966 / 16 251 | 11,5 / 23,3 / 32,1 и 11,4 / 22,4 / 30,6 | 86 / 88 | + +Ошибок не было ни в одном прогоне. + +Без защиты stampede виден напрямую: на каждый сброс в базу уходит ~3 SELECT на сессию при 4 параллельных запросах и ~10,5 при 20. Это почти ровно число запросов, которые в момент сброса были в полёте с этим токеном. Промахов Redis ровно столько же, сколько SELECT: каждый промах — свой запрос в базу. + +С single-flight на сессию за сброс уходит 0,97 SELECT в обоих случаях, разброс между повторами меньше 0,1 %. Не ровно 1, потому что делю на 30 сбросов, а последний `FLUSHALL` пришёлся на самый конец замера, когда k6 уже остановился: фактически сработало 29 сбросов, и 29 × 50 = 1 450, 29 × 10 = 290 — ровно по одному SELECT на сессию за сброс (плюс один запрос на границе замера). Промахов Redis при этом даже больше, чем без защиты (4 037 против 3 138 при 10 сессиях), но это ожидаемо: промахиваются все, кто пришёл до записи в кэш, просто в базу идёт только один из них. Итого запросов к `sessions` меньше в 3,2 раза при 50 сессиях и в 10,8 раза при 10. + +А вот на latency и RPS защита не повлияла: все различия в пределах разброса между повторами, и контрольный прогон без сбросов кэша даёт те же цифры. Причина видна в `top-queries.txt`: за 30 секунд 4 689 поисков сессии заняли в PostgreSQL 77 мс суммарно (~0,02 мс на запрос), а 487 009 поисков пользователя для ответа `/me` — 7 930 мс. Stampede на сессиях — это меньше 1 % работы базы в этом сценарии, и пул на 10 соединений он не забивает. То есть гипотеза про число запросов подтвердилась полностью, а ускорения ответа нет, и я его не заявляю. Выигрыш от защиты вырастет там, где сброс кэша совпадает с тяжёлой базой: много сессий на одном токене, медленный диск, пул, уже занятый другими запросами. Это я не мерил. + +#### Эксперимент 2. Рестарт Redis под нагрузкой + +`scripts/track1/redis-restart.sh`. Та же нагрузка (200 VU, 50 сессий), но вместо `FLUSHALL` на 10-й секунде замера `docker compose restart redis`. Раз в секунду скрипт снимает счётчик поисков сессии из `pg_stat_statements` и попадания Redis, k6 пишет каждый запрос в CSV, из которого потом считаются RPS и задержки по секундам (`per-second.csv`). Время недоступности кэша — по двум строкам лога API: «Session cache is unavailable» и «available again». 5 повторов на вариант: + +| Single-flight | `restart redis`, с | Кэш недоступен по логу API, с | Запросов к `sessions` за прогон | p99 до рестарта, мс | p99 в секунду рестарта, мс | max в секунду рестарта, мс | Не 200 | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| нет | 0,52 (0,48–0,59) | 0,71 (0,65–0,83) | 5 625 (4 700–6 284) | 36 | 76 (68–163) | 133 (112–225) | 0 | +| да | 0,51 (0,47–0,57) | 0,73 (0,70–0,75) | 3 490 (3 106–3 805) | 37 | 71 (70–89) | 138 (129–153) | 0 | + +Пример одного прогона (повтор 3, без single-flight), секунды вокруг рестарта: + +| Секунда замера | Запросов | p50, мс | p99, мс | max, мс | +| ---: | ---: | ---: | ---: | ---: | +| 9 | 13 687 | 13,2 | 38,3 | 58 | +| 10 (рестарт в 10,08) | 9 334 | 17,7 | 77,4 | 162 | +| 11 | 12 568 | 14,1 | 40,1 | 74 | +| 12 | 13 968 | 13,0 | 34,8 | 53 | + +Пока Redis лежит, каждый запрос идёт в PostgreSQL, ошибок нет, только хвост задержек в эту секунду вырастает примерно вдвое. После старта Redis Lettuce переподключается сам, без рестарта API, и уже в следующую секунду p99 возвращается к обычному. Кэш при этом пустой (persistence выключен), заполняется заново из базы при первых запросах. Single-flight во время такого отказа помогает меньше, чем при `FLUSHALL` (в 1,6 раза меньше SELECT, а не в 3): пока Redis недоступен, промахи идут непрерывным потоком, а не одной пачкой, и запросы с одним токеном реже совпадают по времени с уже идущим поиском. + +**Что нашёл этим экспериментом.** В первом прогоне матрицы (до исправления) в 4 рестартах из 6 ровно один запрос получал 500. В логе API было `Unhandled error: java.net.SocketException: Connection reset`. Lettuce на команду, которая уже ушла в сокет в момент закрытия соединения, отдаёт не `RedisException`, а голый `IOException`. Мой обработчик ловил только `RedisException`, и этот запрос проваливался в общий 500. Исправил: `IOException` из кэша теперь тоже значит «кэш недоступен», запрос идёт в базу. После исправления матрица перезапущена целиком, и за 10 рестартов не было ни одного ответа не 200. Тесты из уровня 4 (`docker pause`, закрытый порт) этот случай не ловили, потому что в них соединение не рвётся посреди команды. + +Ещё одна мелочь из того же эксперимента: до этого API писал предупреждение на каждый запрос, который не смог сходить в Redis, — за 0,5 с рестарта это 5 397 строк. Теперь логируется только смена состояния, по этим двум строкам и меряется время недоступности. Иногда в момент переподключения бывает лишний «скачок» unavailable → available за 10 мс (видно в `on/t50_r3/cache-availability.log`): команда, отправленная в старое соединение, падает уже после того, как новое установилось. + +#### Эксперимент 3. Read-after-write для входа и выхода + +В контракте две гарантии, которые кэш может сломать: после 201 на вход токен сразу работает, а после 204 на `DELETE /auth/sessions/current` тот же токен должен получать 401. Самое опасное место — гонка заполнения кэша с logout: запрос прочитал сессию из базы до удаления, а в Redis записал уже после. Без `NX` и метки `revoked` такая копия жила бы до 60 секунд. + +`scripts/track1/read-after-write.sh`. 300 итераций, в каждой: +1. вход и сразу `GET /me` — должен быть 200 (кэш не хранит «токена нет», так что новый токен виден сразу); +2. второй вход, чтобы начать с холодного ключа; +3. 16 потоков без пауз читают `/me` с этим токеном, и через случайные 0–20 мс выполняется logout — то есть ровно в момент, когда первые запросы заполняют кэш; +4. потоки читают ещё 100 мс; нарушением считается любой 200 на запрос, начатый после того, как клиент получил 204; +5. в конце, через секунду после последнего logout, каждый отозванный токен проверяется ещё раз. + +Четыре комбинации: с защитой от stampede и без, Redis работает и остановлен. + +| Single-flight | Redis | Первый запрос после входа не 200 | Запросов до ответа logout | Запросов после ответа logout | Из них 200 | Токен жив через 1 с | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| нет | работает | 0 из 300 | 42 545 | 396 511 | 0 | 0 из 300 | +| да | работает | 0 из 300 | 42 692 | 405 818 | 0 | 0 из 300 | +| нет | остановлен | 0 из 300 | 43 034 | 362 801 | 0 | 0 из 300 | +| да | остановлен | 0 из 300 | 42 973 | 361 654 | 0 | 0 из 300 | + +Ни одного нарушения на 1,53 млн запросов после logout. Других кодов, кроме 200 и 401, не было. + +Здесь честно скажу про силу доказательства: этот эксперимент показывает, что нарушения не случаются на практике, но он не доказывает, что гонка в нём действительно возникала (окно между чтением из базы и записью в кэш — доли миллисекунды). Само опасное чередование проверено детерминированно в тестах: `late cache fill cannot overwrite a tombstone` (метка, потом запоздавшая запись — остаётся метка) и `request arriving after logout does not join a lookup started before it` (single-flight не раздаёт результат поиска, начатого до logout, запросам после него). Отдельно single-flight не должен был ухудшить read-after-write: результат поиска отдаётся ведомым сразу после SELECT, а logout выкидывает незавершённый поиск своего токена из таблицы, поэтому запрос, пришедший после 204, всегда делает свой поиск. + +#### Восстановление после рестарта кэша + +Redis у меня без persistence, поэтому после рестарта он пустой, и восстановление — это просто повторное заполнение из PostgreSQL: +- `make test-persistence ACTION_SCRIPT=scripts/restart.sh` перезапускает api, postgres и redis — тот же токен читает те же данные (уровень 3); +- `SessionCacheTest.emptied cache falls back to PostgreSQL`: после `FLUSHALL` живая сессия работает и снова попадает в кэш, а отозванная остаётся отозванной (её нет в базе); +- эксперимент 2: под нагрузкой 200 VU рестарт Redis проходит без ошибок, через ~0,7 с API снова пользуется кэшем. + +Единственное, что теряется при рестарте Redis, — метки `revoked`. Это не страшно, потому что logout сначала удаляет сессию из PostgreSQL, и без метки поиск всё равно вернёт «нет сессии». + +#### Что может искажать результаты + +- k6, API, PostgreSQL и Redis на одном ноутбуке и делят CPU. Повторы одной комбинации отличаются по RPS на 1–5 %. +- `FLUSHALL` раз в секунду — это искусственно частый сброс. В обычной работе ключи истекают по одному (TTL 60 с от первого промаха), и stampede по сессии случается раз в минуту, а не раз в секунду. +- Сценарий — только `GET /me`. В нём на запрос приходится ровно один дополнительный SELECT пользователя, на других endpoint пропорции другие. +- Single-flight работает внутри одного процесса API. Сейчас процесс один, а с несколькими репликами (lab3) каждая будет делать свой поиск, то есть до одного SELECT на сессию на реплику. Для общего на все реплики нужна блокировка в Redis, но при недоступном Redis она бы не работала, а в базу всё равно ходить надо. +- Время недоступности кэша по логу API — это от первой неудачной команды до первой удачной. Оно немного больше, чем `docker compose restart` (0,7 против 0,5 с), потому что включает переподключение Lettuce. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Если logout пришёлся на время, когда Redis лежал, метка `revoked` не записывается. Тогда копия сессии, закэшированная до сбоя, после возвращения Redis может прожить ещё до 60 секунд. Поэтому TTL кэша и ограничен 60 секундами, а не сроком сессии. Пока Redis недоступен, такой проблемы нет: все чтения идут в базу. +- Неизвестный токен при лежащей базе получает 503, а не 401. Проверить его без базы нельзя, а пустить нельзя, так что это осознанно. +- PostgreSQL один, без реплик и бэкапов. Если пропадёт volume, пропадут данные. Durability — стандартная для PostgreSQL (`fsync`, `synchronous_commit` по умолчанию включены): после ответа 201 запись уже в WAL на диске. +- Просроченные сессии из таблицы `sessions` не удаляются, они только перестают проходить проверку. Нужна периодическая чистка, сейчас её нет. +- Список чатов пагинируется по `(chats.created_at, chats.id)` через join с `chat_members`. Для пользователя с огромным числом чатов это будет сортировка всех его чатов. Для учебных объёмов нормально, EXPLAIN для этого запроса я не снимал. +- Защита от stampede в треке 1 уменьшила число запросов к `sessions` в 3–11 раз, но ускорения ответа в моём сценарии не дала, и я его не заявляю. Где она начнёт влиять на latency (тяжёлая база, занятый пул, много запросов на один токен), не проверял. +- Single-flight работает в пределах одного процесса API. С несколькими репликами каждая сделает свой поиск. Общая блокировка в Redis тут плохо подходит: она нужна как раз тогда, когда Redis может быть недоступен. +- Swarm не использую, только Compose. Сеть между контейнерами без TLS, это тема следующих лабораторных. diff --git a/compose.yaml b/compose.yaml index 0a80034a..0ce5e95e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -5,6 +5,8 @@ services: postgres: image: postgres:17.6-alpine3.22 container_name: mtusi-lab2-postgres + # pg_stat_statements counts executed queries, track 1 uses it to measure the cache stampede. + command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "pg_stat_statements.track=all"] environment: POSTGRES_DB: messenger POSTGRES_USER: messenger @@ -67,6 +69,7 @@ services: REDIS_PORT: "6379" REDIS_PASSWORD_FILE: /run/secrets/redis_password SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_CACHE_SINGLE_FLIGHT: ${SESSION_CACHE_SINGLE_FLIGHT:-true} secrets: - db_password - redis_password diff --git a/evidence/clean-start.txt b/evidence/clean-start.txt new file mode 100644 index 00000000..5639738a --- /dev/null +++ b/evidence/clean-start.txt @@ -0,0 +1,34 @@ +# Clean start: docker compose down -v, then up --build --wait (2026-10-08T21:30:03Z) + Volume mtusi-messenger-lab2_postgres-data Removed + Network mtusi-messenger-lab2_default Removed + Container mtusi-lab2-redis Healthy + Container mtusi-lab2-postgres Healthy + Container mtusi-lab2-api Started + Container mtusi-lab2-redis Healthy + Container mtusi-lab2-postgres Healthy + Container mtusi-lab2-api Healthy +mtusi-lab2-api Up 5 seconds (healthy) +mtusi-lab2-postgres Up 11 seconds (healthy) +mtusi-lab2-redis Up 11 seconds (healthy) +/mtusi-lab2-api started 2026-10-08T21:30:14.569499088Z +/mtusi-lab2-postgres started 2026-10-08T21:30:08.908684627Z +/mtusi-lab2-redis started 2026-10-08T21:30:08.908745585Z + +# Flyway history after first start + version | description | success +---------+-------------+--------- + 1 | init | t +(1 row) + +# Tables + List of relations + Schema | Name | Type | Owner +--------+-----------------------+-------+----------- + public | chat_members | table | messenger + public | chats | table | messenger + public | flyway_schema_history | table | messenger + public | messages | table | messenger + public | sessions | table | messenger + public | users | table | messenger +(6 rows) + diff --git a/evidence/explain-history.txt b/evidence/explain-history.txt index 55f0e6dd..0625f981 100644 --- a/evidence/explain-history.txt +++ b/evidence/explain-history.txt @@ -2,65 +2,65 @@ == Data volume total_messages | target_chat_messages ----------------+---------------------- - 70006 | 20000 + 70003 | 20000 (1 row) == 1. First page: WHERE chat_id = ? ORDER BY created_at, id LIMIT 51 QUERY PLAN ------------------------------------------------------------------------------------------------------------------ - Limit (actual time=0.005..0.022 rows=51 loops=1) + Limit (actual time=0.007..0.012 rows=51 loops=1) Buffers: shared hit=4 - -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.005..0.020 rows=51 loops=1) + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.006..0.009 rows=51 loops=1) Index Cond: (chat_id = '00000000-0000-0000-0001-000000000000'::uuid) Buffers: shared hit=4 Planning: Buffers: shared hit=6 - Planning Time: 0.045 ms - Execution Time: 0.029 ms + Planning Time: 0.036 ms + Execution Time: 0.022 ms (9 rows) == 2. Deep page after the 15 000th message: (created_at, id) > (?, ?) QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - Limit (actual time=0.005..0.010 rows=51 loops=1) + Limit (actual time=0.006..0.010 rows=51 loops=1) Buffers: shared hit=4 - -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.005..0.007 rows=51 loops=1) - Index Cond: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '5ec4eb0a-04cf-487e-9ec0-16b7367e29df'::uuid))) + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.005..0.008 rows=51 loops=1) + Index Cond: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, 'd5bb7c5e-b8e9-43e6-864a-c12a22b3e27d'::uuid))) Buffers: shared hit=4 - Planning Time: 0.027 ms - Execution Time: 0.025 ms + Planning Time: 0.023 ms + Execution Time: 0.029 ms (7 rows) == 3. Same deep page with OFFSET instead of a cursor (for comparison, not used by the API) QUERY PLAN --------------------------------------------------------------------------------------------------------------------- - Limit (actual time=1.076..1.080 rows=51 loops=1) + Limit (actual time=1.024..1.028 rows=51 loops=1) Buffers: shared hit=296 - -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.800 rows=15051 loops=1) + -> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.768 rows=15051 loops=1) Index Cond: (chat_id = '00000000-0000-0000-0001-000000000000'::uuid) Buffers: shared hit=296 - Planning Time: 0.025 ms - Execution Time: 1.093 ms + Planning Time: 0.021 ms + Execution Time: 1.036 ms (7 rows) == 4. Deep page without messages_chat_id_created_at_id_idx (index scans disabled for this query only) QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Limit (actual time=2.151..2.154 rows=51 loops=1) + Limit (actual time=2.097..2.101 rows=51 loops=1) Buffers: shared hit=914 - -> Sort (actual time=2.151..2.152 rows=51 loops=1) + -> Sort (actual time=2.096..2.098 rows=51 loops=1) Sort Key: created_at, id Sort Method: top-N heapsort Memory: 31kB Buffers: shared hit=914 - -> Seq Scan on messages (actual time=0.420..1.969 rows=5000 loops=1) - Filter: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '5ec4eb0a-04cf-487e-9ec0-16b7367e29df'::uuid))) - Rows Removed by Filter: 65006 + -> Seq Scan on messages (actual time=0.423..1.891 rows=5000 loops=1) + Filter: ((chat_id = '00000000-0000-0000-0001-000000000000'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, 'd5bb7c5e-b8e9-43e6-864a-c12a22b3e27d'::uuid))) + Rows Removed by Filter: 65003 Buffers: shared hit=914 - Planning Time: 0.021 ms - Execution Time: 2.162 ms + Planning Time: 0.020 ms + Execution Time: 2.108 ms (12 rows) diff --git a/evidence/failures.txt b/evidence/failures.txt new file mode 100644 index 00000000..a6e988ea --- /dev/null +++ b/evidence/failures.txt @@ -0,0 +1,38 @@ +# Auth checks on the live stack (tokens are not printed) +wrong password, POST /auth/sessions: 401 in 0.030955s +Basic on GET /users/me: 401 in 0.002498s +X-User-Id only, GET /users/me: 401 in 0.002170s +Bearer, GET /users/me: 200 in 0.004881s +redis GET session:: {"id":"5870165f-4435-45c8-a765-b607aa414470","userId":"df0e4... +redis TTL of cached copy: 60s (session itself lives 3600s) +DELETE /auth/sessions/current: 204 in 0.008615s +redis value after logout: revoked, ttl 3599s +same token after logout: 401 in 0.003347s + +# Short TTL: SESSION_TTL_SECONDS=5 docker compose up -d --wait api +right after login: 200 in 0.101714s +after 6 s: 401 in 0.020896s +(api recreated back with the default 3600 s) + +# Redis is stopped: docker compose stop redis +GET /health/ready: 200 in 0.005506s +GET /users/me with token: 200 in 0.006916s +GET /users/me anonymous: 401 in 0.004147s +POST /auth/sessions: 201 in 0.030189s +DELETE /auth/sessions/current: 204 in 0.006507s +same token after logout: 401 in 0.003473s +after docker compose start redis, same token: 401 in 0.014775s +2026-10-08T21:31:27.380Z WARN [eventLoopGroupProxy-6-6] c.m.m.m.i.s.a.DefaultAuthenticationService - Session cache is unavailable, reading from the database: Currently not connected. Commands are rejected. +2026-10-08T21:31:27.382Z WARN [DefaultDispatcher-worker-2] c.m.m.m.i.s.a.DefaultAuthenticationService - Session cache is unavailable, session is not cached: Currently not connected. Commands are rejected. + +# PostgreSQL is stopped: docker compose stop postgres +GET /health/live: 200 in 0.003356s +GET /health/ready: 503 in 0.008268s +GET /users/me with token: 503 in 2.029986s + body: {"error":{"code":"unavailable","message":"service temporarily unavailable","request_id":"..."}} +POST /auth/sessions: 503 in 2.014048s +GET /users/me anonymous: 401 in 0.003069s +GET /users/me with X-User-Id: 401 in 0.003128s +GET /users/me unknown token: 503 in 2.007361s +after docker compose start postgres, same token: 200 in 0.006353s +GET /health/ready: 200 in 0.003154s diff --git a/evidence/gradle-tests.txt b/evidence/gradle-tests.txt new file mode 100644 index 00000000..bd16314f --- /dev/null +++ b/evidence/gradle-tests.txt @@ -0,0 +1,72 @@ +# ./gradlew test (Testcontainers: postgres:17.6-alpine3.22, redis:8.4.0-alpine) +total: 56 tests, 0 failed + +infrastructure.controllers.authentication.AuthenticationControllerTest: 9 tests, 0 failed, 7.771 s + - logout revokes only the current token + - Bearer token cannot open a session + - password containing a colon and non-ASCII characters works + - unknown token returns 401 + - session expires after SESSION_TTL_SECONDS + - each login issues a different token + - valid Basic credentials open a session + - missing or malformed Basic header returns 401 + - wrong password and unknown user get the same 401 +infrastructure.controllers.chat.ChatControllerTest: 6 tests, 0 failed, 2.042 s + - member can read own chat and members keep their order + - unknown member is rejected before anything is written + - foreign chat returns 404 for non-member + - cursor issued to another user is rejected + - chat list contains only own chats and is paginated + - invalid member lists are rejected with 400 +infrastructure.controllers.health.HealthControllerTest: 2 tests, 0 failed, 0.128 s + - live returns 200 + - ready returns 200 when database is reachable +infrastructure.controllers.message.MessageConcurrencyTest: 1 tests, 0 failed, 0.281 s + - parallel senders produce exactly N unique messages +infrastructure.controllers.message.MessageControllerTest: 7 tests, 0 failed, 1.864 s + - foreign chat returns 404 when sending + - last page has null next_cursor + - pagination walks all messages exactly once + - foreign chat returns 404 when listing + - empty text returns 400 invalid_request + - history that is an exact multiple of limit ends with null next_cursor + - foreign cursor returns 400 +infrastructure.controllers.user.UserControllerTest: 11 tests, 0 failed, 1.7 s + - password shorter than 12 code points returns 400 + - concurrent registrations of one username create exactly one user + - X-User-Id alone gives no access + - create user returns 201 without password + - duplicate username returns 409 conflict + - missing token returns 401 with Bearer challenge + - invalid JSON body returns 400 invalid_request + - missing password returns 400 + - Basic credentials are rejected on business endpoints + - me returns the session owner + - X-User-Id does not override bearer identity +infrastructure.repositories.authentication.session.cache.RedisSessionCacheRepositoryTest: 3 tests, 0 failed, 0.1 s + - cached session round-trips and expires together with the session + - revoke replaces a cached session with a tombstone + - late cache fill cannot overwrite a tombstone +infrastructure.repositories.chat.ExposedChatRepositoryTest: 2 tests, 0 failed, 0.529 s + - chat row is rolled back when inserting members fails + - successful creation commits the chat and every member +infrastructure.services.authentication.SessionLookupSingleFlightTest: 4 tests, 0 failed, 1.107 s + - request arriving after logout does not join a lookup started before it + - without single-flight every concurrent miss queries the database + - with single-flight concurrent misses share one database lookup + - lookup that finished before a request arrived is not reused +infrastructure.services.hashing.DefaultHashingServiceTest: 4 tests, 0 failed, 0.425 s + - passwords differing only after 72 bytes are distinguished + - validates the right password and rejects a wrong one + - malformed hash is rejected instead of throwing + - hash is a salted Argon2id PHC string +plugins.DatabaseMigrationTest: 1 tests, 0 failed, 0.206 s + - re-running migrations applies nothing and keeps data +plugins.DependencyFailureTest: 3 tests, 0 failed, 8.502 s + - without PostgreSQL requests fail with a bounded 503 + - without Redis requests bypass the cache + - hanging Redis costs one command timeout and recovers +plugins.SessionCacheTest: 3 tests, 0 failed, 0.963 s + - emptied cache falls back to PostgreSQL + - first authenticated request fills the cache + - logout leaves a tombstone and the token is rejected diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..2e71aeff --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,27 @@ +# Before restart +mtusi-lab2-api Up 6 seconds (healthy) +mtusi-lab2-postgres Up 12 seconds (healthy) +mtusi-lab2-redis Up 12 seconds (healthy) +/mtusi-lab2-api started 2026-10-08T21:30:14.569499088Z +/mtusi-lab2-postgres started 2026-10-08T21:30:08.908684627Z +/mtusi-lab2-redis started 2026-10-08T21:30:08.908745585Z + +$ make test-persistence ACTION_SCRIPT=scripts/restart.sh +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +# After restart: all three containers have a new StartedAt, volume kept +mtusi-lab2-api Up 5 seconds (healthy) +mtusi-lab2-postgres Up 11 seconds (healthy) +mtusi-lab2-redis Up 11 seconds (healthy) +/mtusi-lab2-api started 2026-10-08T21:30:30.898479762Z +/mtusi-lab2-postgres started 2026-10-08T21:30:25.306495884Z +/mtusi-lab2-redis started 2026-10-08T21:30:25.305453468Z +mtusi-messenger-lab2_postgres-data + +# Migrations are not re-applied +2026-10-08T21:30:15.407Z INFO [main] o.f.core.internal.command.DbMigrate - Migrating schema "public" to version "1 - init" +2026-10-08T21:30:31.478Z INFO [main] o.f.core.internal.command.DbMigrate - Schema "public" is up to date. No migration necessary. + +# Redis keys after restart: Redis came up empty (no RDB/AOF), these 2 keys were filled by the test requests made after the restart +2 diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..20b89e50 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,4 @@ +$ make check +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +$ make test +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/storage.txt b/evidence/storage.txt new file mode 100644 index 00000000..dbe2dd11 --- /dev/null +++ b/evidence/storage.txt @@ -0,0 +1,23 @@ +# Password hashes (prefix only) +$argon2id$v=19$m=19456,t=2,p=1$|6 +# Sessions: only sha256 of the token is stored + Table "public.sessions" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+--------- + id | uuid | | not null | + user_id | uuid | | not null | + token_hash | character varying(64) | | not null | + created_at | timestamp with time zone | | not null | + expires_at | timestamp with time zone | | not null | +Indexes: + "sessions_pkey" PRIMARY KEY, btree (id) + "sessions_token_hash_key" UNIQUE CONSTRAINT, btree (token_hash) + "sessions_user_id_idx" btree (user_id) +Foreign-key constraints: + "sessions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + +64|5 +# Secrets are ignored by git +.gitignore:5:secrets/ secrets/db_password +.gitignore:5:secrets/ secrets/redis_password +tracked files under secrets/: 0 diff --git a/evidence/track1/read-after-write/off_redis-down.json b/evidence/track1/read-after-write/off_redis-down.json new file mode 100644 index 00000000..e26c2344 --- /dev/null +++ b/evidence/track1/read-after-write/off_redis-down.json @@ -0,0 +1,11 @@ +{ + "iterations": 300, + "readers": 16, + "first_request_after_login_not_200": 0, + "requests_started_before_logout_response": 43034, + "requests_started_after_logout_response": 362801, + "violations_200_after_logout": 0, + "unexpected_statuses": {}, + "token_alive_one_second_later": 0, + "logout_not_204": 0 +} diff --git a/evidence/track1/read-after-write/off_redis-up.json b/evidence/track1/read-after-write/off_redis-up.json new file mode 100644 index 00000000..a975e499 --- /dev/null +++ b/evidence/track1/read-after-write/off_redis-up.json @@ -0,0 +1,11 @@ +{ + "iterations": 300, + "readers": 16, + "first_request_after_login_not_200": 0, + "requests_started_before_logout_response": 42545, + "requests_started_after_logout_response": 396511, + "violations_200_after_logout": 0, + "unexpected_statuses": {}, + "token_alive_one_second_later": 0, + "logout_not_204": 0 +} diff --git a/evidence/track1/read-after-write/on_redis-down.json b/evidence/track1/read-after-write/on_redis-down.json new file mode 100644 index 00000000..ba321e08 --- /dev/null +++ b/evidence/track1/read-after-write/on_redis-down.json @@ -0,0 +1,11 @@ +{ + "iterations": 300, + "readers": 16, + "first_request_after_login_not_200": 0, + "requests_started_before_logout_response": 42973, + "requests_started_after_logout_response": 361654, + "violations_200_after_logout": 0, + "unexpected_statuses": {}, + "token_alive_one_second_later": 0, + "logout_not_204": 0 +} diff --git a/evidence/track1/read-after-write/on_redis-up.json b/evidence/track1/read-after-write/on_redis-up.json new file mode 100644 index 00000000..23132f25 --- /dev/null +++ b/evidence/track1/read-after-write/on_redis-up.json @@ -0,0 +1,11 @@ +{ + "iterations": 300, + "readers": 16, + "first_request_after_login_not_200": 0, + "requests_started_before_logout_response": 42692, + "requests_started_after_logout_response": 405818, + "violations_200_after_logout": 0, + "unexpected_statuses": {}, + "token_alive_one_second_later": 0, + "logout_not_204": 0 +} diff --git a/evidence/track1/redis-restart-runs.csv b/evidence/track1/redis-restart-runs.csv new file mode 100644 index 00000000..a675086b --- /dev/null +++ b/evidence/track1/redis-restart-runs.csv @@ -0,0 +1,11 @@ +variant,single_flight,tokens,vus,warmup_s,duration_s,measure_start,restart_begin,restart_end,repeat,finished_at,requests,failed,p50,p95,p99,max,session_lookups,cache_outage_s,recovered_after_restart_s,restart_s,peak_p99_ms,peak_max_ms,p99_before_ms,non_200 +off,False,50,200,5,30,1791498859.356887,1791498869.424248,1791498869.939573,1,2026-10-08T22:35:00Z,428635,0,12.452,27.07229999999998,39.76697999999999,132.782,5427,0.7099997997283936,0.4074268341064453,0.5153250694274902,76.32,132.78,35.55,0 +off,False,50,200,5,30,1791499169.386271,1791499179.479216,1791499180.0737689,2,2026-10-08T22:40:10Z,428950,0,12.47,26.540549999999982,38.444019999999995,224.922,6284,0.8270001411437988,0.47123122215270996,0.594552755355835,162.53,224.92,39.09,0 +off,False,50,200,5,30,1791499477.8345048,1791499487.915502,1791499488.4199932,3,2026-10-08T22:45:18Z,421278,0,12.626,27.578,40.115,161.579,5625,0.7209999561309814,0.42000675201416016,0.5044910907745361,77.41,161.58,37.26,0 +off,False,50,200,5,30,1791499595.6580842,1791499605.734366,1791499606.216612,4,2026-10-08T22:47:17Z,441542,0,12.277,25.8,36.003589999999996,112.49,5632,0.693000078201294,0.40138792991638184,0.48224616050720215,67.52,112.49,35.04,0 +off,False,50,200,5,30,1791499714.4913611,1791499724.5610518,1791499725.0957701,5,2026-10-08T22:49:15Z,440087,0,12.246,25.995,36.58613999999999,117.652,4700,0.6530001163482666,0.3472299575805664,0.5347182750701904,71.53,117.65,34.19,0 +on,True,50,200,5,30,1791498918.550673,1791498928.624585,1791498929.1620429,1,2026-10-08T22:36:00Z,437728,0,12.239,26.51164999999998,37.84445999999999,138.771,3349,0.7160000801086426,0.3989572525024414,0.5374579429626465,70.65,138.77,36.27,0 +on,True,50,200,5,30,1791499228.067796,1791499238.1518989,1791499238.66642,2,2026-10-08T22:41:09Z,425673,0,12.577,27.137,38.40755999999999,130.099,3490,0.7339999675750732,0.37657999992370605,0.5145211219787598,72.28,130.1,37.48,0 +on,True,50,200,5,30,1791499536.427604,1791499546.508571,1791499546.976043,3,2026-10-08T22:46:17Z,437173,0,12.129,26.806399999999982,38.543,137.96,3502,0.752000093460083,0.4419569969177246,0.4674720764160156,69.74,137.96,36.54,0 +on,True,50,200,5,30,1791499655.0228858,1791499665.094867,1791499665.5880342,4,2026-10-08T22:48:16Z,438776,0,12.336,25.784,36.31625,128.767,3106,0.7019999027252197,0.40596580505371094,0.4931671619415283,71.46,128.77,35.38,0 +on,True,50,200,5,30,1791499773.790411,1791499783.8553238,1791499784.422722,5,2026-10-08T22:50:14Z,434992,0,12.311,26.562,38.479359999999986,153.453,3805,0.7409999370574951,0.38727784156799316,0.5673983097076416,88.56,153.45,39.52,0 diff --git a/evidence/track1/redis-restart/off/t50_r1/k6-summary.json b/evidence/track1/redis-restart/off/t50_r1/k6-summary.json new file mode 100644 index 00000000..d15efb2f --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "groups": [], + "checks": [ + { + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 471907 + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e" + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35006.219 + }, + "metrics": { + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.764247413155049, + "med": 12.942, + "p(95)": 29.60769999999998, + "p(99)": 44.87233999999995, + "max": 273.623 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 39.76697999999999, + "max": 132.782, + "avg": 13.925806278068102, + "med": 12.452, + "p(95)": 27.07229999999998 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "fails": 0, + "rate": 1, + "passes": 471907 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.827875725505196, + "med": 13.005375, + "p(95)": 29.668933099999997, + "p(99)": 44.92554052, + "max": 281.858083 + } + }, + "http_req_failed": { + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 471907 + }, + "type": "rate" + }, + "http_req_blocked": { + "contains": "time", + "values": { + "avg": 0.004491240858890895, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.005, + "max": 10.725 + }, + "type": "trend" + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 154219353, + "rate": 4405484.436922479 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "max": 14.117, + "avg": 0.0204302055277808, + "med": 0.009, + "p(95)": 0.027, + "p(99)": 0.101 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "rate": 13480.661821832286, + "count": 471907 + } + }, + "http_req_connecting": { + "contains": "time", + "values": { + "max": 7.886, + "avg": 0.0023367697448861743, + "med": 0, + "p(95)": 0, + "p(99)": 0 + }, + "type": "trend" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.738216824501464, + "med": 12.919, + "p(95)": 29.57769999999998, + "p(99)": 44.842879999999994, + "max": 273.225 + } + }, + "http_reqs": { + "values": { + "count": 471907, + "rate": 13480.661821832286 + }, + "type": "counter", + "contains": "default" + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.005600383126326962, + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.034, + "max": 10.287 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 71729864, + "rate": 2049060.5969185075 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 428635, + "rate": 12244.538606125956 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 44.87233999999995, + "max": 273.623, + "avg": 14.764247413155049, + "med": 12.942, + "p(95)": 29.60769999999998 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 428635 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/off/t50_r1/per-second.csv b/evidence/track1/redis-restart/off/t50_r1/per-second.csv new file mode 100644 index 00000000..bbba28e4 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r1/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,14208,0,12.98,38.25,73.67 +1,14245,0,12.80,35.35,58.89 +2,15755,0,11.22,35.55,61.24 +3,15465,0,12.19,30.72,50.18 +4,16066,0,11.16,30.23,41.23 +5,14522,0,12.62,35.74,49.60 +6,13907,0,12.92,36.98,54.97 +7,14081,0,12.94,38.99,56.80 +8,15426,0,12.11,30.41,50.02 +9,14754,0,12.58,32.68,52.41 +10,8269,0,20.28,76.32,132.78 +11,12953,0,14.18,35.54,55.33 +12,15806,0,11.94,29.63,45.35 +13,15775,0,11.79,27.79,57.80 +14,16241,0,11.05,31.63,60.80 +15,14568,0,12.09,37.94,80.73 +16,14910,0,11.92,36.34,58.58 +17,11572,0,14.58,56.35,89.45 +18,12334,0,13.63,51.14,75.03 +19,14573,0,11.54,45.21,91.66 +20,14287,0,12.00,36.73,67.19 +21,14058,0,12.23,49.08,79.07 +22,14907,0,12.22,32.15,51.91 +23,14940,0,12.04,34.16,52.36 +24,14669,0,11.95,39.83,75.01 +25,13198,0,13.06,48.21,101.27 +26,14741,0,12.79,29.48,45.46 +27,12750,0,14.80,37.52,56.21 +28,15628,0,11.63,30.12,48.03 +29,11355,0,11.66,32.69,54.36 diff --git a/evidence/track1/redis-restart/off/t50_r1/run.json b/evidence/track1/redis-restart/off/t50_r1/run.json new file mode 100644 index 00000000..632c03a8 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r1/run.json @@ -0,0 +1,4 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791498859.356887, + "restart_begin": 1791498869.424248, "restart_end": 1791498869.939573, "repeat": 1, + "finished_at": "2026-10-08T22:35:00Z"} diff --git a/evidence/track1/redis-restart/off/t50_r1/samples.csv b/evidence/track1/redis-restart/off/t50_r1/samples.csv new file mode 100644 index 00000000..0bfeed70 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r1/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791498859.864,0,512089,4214, +1791498860.756,0,524927,4214, +1791498861.713,0,539048,4214, +1791498862.794,0,555997,4214, +1791498863.76,0,570946,4214, +1791498864.854,0,588689,4214, +1791498865.878,0,602767,4214, +1791498866.818,0,616391,4214, +1791498867.786,0,630300,4214, +1791498868.72,0,644189,4214, +1791498869.798,0, +1791498870.812,5427,5110,57, +1791498871.75,5427,18070,57, +1791498872.766,5427,34359,57, +1791498873.738,5427,49277,57, +1791498874.831,5427,67502,57, +1791498875.801,5427,80988,57, +1791498876.758,5427,95693,57, +1791498877.872,5427,106337,57, +1791498878.927,5427,121509,57, +1791498879.829,5427,134595,57, +1791498880.828,5427,148840,57, +1791498881.792,5427,163192,57, +1791498882.795,5427,178002,57, +1791498883.798,5427,192983,57, +1791498884.779,5427,207703,57, +1791498885.785,5427,220645,57, +1791498886.732,5427,233709,57, +1791498887.813,5427,248645,57, +1791498888.73,5427,263312,57, diff --git a/evidence/track1/redis-restart/off/t50_r2/k6-summary.json b/evidence/track1/redis-restart/off/t50_r2/k6-summary.json new file mode 100644 index 00000000..46d5cd74 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "state": { + "testRunDurationMs": 35011.754, + "isStdOutTTY": false, + "isStdErrTTY": false + }, + "metrics": { + "http_reqs": { + "contains": "default", + "values": { + "count": 472464, + "rate": 13494.439610194906 + }, + "type": "counter" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.716876849876583, + "med": 12.874, + "p(95)": 29.014, + "p(99)": 44.48158999999997, + "max": 256.777 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "rate": 12251.59984843947, + "count": 428950 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.02486028565136214, + "med": 0.009, + "p(95)": 0.027, + "p(99)": 0.114, + "max": 17.033 + } + }, + "iterations": { + "values": { + "count": 472464, + "rate": 13494.439610194906 + }, + "type": "counter", + "contains": "default" + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 472464 + } + }, + "data_sent": { + "contains": "data", + "values": { + "count": 71814528, + "rate": 2051154.8207496258 + }, + "type": "counter" + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.917842683296533, + "med": 12.47, + "p(95)": 26.540549999999982, + "p(99)": 38.444019999999995, + "max": 224.922 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.962916499999999, + "p(95)": 29.132189249999996, + "p(99)": 44.585753629999985, + "max": 264.631125, + "avg": 14.8122813028043 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "min": 200, + "max": 200, + "value": 200 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 428950 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "max": 17.938, + "avg": 0.001841765721832775, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "avg": 14.749357261082592, + "med": 12.902, + "p(95)": 29.071, + "p(99)": 44.513369999999995, + "max": 259.749 + }, + "type": "trend" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.005, + "max": 19.84, + "avg": 0.004122038927809423, + "med": 0.001, + "p(95)": 0.002 + } + }, + "checks": { + "values": { + "passes": 472464, + "fails": 0, + "rate": 1 + }, + "type": "rate", + "contains": "default" + }, + "http_req_tls_handshaking": { + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + }, + "type": "trend" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 154401348, + "rate": 4409986.086386874 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.749357261082592, + "med": 12.902, + "p(95)": 29.071, + "p(99)": 44.513369999999995, + "max": 259.749 + } + }, + "http_req_sending": { + "values": { + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.032, + "max": 18.129, + "avg": 0.007620125554550124 + }, + "type": "trend", + "contains": "time" + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 472464, + "fails": 0, + "name": "status is 200", + "path": "::status is 200" + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/off/t50_r2/per-second.csv b/evidence/track1/redis-restart/off/t50_r2/per-second.csv new file mode 100644 index 00000000..145cac1c --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r2/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,13183,0,13.68,37.62,65.37 +1,11835,0,15.33,41.56,61.33 +2,13706,0,12.92,41.07,75.96 +3,14687,0,12.29,34.34,76.87 +4,15065,0,12.11,31.57,57.47 +5,14716,0,12.21,39.09,61.12 +6,14694,0,12.64,32.24,45.00 +7,10787,0,15.45,64.66,105.60 +8,11306,0,14.85,53.23,93.07 +9,14932,0,12.50,30.28,46.64 +10,9196,0,14.95,162.53,224.92 +11,13251,0,13.62,36.19,55.49 +12,15493,0,11.90,29.90,42.35 +13,16528,0,10.95,32.57,61.17 +14,16522,0,10.73,30.40,50.92 +15,15305,0,11.95,31.96,58.61 +16,14122,0,13.05,36.73,65.61 +17,13084,0,13.48,50.46,85.51 +18,14804,0,12.23,33.57,55.10 +19,14648,0,12.56,31.26,48.91 +20,15292,0,11.62,34.05,58.57 +21,15098,0,12.43,29.98,58.95 +22,15093,0,12.31,31.74,46.91 +23,16796,0,10.74,28.41,43.15 +24,14733,0,12.76,29.88,47.53 +25,14409,0,12.79,34.22,55.14 +26,17194,0,10.33,29.15,47.15 +27,13183,0,13.98,38.02,54.26 +28,15846,0,11.60,30.98,56.75 +29,11278,0,12.97,33.05,46.19 diff --git a/evidence/track1/redis-restart/off/t50_r2/run.json b/evidence/track1/redis-restart/off/t50_r2/run.json new file mode 100644 index 00000000..5409b90c --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r2/run.json @@ -0,0 +1,4 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499169.386271, + "restart_begin": 1791499179.479216, "restart_end": 1791499180.0737689, "repeat": 2, + "finished_at": "2026-10-08T22:40:10Z"} diff --git a/evidence/track1/redis-restart/off/t50_r2/samples.csv b/evidence/track1/redis-restart/off/t50_r2/samples.csv new file mode 100644 index 00000000..09a1eef7 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r2/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499169.947,0,515309,4269, +1791499170.835,0,527125,4269, +1791499171.916,0,539462,4269, +1791499172.863,0,554289,4269, +1791499173.824,0,568084,4269, +1791499174.812,0,582152,4269, +1791499175.778,0,597540,4269, +1791499176.864,0,613082,4269, +1791499178.029,0,623870,4269, +1791499178.865,0,635700,4269, +1791499180.141,0,0,0, +1791499180.903,6284,4203,97, +1791499181.83,6284,17538,97, +1791499182.82,6284,32281,97, +1791499183.802,6284,49011,97, +1791499184.792,6284,65558,97, +1791499185.804,6284,80275,97, +1791499186.894,6284,95577,97, +1791499187.839,6284,108571,97, +1791499188.782,6284,121475,97, +1791499189.803,6284,137606,97, +1791499190.861,6284,153144,97, +1791499191.758,6284,166411,97, +1791499192.844,6284,184088,97, +1791499193.808,6284,199336,97, +1791499194.789,6284,213503,97, +1791499195.827,6284,230318,97, +1791499196.759,6284,244205,97, +1791499197.813,6284,259548,97, +1791499198.777,6284,275085,97, diff --git a/evidence/track1/redis-restart/off/t50_r3/k6-summary.json b/evidence/track1/redis-restart/off/t50_r3/k6-summary.json new file mode 100644 index 00000000..1fcc3526 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35007.175 + }, + "metrics": { + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 460812, + "rate": 0 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 70043424, + "rate": 2000830.515458617 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "max": 5.508, + "avg": 0.0009216687065441001, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_receiving": { + "values": { + "avg": 0.02030224256312753, + "med": 0.01, + "p(95)": 0.026, + "p(99)": 0.095, + "max": 25.03 + }, + "type": "trend", + "contains": "time" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 47.51888999999999, + "max": 243.202, + "avg": 15.094730109025615, + "med": 13.09, + "p(95)": 30.59044999999998 + } + }, + "vus_max": { + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0030553132296668143, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.005, + "max": 8.159 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "rate": 4301781.591916515, + "count": 150593221 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 460812, + "rate": 13163.358654333006 + } + }, + "iterations": { + "values": { + "count": 460812, + "rate": 13163.358654333006 + }, + "type": "counter", + "contains": "default" + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "med": 13.113, + "p(95)": 30.63144999999998, + "p(99)": 47.572, + "max": 243.737, + "avg": 15.120494461949612 + }, + "type": "trend" + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 421278 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 243.737, + "avg": 15.120494461949612, + "med": 13.113, + "p(95)": 30.63144999999998, + "p(99)": 47.572 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.005462110361699867, + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.03, + "max": 21.888 + } + }, + "http_req_duration{phase:measure}": { + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time", + "values": { + "avg": 14.167799875616495, + "med": 12.626, + "p(95)": 27.578, + "p(99)": 40.115, + "max": 161.579 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 421278, + "rate": 12034.047306016553 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 15.18369266241983, + "med": 13.168084, + "p(95)": 30.717431249999997, + "p(99)": 47.69920598999999, + "max": 250.832291 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 460812, + "fails": 0 + } + } + }, + "root_group": { + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "passes": 460812, + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f" + } + ], + "name": "", + "path": "" + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/off/t50_r3/per-second.csv b/evidence/track1/redis-restart/off/t50_r3/per-second.csv new file mode 100644 index 00000000..b56b17eb --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r3/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,11980,0,15.04,48.92,86.32 +1,10196,0,16.53,62.53,91.28 +2,12842,0,13.46,42.20,61.44 +3,14513,0,12.45,37.26,89.99 +4,14203,0,12.48,39.47,67.48 +5,15145,0,11.59,34.51,70.34 +6,15360,0,11.75,35.32,51.02 +7,15000,0,12.30,29.88,47.96 +8,14761,0,12.21,36.57,83.75 +9,13687,0,13.16,38.34,57.54 +10,9334,0,17.65,77.41,161.58 +11,12568,0,14.12,40.11,73.91 +12,13968,0,13.01,34.76,52.99 +13,14453,0,11.83,37.20,65.84 +14,14510,0,12.49,35.25,99.83 +15,14487,0,12.40,35.04,56.12 +16,15502,0,11.34,33.16,52.91 +17,14646,0,12.45,34.83,57.32 +18,14166,0,12.65,38.85,68.11 +19,14531,0,12.40,33.75,54.74 +20,15244,0,11.83,32.98,57.56 +21,14585,0,12.34,36.98,72.59 +22,14811,0,12.55,34.53,67.74 +23,15705,0,11.80,30.10,52.46 +24,14766,0,12.29,32.69,57.07 +25,14371,0,13.10,30.52,47.73 +26,16018,0,11.16,30.27,60.16 +27,14366,0,12.99,33.12,68.86 +28,15109,0,11.79,33.39,48.43 +29,9316,0,14.12,64.89,132.72 diff --git a/evidence/track1/redis-restart/off/t50_r3/run.json b/evidence/track1/redis-restart/off/t50_r3/run.json new file mode 100644 index 00000000..159df8da --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r3/run.json @@ -0,0 +1,4 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499477.8345048, + "restart_begin": 1791499487.915502, "restart_end": 1791499488.4199932, "repeat": 3, + "finished_at": "2026-10-08T22:45:18Z"} diff --git a/evidence/track1/redis-restart/off/t50_r3/samples.csv b/evidence/track1/redis-restart/off/t50_r3/samples.csv new file mode 100644 index 00000000..3bf2557d --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r3/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499478.391,0,514178,4179, +1791499479.42,0,525888,4179, +1791499480.325,0,536517,4179, +1791499481.385,0,550681,4179, +1791499482.312,0,563782,4179, +1791499483.282,0,578653,4179, +1791499484.289,0,593619,4179, +1791499485.222,0,607812,4179, +1791499486.228,0,623157,4179, +1791499487.316,0,638365,4179, +1791499488.491,0,0,0, +1791499489.388,5625,6357,139, +1791499490.326,5625,17832,139, +1791499491.28,5625,32144,139, +1791499492.329,5625,47177,139, +1791499493.326,5625,62132,139, +1791499494.245,5625,74845,139, +1791499495.213,5625,89695,139, +1791499496.263,5625,104778,139, +1791499497.318,5625,120104,139, +1791499498.256,5625,133818,139, +1791499499.226,5625,149087,139, +1791499500.236,5625,163102,139, +1791499501.243,5625,178474,139, +1791499502.293,5625,194607,139, +1791499503.247,5625,208856,139, +1791499504.306,5625,225215,139, +1791499505.229,5625,239096,139, +1791499506.235,5625,252821,139, +1791499507.349,5625,268098,139, diff --git a/evidence/track1/redis-restart/off/t50_r4/k6-summary.json b/evidence/track1/redis-restart/off/t50_r4/k6-summary.json new file mode 100644 index 00000000..fa5b6a13 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r4/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 486255, + "fails": 81 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35013.452 + }, + "metrics": { + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "max": 1.984, + "avg": 0.00067285374720358, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0.9998334484800632, + "passes": 486255, + "fails": 81 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 73914408, + "rate": 2111028.869704135 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 158879033, + "rate": 4537656.926829151 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.326034741412773, + "med": 12.679, + "p(95)": 28.305, + "p(99)": 42.136649999999996, + "max": 257.138 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.386179311953176, + "med": 12.7341455, + "p(95)": 28.378582749999996, + "p(99)": 42.21687325, + "max": 259.654125 + } + }, + "http_req_tls_handshaking": { + "values": { + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0 + }, + "type": "trend", + "contains": "time" + }, + "http_reqs": { + "contains": "default", + "values": { + "count": 486336, + "rate": 13889.975772740145 + }, + "type": "counter" + }, + "http_req_receiving": { + "contains": "time", + "values": { + "p(99)": 0.107, + "max": 19.168, + "avg": 0.0206999708020806, + "med": 0.009, + "p(95)": 0.026 + }, + "type": "trend" + }, + "http_req_failed": { + "contains": "default", + "values": { + "rate": 0.0001665515199368338, + "passes": 81, + "fails": 486255 + }, + "type": "rate" + }, + "http_reqs{phase:measure}": { + "contains": "default", + "values": { + "count": 441542, + "rate": 12610.638905298454 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter" + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.299780478928266, + "med": 12.657, + "p(95)": 28.265, + "p(99)": 42.07064999999999, + "max": 257.009 + } + }, + "http_req_sending": { + "contains": "time", + "values": { + "p(99)": 0.035, + "max": 18.398, + "avg": 0.005554291683109536, + "med": 0.003, + "p(95)": 0.009 + }, + "type": "trend" + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.520681441402726, + "med": 12.277, + "p(95)": 25.8, + "p(99)": 36.003589999999996, + "max": 112.49 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 441542 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 486336, + "rate": 13889.975772740145 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.002852982300280097, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 10.914 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.681, + "p(95)": 28.305, + "p(99)": 42.13837999999999, + "max": 257.138, + "avg": 14.328368140172795 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/off/t50_r4/per-second.csv b/evidence/track1/redis-restart/off/t50_r4/per-second.csv new file mode 100644 index 00000000..30743b46 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r4/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,12715,0,14.45,36.45,64.04 +1,10581,0,17.41,44.58,64.33 +2,14179,0,12.89,35.04,61.72 +3,14318,0,12.53,37.96,59.33 +4,14792,0,11.85,40.34,79.74 +5,16249,0,11.35,29.80,46.75 +6,15848,0,11.50,31.80,74.79 +7,15711,0,11.68,34.58,57.46 +8,15294,0,11.76,31.68,46.27 +9,15335,0,11.92,30.41,48.52 +10,9506,0,17.60,67.52,112.49 +11,12370,0,14.93,38.32,74.71 +12,14833,0,12.73,31.75,47.67 +13,15645,0,11.81,29.53,52.72 +14,14186,0,12.34,40.49,68.77 +15,14497,0,12.68,33.11,55.55 +16,14867,0,12.32,32.80,58.83 +17,15925,0,11.59,29.35,50.58 +18,15749,0,11.77,30.82,53.76 +19,16242,0,11.23,31.00,49.71 +20,15967,0,11.23,33.81,63.82 +21,13801,0,13.24,35.50,53.41 +22,15339,0,11.79,33.48,57.64 +23,15599,0,12.16,30.17,44.75 +24,14012,0,12.64,62.10,104.27 +25,16364,0,11.13,31.07,51.80 +26,15277,0,11.67,35.48,55.90 +27,16592,0,10.98,27.14,45.43 +28,15277,0,12.21,30.49,72.97 +29,12303,0,12.37,32.19,61.25 diff --git a/evidence/track1/redis-restart/off/t50_r4/run.json b/evidence/track1/redis-restart/off/t50_r4/run.json new file mode 100644 index 00000000..adafe8e2 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r4/run.json @@ -0,0 +1,4 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499595.6580842, + "restart_begin": 1791499605.734366, "restart_end": 1791499606.216612, "repeat": 4, + "finished_at": "2026-10-08T22:47:17Z"} diff --git a/evidence/track1/redis-restart/off/t50_r4/samples.csv b/evidence/track1/redis-restart/off/t50_r4/samples.csv new file mode 100644 index 00000000..a80570a6 --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r4/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499596.157,0,340499,326, +1791499597.18,0,352918,326, +1791499598.146,0,363899,326, +1791499599.121,0,378171,326, +1791499600.147,0,393091,326, +1791499601.143,0,409374,326, +1791499602.133,0,425489,326, +1791499603.081,0,439299,326, +1791499604.089,0,456049,326, +1791499605.076,0,470768,326, +1791499606.264,0,0,0, +1791499607.126,5632,5406,175, +1791499608.159,5632,18795,175, +1791499609.092,5632,32858,175, +1791499610.172,5632,48585,175, +1791499611.072,5632,62560,175, +1791499612.092,5632,77524,175, +1791499613.085,5632,93072,175, +1791499614.116,5632,109574,175, +1791499615.1,5632,124272,175, +1791499616.108,5632,140777,175, +1791499617.025,5632,154654,175, +1791499618.008,5632,168103,175, +1791499619.09,5632,185717,175, +1791499620.107,5632,200716,175, +1791499621.103,5632,215755,175, +1791499622.148,5632,232413,175, +1791499623.098,5632,247222,175, +1791499624.064,5632,262899,175, +1791499625.097,5632,278598,175, diff --git a/evidence/track1/redis-restart/off/t50_r5/k6-summary.json b/evidence/track1/redis-restart/off/t50_r5/k6-summary.json new file mode 100644 index 00000000..c12531cb --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r5/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "checks": [ + { + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 484492 + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35007.881 + }, + "metrics": { + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.005235176225810493, + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.032, + "max": 10.618 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 41.75308999999999, + "max": 292.076, + "avg": 14.357900902388325, + "med": 12.701, + "p(95)": 28.345 + } + }, + "http_req_receiving": { + "values": { + "p(95)": 0.026, + "p(99)": 0.099, + "max": 16.6, + "avg": 0.02069577413042727, + "med": 0.009 + }, + "type": "trend", + "contains": "time" + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 41.78708999999999, + "max": 292.093, + "avg": 14.383831852744583, + "med": 12.723, + "p(95)": 28.394 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 440087, + "rate": 12571.083636853085 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 158332084, + "rate": 4522755.43326944 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 73642784, + "rate": 2103605.8709180374 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 484492, + "rate": 13839.512308671297 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.383831852744583, + "med": 12.723, + "p(95)": 28.394, + "p(99)": 41.78708999999999, + "max": 292.093 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 440087 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 484492 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.442657354761863, + "med": 12.7803545, + "p(95)": 28.44593535, + "p(99)": 41.85505868999999, + "max": 295.687208 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 484492, + "fails": 0 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0 + } + }, + "http_reqs": { + "contains": "default", + "values": { + "count": 484492, + "rate": 13839.512308671297 + }, + "type": "counter" + }, + "http_req_duration{phase:measure}": { + "contains": "time", + "values": { + "p(99)": 36.58613999999999, + "max": 117.652, + "avg": 13.56688794942809, + "med": 12.246, + "p(95)": 25.995 + }, + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend" + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0007097970657926239, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.395 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.005, + "max": 6.567, + "avg": 0.0029002253906960382, + "med": 0.001, + "p(95)": 0.002 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/off/t50_r5/per-second.csv b/evidence/track1/redis-restart/off/t50_r5/per-second.csv new file mode 100644 index 00000000..4dbb793c --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r5/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,12845,0,14.31,36.50,51.16 +1,13580,0,13.93,34.01,52.87 +2,14343,0,12.52,37.48,61.44 +3,16036,0,10.98,32.38,75.53 +4,14644,0,12.49,33.59,67.31 +5,14431,0,12.09,47.04,103.81 +6,12818,0,14.34,41.83,62.49 +7,14576,0,12.43,34.19,64.39 +8,16019,0,11.34,30.49,41.02 +9,14539,0,12.29,33.71,56.27 +10,9430,0,16.91,71.53,117.65 +11,13524,0,14.02,32.07,45.63 +12,13643,0,13.59,33.77,54.31 +13,15035,0,12.55,30.84,53.13 +14,16310,0,10.71,30.58,67.90 +15,13745,0,13.32,35.81,52.89 +16,14936,0,12.15,37.68,64.96 +17,14292,0,12.53,40.45,55.23 +18,14485,0,12.01,39.41,80.12 +19,15955,0,11.26,33.40,48.78 +20,15486,0,11.89,32.33,54.35 +21,15891,0,11.44,33.42,66.86 +22,15830,0,11.06,38.56,57.84 +23,15396,0,11.82,31.34,48.08 +24,15722,0,11.46,30.89,54.16 +25,16087,0,11.12,32.57,46.88 +26,15180,0,12.29,31.57,46.84 +27,16129,0,11.28,31.89,54.02 +28,15066,0,11.84,37.84,81.58 +29,12635,0,12.49,32.00,57.39 diff --git a/evidence/track1/redis-restart/off/t50_r5/run.json b/evidence/track1/redis-restart/off/t50_r5/run.json new file mode 100644 index 00000000..d3d0774c --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r5/run.json @@ -0,0 +1,4 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499714.4913611, + "restart_begin": 1791499724.5610518, "restart_end": 1791499725.0957701, "repeat": 5, + "finished_at": "2026-10-08T22:49:15Z"} diff --git a/evidence/track1/redis-restart/off/t50_r5/samples.csv b/evidence/track1/redis-restart/off/t50_r5/samples.csv new file mode 100644 index 00000000..5def267b --- /dev/null +++ b/evidence/track1/redis-restart/off/t50_r5/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499715.043,0,335130,371, +1791499715.952,0,347490,371, +1791499717.018,0,361982,371, +1791499717.912,0,374894,371, +1791499718.94,0,391959,371, +1791499719.921,0,405237,371, +1791499720.956,0,419892,371, +1791499722.043,0,434785,371, +1791499722.953,0,449061,371, +1791499723.942,0,464268,371, +1791499725.172,0,0,0, +1791499725.932,4700,6255,48, +1791499726.92,4700,19634,48, +1791499727.897,4700,33312,48, +1791499728.937,4700,49141,48, +1791499729.99,4700,65387,48, +1791499730.955,4700,79037,48, +1791499731.876,4700,92751,48, +1791499732.961,4700,108124,48, +1791499733.881,4700,120883,48, +1791499734.889,4700,137311,48, +1791499735.945,4700,153840,48, +1791499737.059,4700,171870,48, +1791499737.965,4700,186268,48, +1791499738.942,4700,201226,48, +1791499739.939,4700,216974,48, +1791499740.904,4700,232435,48, +1791499741.876,4700,247269,48, +1791499742.938,4700,263500,48, +1791499743.861,4700,277361,48, diff --git a/evidence/track1/redis-restart/on/t50_r1/k6-summary.json b/evidence/track1/redis-restart/on/t50_r1/k6-summary.json new file mode 100644 index 00000000..51b1f1a5 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "checks": [ + { + "fails": 26, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 478630 + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "testRunDurationMs": 35011.623, + "isStdOutTTY": false, + "isStdErrTTY": false + }, + "metrics": { + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 156416330, + "rate": 4467554.389009615 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 29.405, + "p(99)": 44.542799999999986, + "max": 260.28, + "avg": 14.557005296079032, + "med": 12.729 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0006549338146811069, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 1.863 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 72755712, + "rate": 2078044.539666156 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.002757521058943105, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.005, + "max": 7.489 + } + }, + "http_req_waiting": { + "values": { + "med": 12.705, + "p(95)": 29.366, + "p(99)": 44.507, + "max": 260.242, + "avg": 14.528975855311547 + }, + "type": "trend", + "contains": "time" + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.106, + "max": 14.215, + "avg": 0.022400015877768808, + "med": 0.009, + "p(95)": 0.026 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 29.464698, + "p(99)": 44.608145949999994, + "max": 263.268292, + "avg": 14.619031170008995, + "med": 12.7908125 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "count": 437728, + "rate": 12502.36242975654 + } + }, + "http_req_failed": { + "values": { + "rate": 0.000054318759192405404, + "passes": 26, + "fails": 478630 + }, + "type": "rate", + "contains": "default" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 437728 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.032, + "max": 11.176, + "avg": 0.005629424889685217 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.557682502141537, + "med": 12.729, + "p(95)": 29.405, + "p(99)": 44.54383999999998, + "max": 260.28 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 478656, + "rate": 13671.345655698395 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.239, + "p(95)": 26.51164999999998, + "p(99)": 37.84445999999999, + "max": 138.771, + "avg": 13.635527300058603 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_reqs": { + "values": { + "count": 478656, + "rate": 13671.345655698395 + }, + "type": "counter", + "contains": "default" + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0.9999456812408076, + "passes": 478630, + "fails": 26 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/on/t50_r1/per-second.csv b/evidence/track1/redis-restart/on/t50_r1/per-second.csv new file mode 100644 index 00000000..5603b02a --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r1/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,12213,0,14.61,41.13,74.22 +1,12003,0,14.94,45.38,83.34 +2,15366,0,11.88,31.92,63.48 +3,15860,0,11.69,30.37,50.03 +4,15975,0,11.29,31.56,60.09 +5,16120,0,11.06,34.09,71.77 +6,14812,0,12.44,36.27,57.96 +7,12949,0,13.50,43.30,69.10 +8,15233,0,11.41,39.21,74.20 +9,14742,0,12.35,33.16,62.76 +10,10257,0,15.73,70.65,138.77 +11,13312,0,13.33,37.88,74.71 +12,13899,0,13.21,34.32,61.78 +13,15348,0,11.40,36.97,63.73 +14,15002,0,11.97,35.83,53.83 +15,15868,0,11.71,27.60,41.99 +16,14414,0,12.57,33.39,54.13 +17,15924,0,10.81,44.06,69.43 +18,13682,0,12.61,41.81,66.34 +19,15676,0,11.76,31.78,61.49 +20,15032,0,11.85,34.64,52.50 +21,15127,0,11.97,35.84,58.51 +22,15163,0,12.06,32.21,52.89 +23,14419,0,12.03,41.51,73.14 +24,15821,0,11.52,30.89,53.97 +25,14857,0,12.46,32.85,56.86 +26,15789,0,11.47,33.42,63.45 +27,15351,0,12.14,32.52,50.62 +28,14627,0,12.08,38.89,73.95 +29,11194,0,13.24,44.34,72.24 diff --git a/evidence/track1/redis-restart/on/t50_r1/run.json b/evidence/track1/redis-restart/on/t50_r1/run.json new file mode 100644 index 00000000..e3f45f51 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r1/run.json @@ -0,0 +1,4 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791498918.550673, + "restart_begin": 1791498928.624585, "restart_end": 1791498929.1620429, "repeat": 1, + "finished_at": "2026-10-08T22:36:00Z"} diff --git a/evidence/track1/redis-restart/on/t50_r1/samples.csv b/evidence/track1/redis-restart/on/t50_r1/samples.csv new file mode 100644 index 00000000..07eed950 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r1/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791498919.071,0,317401,257, +1791498919.987,0,327828,257, +1791498921.001,0,341899,257, +1791498921.983,0,357576,257, +1791498922.957,0,372222,257, +1791498924.008,0,390319,257, +1791498924.97,0,404625,257, +1791498926.008,0,418215,257, +1791498927.102,0,433839,257, +1791498928.042,0,449050,257, +1791498929.24,0,0,0, +1791498930.063,3349,5883,86, +1791498931.052,3349,19175,86, +1791498932.042,3349,33712,86, +1791498932.968,3349,47268,86, +1791498934.045,3349,64450,86, +1791498934.973,3349,78135,86, +1791498936.001,3349,93074,86, +1791498936.967,3349,107697,86, +1791498937.967,3349,123259,86, +1791498938.989,3349,138163,86, +1791498939.954,3349,153047,86, +1791498940.99,3349,169183,86, +1791498942.045,3349,184284,86, +1791498943.026,3349,199741,86, +1791498943.961,3349,213986,86, +1791498945.019,3349,229833,86, +1791498945.958,3349,245094,86, +1791498947.062,3349,259971,86, +1791498947.93,3349,273526,86, diff --git a/evidence/track1/redis-restart/on/t50_r2/k6-summary.json b/evidence/track1/redis-restart/on/t50_r2/k6-summary.json new file mode 100644 index 00000000..859bdcfa --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "checks": [ + { + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 469526, + "fails": 0, + "name": "status is 200" + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + }, + "options": { + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "" + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35010.557 + }, + "metrics": { + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 425673 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 71367952, + "rate": 2038469.4822193205 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.811756335112861, + "med": 13.017, + "p(95)": 29.444, + "p(99)": 44.23424999999999, + "max": 212.836 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.903013638786282, + "med": 13.1062295, + "p(95)": 29.568145749999992, + "p(99)": 44.3406665, + "max": 217.317375 + } + }, + "http_req_duration{phase:measure}": { + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time", + "values": { + "p(99)": 38.40755999999999, + "max": 130.099, + "avg": 14.023004470568258, + "med": 12.577, + "p(95)": 27.137 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "count": 425673, + "rate": 12158.418387916538 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0007158836784331432, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.413 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 469526, + "fails": 0 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 469526, + "rate": 0 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 469526, + "rate": 13410.983435653423 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.006134463267205933, + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.036, + "max": 13.965 + } + }, + "data_received": { + "contains": "data", + "values": { + "count": 153441035, + "rate": 4382707.621589682 + }, + "type": "counter" + }, + "http_req_blocked": { + "contains": "time", + "values": { + "avg": 0.0029741164493320197, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.005, + "max": 10.368 + }, + "type": "trend" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 212.851, + "avg": 14.840465633426115, + "med": 13.045, + "p(95)": 29.503, + "p(99)": 44.28474999999996 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 469526, + "rate": 13410.983435653423 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.840465633426115, + "med": 13.045, + "p(95)": 29.503, + "p(99)": 44.28474999999996, + "max": 212.851 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.02257483504639342, + "med": 0.01, + "p(95)": 0.027, + "p(99)": 0.11, + "max": 13.986 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/on/t50_r2/per-second.csv b/evidence/track1/redis-restart/on/t50_r2/per-second.csv new file mode 100644 index 00000000..ce846285 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r2/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,11213,0,16.31,44.01,59.43 +1,12491,0,14.84,36.39,51.15 +2,13031,0,14.03,37.95,69.25 +3,13593,0,13.20,37.95,69.59 +4,14146,0,12.65,34.57,58.95 +5,14553,0,12.50,33.02,54.43 +6,15391,0,11.26,38.35,64.15 +7,14686,0,12.09,37.48,52.37 +8,14690,0,11.90,37.22,56.36 +9,14779,0,11.81,40.11,72.89 +10,9876,0,16.58,72.28,130.10 +11,13823,0,13.32,36.58,78.45 +12,13851,0,13.07,37.98,60.76 +13,15651,0,11.83,29.86,69.26 +14,14817,0,12.44,32.01,55.01 +15,14137,0,12.67,40.56,96.58 +16,15755,0,11.21,35.83,59.05 +17,15764,0,11.59,31.11,55.74 +18,15474,0,11.73,30.58,56.33 +19,12696,0,13.92,43.99,79.47 +20,15696,0,11.12,33.06,52.73 +21,14311,0,12.66,36.62,58.77 +22,15257,0,11.87,31.96,76.74 +23,15808,0,11.51,31.97,55.71 +24,14781,0,12.62,30.77,46.26 +25,16376,0,11.11,30.00,51.19 +26,13908,0,13.06,37.28,67.95 +27,12516,0,14.79,43.17,68.90 +28,13341,0,13.68,40.16,66.15 +29,12423,0,12.19,39.25,53.88 diff --git a/evidence/track1/redis-restart/on/t50_r2/run.json b/evidence/track1/redis-restart/on/t50_r2/run.json new file mode 100644 index 00000000..d8fa753f --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r2/run.json @@ -0,0 +1,4 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499228.067796, + "restart_begin": 1791499238.1518989, "restart_end": 1791499238.66642, "repeat": 2, + "finished_at": "2026-10-08T22:41:09Z"} diff --git a/evidence/track1/redis-restart/on/t50_r2/samples.csv b/evidence/track1/redis-restart/on/t50_r2/samples.csv new file mode 100644 index 00000000..c9c68947 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r2/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499228.567,0,330121,297, +1791499229.544,0,341792,297, +1791499230.464,0,352997,297, +1791499231.538,0,367011,297, +1791499232.566,0,381349,297, +1791499233.576,0,396290,297, +1791499234.515,0,409576,297, +1791499235.525,0,425803,297, +1791499236.523,0,439715,297, +1791499237.548,0,455015,297, +1791499238.738,0,0,0, +1791499239.58,3490,6544,155, +1791499240.542,3490,19074,155, +1791499241.494,3490,33261,155, +1791499242.519,3490,49163,155, +1791499243.491,3490,63238,155, +1791499244.582,3490,79585,155, +1791499245.518,3490,93930,155, +1791499246.546,3490,110638,155, +1791499247.537,3490,124333,155, +1791499248.501,3490,137784,155, +1791499249.542,3490,155102,155, +1791499250.537,3490,168371,155, +1791499251.558,3490,184624,155, +1791499252.462,3490,198017,155, +1791499253.535,3490,215104,155, +1791499254.493,3490,229588,155, +1791499255.464,3490,241923,155, +1791499256.507,3490,256022,155, +1791499257.441,3490,267875,155, diff --git a/evidence/track1/redis-restart/on/t50_r3/k6-summary.json b/evidence/track1/redis-restart/on/t50_r3/k6-summary.json new file mode 100644 index 00000000..a16eaf41 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35010.257 + }, + "metrics": { + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 477574, + "rate": 13640.97384375099 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.576, + "p(95)": 29.78334999999998, + "p(99)": 45.757, + "max": 499.375, + "avg": 14.552761925900535 + } + }, + "http_req_sending": { + "contains": "time", + "values": { + "avg": 0.0058634871245025625, + "med": 0.003, + "p(95)": 0.009, + "p(99)": 0.035, + "max": 15.193 + }, + "type": "trend" + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 477574, + "rate": 13640.97384375099 + } + }, + "checks": { + "values": { + "rate": 1, + "passes": 477574, + "fails": 0 + }, + "type": "rate", + "contains": "default" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0044636412367465095, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.005, + "max": 9.546 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.660792, + "p(95)": 29.97076524999998, + "p(99)": 45.86761131999999, + "max": 506.77425, + "avg": 14.651712941877424 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.58712367926269, + "med": 12.603, + "p(95)": 29.897, + "p(99)": 45.80507999999998, + "max": 500.147 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 437173 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "min": 200, + "max": 200, + "value": 200 + } + }, + "data_received": { + "contains": "data", + "values": { + "count": 156071138, + "rate": 4457868.961087603 + }, + "type": "counter" + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "max": 5.983, + "avg": 0.0018166713430798165, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 72591248, + "rate": 2073428.0242501502 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 437173, + "rate": 12486.997738976894 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_failed": { + "values": { + "rate": 0, + "passes": 0, + "fails": 477574 + }, + "type": "rate", + "contains": "default" + }, + "http_req_receiving": { + "values": { + "avg": 0.028498266237226566, + "med": 0.01, + "p(95)": 0.027, + "p(99)": 0.127, + "max": 17.248 + }, + "type": "trend", + "contains": "time" + }, + "http_req_duration{phase:measure}": { + "values": { + "max": 137.96, + "avg": 13.654357071457257, + "med": 12.129, + "p(95)": 26.806399999999982, + "p(99)": 38.543 + }, + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time" + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.58712367926269, + "med": 12.603, + "p(95)": 29.897, + "p(99)": 45.80507999999998, + "max": 500.147 + } + } + }, + "root_group": { + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 477574, + "fails": 0 + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/on/t50_r3/per-second.csv b/evidence/track1/redis-restart/on/t50_r3/per-second.csv new file mode 100644 index 00000000..4713a710 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r3/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,9078,0,19.16,60.40,87.15 +1,10840,0,16.67,44.07,75.27 +2,12855,0,13.76,42.75,82.64 +3,12885,0,13.07,43.88,66.19 +4,15122,0,11.43,36.54,60.40 +5,15847,0,11.33,30.86,46.78 +6,15322,0,12.05,32.28,55.72 +7,15255,0,12.12,33.18,58.55 +8,15412,0,11.93,29.67,45.34 +9,14168,0,13.23,31.57,47.34 +10,10146,0,15.87,69.74,137.96 +11,13607,0,12.87,39.47,68.28 +12,14794,0,12.13,37.53,48.55 +13,14536,0,12.54,35.94,64.93 +14,15328,0,12.01,30.52,57.89 +15,16020,0,11.40,29.38,52.46 +16,14937,0,11.47,35.73,66.18 +17,15219,0,12.34,29.45,50.47 +18,15757,0,11.38,35.08,71.25 +19,15088,0,11.51,35.87,56.89 +20,14197,0,12.17,43.79,64.50 +21,14729,0,12.25,36.71,51.84 +22,16060,0,11.11,31.92,55.45 +23,14841,0,11.68,46.78,89.15 +24,16627,0,10.79,30.23,52.39 +25,16083,0,11.24,31.46,48.93 +26,15985,0,11.47,31.59,50.52 +27,15972,0,11.49,30.92,47.07 +28,16312,0,10.95,30.31,52.09 +29,12438,0,11.96,29.14,46.60 diff --git a/evidence/track1/redis-restart/on/t50_r3/run.json b/evidence/track1/redis-restart/on/t50_r3/run.json new file mode 100644 index 00000000..95677ec4 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r3/run.json @@ -0,0 +1,4 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499536.427604, + "restart_begin": 1791499546.508571, "restart_end": 1791499546.976043, "repeat": 3, + "finished_at": "2026-10-08T22:46:17Z"} diff --git a/evidence/track1/redis-restart/on/t50_r3/samples.csv b/evidence/track1/redis-restart/on/t50_r3/samples.csv new file mode 100644 index 00000000..a7a06257 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r3/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499537.045,0,320833,339, +1791499538.005,0,329456,339, +1791499538.983,0,341273,339, +1791499540.008,0,353607,339, +1791499540.878,0,365921,339, +1791499541.903,0,382641,339, +1791499542.903,0,398134,339, +1791499543.83,0,411675,339, +1791499544.84,0,427801,339, +1791499545.818,0,442717,339, +1791499546.841,0, +1791499547.962,3502,6446,126, +1791499548.96,3502,20517,126, +1791499549.907,3502,34710,126, +1791499550.873,3502,48933,126, +1791499551.883,3502,64701,126, +1791499552.875,3502,80209,126, +1791499553.89,3502,95848,126, +1791499554.798,3502,108876,126, +1791499555.98,3502,126317,126, +1791499556.882,3502,141614,126, +1791499557.901,3502,155643,126, +1791499558.883,3502,170717,126, +1791499559.949,3502,186638,126, +1791499560.824,3502,200061,126, +1791499561.843,3502,216663,126, +1791499562.868,3502,234124,126, +1791499563.816,3502,248157,126, +1791499564.897,3502,266400,126, +1791499565.855,3502,281905,126, diff --git a/evidence/track1/redis-restart/on/t50_r4/k6-summary.json b/evidence/track1/redis-restart/on/t50_r4/k6-summary.json new file mode 100644 index 00000000..79515a88 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r4/k6-summary.json @@ -0,0 +1,245 @@ +{ + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35007.835 + }, + "metrics": { + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 483782, + "fails": 0 + } + }, + "http_req_duration": { + "values": { + "p(95)": 28.261949999999977, + "p(99)": 42.026, + "max": 273.952, + "avg": 14.406687468735786, + "med": 12.765 + }, + "type": "trend", + "contains": "time" + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0050353361637967015, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.029, + "max": 13.265 + } + }, + "data_received": { + "contains": "data", + "values": { + "rate": 4516130.88898528, + "count": 158099965 + }, + "type": "counter" + }, + "http_req_failed{phase:measure}": { + "contains": "default", + "values": { + "fails": 438776, + "rate": 0, + "passes": 0 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate" + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 73534864, + "rate": 2100525.896560013 + } + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "avg": 14.406687468735786, + "med": 12.765, + "p(95)": 28.261949999999977, + "p(99)": 42.026, + "max": 273.952 + }, + "type": "trend" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0.002, + "p(99)": 0.004, + "max": 6.017, + "avg": 0.0025595495491554975, + "med": 0.001 + } + }, + "http_req_waiting": { + "values": { + "p(95)": 28.222, + "p(99)": 42.006, + "max": 273.794, + "avg": 14.381734274942444, + "med": 12.742 + }, + "type": "trend", + "contains": "time" + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.01991785763008978, + "med": 0.009, + "p(95)": 0.025, + "p(99)": 0.095, + "max": 15.029 + } + }, + "http_reqs": { + "values": { + "count": 483782, + "rate": 13819.249319473769 + }, + "type": "counter", + "contains": "default" + }, + "vus_max": { + "values": { + "min": 200, + "max": 200, + "value": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0006676395566598179, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 1.944 + } + }, + "iteration_duration": { + "contains": "time", + "values": { + "p(99)": 42.08894228999999, + "max": 277.88825, + "avg": 14.464418676009002, + "med": 12.8218955, + "p(95)": 28.318070499999997 + }, + "type": "trend" + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 483782, + "rate": 13819.249319473769 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.60831078044378, + "med": 12.336, + "p(95)": 25.784, + "p(99)": 36.31625, + "max": 128.767 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_reqs{phase:measure}": { + "contains": "default", + "values": { + "count": 438776, + "rate": 12533.651395466186 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter" + }, + "http_req_failed": { + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 483782 + }, + "type": "rate" + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "passes": 483782, + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f" + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/on/t50_r4/per-second.csv b/evidence/track1/redis-restart/on/t50_r4/per-second.csv new file mode 100644 index 00000000..e2fca9d8 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r4/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,12920,0,13.70,38.19,78.70 +1,12884,0,13.80,44.19,70.43 +2,13225,0,13.82,41.34,59.20 +3,14550,0,12.22,34.91,48.58 +4,13950,0,13.17,40.97,71.20 +5,14322,0,12.78,31.06,52.69 +6,15653,0,11.57,31.08,58.54 +7,14249,0,12.97,35.38,46.83 +8,16076,0,11.32,31.41,49.70 +9,16580,0,10.75,31.65,47.38 +10,9003,0,18.59,71.46,128.77 +11,13548,0,13.43,35.02,59.23 +12,14259,0,13.01,33.14,69.45 +13,15914,0,11.65,32.05,49.77 +14,14913,0,12.22,33.02,54.14 +15,15119,0,12.00,35.51,53.53 +16,14006,0,13.42,32.26,47.92 +17,14872,0,12.58,31.73,55.27 +18,15628,0,11.66,31.01,48.98 +19,14724,0,12.67,29.33,39.01 +20,13938,0,13.39,34.22,53.39 +21,14637,0,12.64,33.75,54.57 +22,13808,0,13.21,39.53,68.36 +23,17243,0,10.41,29.20,56.08 +24,15104,0,11.52,39.67,69.29 +25,15793,0,11.48,30.73,55.36 +26,14274,0,12.92,35.80,83.75 +27,16228,0,11.18,29.63,49.05 +28,15600,0,11.88,31.54,69.40 +29,13573,0,10.35,30.48,56.17 diff --git a/evidence/track1/redis-restart/on/t50_r4/run.json b/evidence/track1/redis-restart/on/t50_r4/run.json new file mode 100644 index 00000000..2ade7542 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r4/run.json @@ -0,0 +1,4 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499655.0228858, + "restart_begin": 1791499665.094867, "restart_end": 1791499665.5880342, "repeat": 4, + "finished_at": "2026-10-08T22:48:16Z"} diff --git a/evidence/track1/redis-restart/on/t50_r4/samples.csv b/evidence/track1/redis-restart/on/t50_r4/samples.csv new file mode 100644 index 00000000..b60fdd54 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r4/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499655.509,0,337954,375, +1791499656.468,0,349785,375, +1791499657.573,0,363693,375, +1791499658.432,0,375907,375, +1791499659.421,0,391136,375, +1791499660.49,0,405442,375, +1791499661.425,0,419783,375, +1791499662.393,0,434058,375, +1791499663.495,0,451000,375, +1791499664.55,0,467927,375, +1791499665.652,0,0,0, +1791499666.483,3106,6214,171, +1791499667.48,3106,19219,171, +1791499668.415,3106,33856,171, +1791499669.474,3106,50843,171, +1791499670.499,3106,65414,171, +1791499671.381,3106,78125,171, +1791499672.408,3106,93040,171, +1791499673.404,3106,107728,171, +1791499674.422,3106,123963,171, +1791499675.39,3106,137972,171, +1791499676.471,3106,153819,171, +1791499677.452,3106,166548,171, +1791499678.478,3106,182849,171, +1791499679.434,3106,198741,171, +1791499680.573,3106,216121,171, +1791499681.428,3106,228874,171, +1791499682.446,3106,243413,171, +1791499683.431,3106,259265,171, +1791499684.478,3106,276241,171, diff --git a/evidence/track1/redis-restart/on/t50_r5/k6-summary.json b/evidence/track1/redis-restart/on/t50_r5/k6-summary.json new file mode 100644 index 00000000..df84aef2 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r5/k6-summary.json @@ -0,0 +1,245 @@ +{ + "metrics": { + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 259.572, + "avg": 14.5746728930318, + "med": 12.802, + "p(95)": 29.272, + "p(99)": 44.59939999999999 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 478021 + } + }, + "http_req_connecting": { + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 1.825, + "avg": 0.0006622198606337379 + }, + "type": "trend", + "contains": "time" + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 478021, + "fails": 0 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.638287244112455, + "med": 12.865459, + "p(95)": 29.335375, + "p(99)": 44.66789159999999, + "max": 263.006666 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 156217124, + "rate": 4462552.703126373 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 14.5746728930318, + "med": 12.802, + "p(95)": 29.272, + "p(99)": 44.59939999999999, + "max": 259.572 + } + }, + "vus": { + "values": { + "min": 200, + "max": 200, + "value": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.72225077932451, + "med": 12.311, + "p(95)": 26.562, + "p(99)": 38.479359999999986, + "max": 153.453 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 434992 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "iterations": { + "values": { + "count": 478021, + "rate": 13655.31416198119 + }, + "type": "counter", + "contains": "default" + }, + "http_req_sending": { + "contains": "time", + "values": { + "max": 16.4, + "avg": 0.00560376217780366, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.029 + }, + "type": "trend" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 44.573399999999985, + "max": 259.544, + "avg": 14.54586307923653, + "med": 12.777, + "p(95)": 29.225 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 478021, + "rate": 13655.31416198119 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 72659192, + "rate": 2075607.752621141 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "rate": 12426.132780669723, + "count": 434992 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "max": 16.314, + "avg": 0.0232060516169539, + "med": 0.009, + "p(95)": 0.026, + "p(99)": 0.101 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0 + } + }, + "http_req_blocked": { + "contains": "time", + "values": { + "avg": 0.0026765309473631587, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 7.913 + }, + "type": "trend" + }, + "vus_max": { + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge" + } + }, + "root_group": { + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "passes": 478021, + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f" + } + ], + "name": "", + "path": "" + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35006.225 + } +} \ No newline at end of file diff --git a/evidence/track1/redis-restart/on/t50_r5/per-second.csv b/evidence/track1/redis-restart/on/t50_r5/per-second.csv new file mode 100644 index 00000000..ca5b86f5 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r5/per-second.csv @@ -0,0 +1,31 @@ +second,requests,non_200,p50_ms,p99_ms,max_ms +0,11648,0,15.96,39.52,70.54 +1,12687,0,14.35,36.37,60.09 +2,14015,0,13.19,32.34,51.76 +3,9914,0,16.91,67.62,101.70 +4,13194,0,13.61,43.19,65.23 +5,15501,0,11.82,31.39,66.64 +6,14890,0,11.57,40.82,75.62 +7,15381,0,10.86,43.81,78.10 +8,14354,0,12.32,36.76,59.65 +9,14730,0,12.03,37.72,55.50 +10,9487,0,15.04,88.56,153.45 +11,13277,0,13.82,36.56,76.60 +12,14575,0,12.81,31.33,49.15 +13,14792,0,12.32,33.19,52.85 +14,14507,0,12.71,31.72,50.98 +15,15867,0,11.17,33.27,58.72 +16,14892,0,11.98,38.11,64.65 +17,15417,0,11.76,32.26,49.95 +18,15166,0,12.22,31.21,47.60 +19,16696,0,10.79,32.02,60.49 +20,15547,0,11.71,31.00,66.98 +21,15964,0,11.83,28.24,68.65 +22,16691,0,10.83,28.69,51.63 +23,13085,0,14.24,36.87,80.86 +24,15758,0,11.66,31.48,52.94 +25,17297,0,9.93,33.31,68.17 +26,14752,0,12.52,32.08,50.36 +27,14718,0,12.44,34.00,57.01 +28,15608,0,11.60,31.39,58.12 +29,12164,0,11.30,29.76,48.71 diff --git a/evidence/track1/redis-restart/on/t50_r5/run.json b/evidence/track1/redis-restart/on/t50_r5/run.json new file mode 100644 index 00000000..fe328108 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r5/run.json @@ -0,0 +1,4 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "measure_start": 1791499773.790411, + "restart_begin": 1791499783.8553238, "restart_end": 1791499784.422722, "repeat": 5, + "finished_at": "2026-10-08T22:50:14Z"} diff --git a/evidence/track1/redis-restart/on/t50_r5/samples.csv b/evidence/track1/redis-restart/on/t50_r5/samples.csv new file mode 100644 index 00000000..70463bf1 --- /dev/null +++ b/evidence/track1/redis-restart/on/t50_r5/samples.csv @@ -0,0 +1,31 @@ +unix_time,session_lookups_total,redis_hits_total,redis_misses_total, +1791499774.292,0,336306,186, +1791499775.347,0,349366,186, +1791499776.267,0,360827,186, +1791499777.427,0,374239,186, +1791499778.2,0,383571,186, +1791499779.174,0,397633,186, +1791499780.29,0,413759,186, +1791499781.164,0,427893,186, +1791499782.295,0,444982,186, +1791499783.301,0,459384,186, +1791499784.491,0,0,0, +1791499785.335,3805,5850,63, +1791499786.202,3805,17924,63, +1791499787.278,3805,33720,63, +1791499788.163,3805,46375,63, +1791499789.167,3805,61286,63, +1791499790.242,3805,77877,63, +1791499791.137,3805,91476,63, +1791499792.193,3805,107851,63, +1791499793.231,3805,124182,63, +1791499794.198,3805,140428,63, +1791499795.247,3805,157840,63, +1791499796.218,3805,172479,63, +1791499797.218,3805,188444,63, +1791499798.255,3805,202652,63, +1791499799.234,3805,219289,63, +1791499800.238,3805,234121,63, +1791499801.175,3805,248479,63, +1791499802.165,3805,263347,63, +1791499803.206,3805,280493,63, diff --git a/evidence/track1/stampede-runs.csv b/evidence/track1/stampede-runs.csv new file mode 100644 index 00000000..d25739d9 --- /dev/null +++ b/evidence/track1/stampede-runs.csv @@ -0,0 +1,15 @@ +variant,single_flight,tokens,vus,warmup_s,duration_s,flush_interval_s,flushes,repeat,finished_at,requests,failed,p50,p95,p99,max,sessions,users,total_sql,misses,hits +off,False,10,200,5,30,1,30,1,2026-10-08T22:33:14Z,483225,0,11.438,22.678,31.019,83.901,3138,482439,485580,3138,477069 +off,False,10,200,5,30,1,30,2,2026-10-08T22:38:24Z,459671,0,11.894,24.48249999999998,34.759299999999996,132.111,2893,458894,461790,2893,453216 +off,False,10,200,5,30,1,30,3,2026-10-08T22:43:33Z,471574,0,11.711,23.41434999999998,31.976269999999996,82.79,3500,470505,474008,3500,464462 +off,False,50,200,5,30,0,0,1,2026-10-08T22:51:03Z,478965,0,11.461,23.26479999999998,32.12,85.924,0,477949,477952,0,475982 +off,False,50,200,5,30,1,30,1,2026-10-08T22:31:38Z,488109,0,11.229,22.969,31.842919999999996,85.686,4689,487009,491701,4689,479915 +off,False,50,200,5,30,1,30,2,2026-10-08T22:36:49Z,495366,0,11.095,22.443749999999977,31.58469999999999,77.079,4622,494677,499302,4622,487510 +off,False,50,200,5,30,1,30,3,2026-10-08T22:41:57Z,488040,0,11.269,22.938049999999976,31.582,88.5,4651,487431,492085,4651,480518 +on,True,10,200,5,30,1,30,1,2026-10-08T22:34:01Z,466931,0,11.79,23.741,32.65839999999999,86.517,291,466489,466783,4037,460346 +on,True,10,200,5,30,1,30,2,2026-10-08T22:39:11Z,471573,0,11.828,23.076,31.163279999999997,132.753,292,469849,470144,4069,463418 +on,True,10,200,5,30,1,30,3,2026-10-08T22:44:19Z,475444,0,11.686,22.986,31.554569999999995,75.303,291,474225,474519,3979,468356 +on,True,50,200,5,30,0,0,1,2026-10-08T22:51:51Z,487518,0,11.383,22.381,30.630829999999996,87.904,0,486661,486664,0,484721 +on,True,50,200,5,30,1,30,1,2026-10-08T22:32:27Z,487193,0,11.453,22.145,29.846,84.089,1451,485556,487010,4653,478297 +on,True,50,200,5,30,1,30,2,2026-10-08T22:37:37Z,483185,0,11.283,23.079,31.949,123.271,1450,481934,483387,4390,474193 +on,True,50,200,5,30,1,30,3,2026-10-08T22:42:46Z,482887,0,11.483,22.571,29.937559999999984,71.529,1451,482275,483729,4777,475235 diff --git a/evidence/track1/stampede/off/t10_f1_r1/k6-summary.json b/evidence/track1/stampede/off/t10_f1_r1/k6-summary.json new file mode 100644 index 00000000..1ce5f828 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 523785, + "fails": 0 + } + ], + "name": "" + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35010.924 + }, + "metrics": { + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.314028567064804, + "med": 11.856, + "p(95)": 25.759799999999977, + "p(99)": 40.16, + "max": 316.799 + } + }, + "http_req_failed{phase:measure}": { + "contains": "default", + "values": { + "fails": 483225, + "rate": 0, + "passes": 0 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate" + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 170753910, + "rate": 4877160.9112630095 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "rate": 2274013.676417109, + "count": 79615320 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 40.230221439999994, + "max": 323.026917, + "avg": 13.359666055358604, + "med": 11.898084, + "p(95)": 25.80697539999999 + } + }, + "http_req_receiving": { + "values": { + "med": 0.007, + "p(95)": 0.023, + "p(99)": 0.068, + "max": 9.83, + "avg": 0.019716217531957726 + }, + "type": "trend", + "contains": "time" + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "fails": 0, + "rate": 1, + "passes": 523785 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "max": 316.778, + "avg": 13.29003580476757, + "med": 11.835, + "p(95)": 25.726, + "p(99)": 40.129 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "max": 83.901, + "avg": 12.36781745770601, + "med": 11.438, + "p(95)": 22.678, + "p(99)": 31.019 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 25.759799999999977, + "p(99)": 40.16, + "max": 316.799, + "avg": 13.314028567064804, + "med": 11.856 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 523785, + "rate": 14960.616292217823 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 523785, + "rate": 14960.616292217823 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.003, + "max": 6.854, + "avg": 0.002945817463251851, + "med": 0.001, + "p(95)": 0.002 + } + }, + "http_req_tls_handshaking": { + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + }, + "type": "trend" + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_req_sending": { + "values": { + "avg": 0.004276544765483331, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.017, + "max": 9.021 + }, + "type": "trend", + "contains": "time" + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.461, + "avg": 0.0006732609754002117 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 523785 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "count": 483225, + "rate": 13802.120732374842 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t10_f1_r1/redis-stats.txt b/evidence/track1/stampede/off/t10_f1_r1/redis-stats.txt new file mode 100644 index 00000000..d352c8d9 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:477069 +keyspace_misses:3138 diff --git a/evidence/track1/stampede/off/t10_f1_r1/run.json b/evidence/track1/stampede/off/t10_f1_r1/run.json new file mode 100644 index 00000000..4e39cb79 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 1, "finished_at": "2026-10-08T22:33:14Z"} diff --git a/evidence/track1/stampede/off/t10_f1_r1/sql-calls.csv b/evidence/track1/stampede/off/t10_f1_r1/sql-calls.csv new file mode 100644 index 00000000..a40f1f68 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r1/sql-calls.csv @@ -0,0 +1 @@ +3138,482439,485580 diff --git a/evidence/track1/stampede/off/t10_f1_r1/top-queries.txt b/evidence/track1/stampede/off/t10_f1_r1/top-queries.txt new file mode 100644 index 00000000..4524305e --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r1/top-queries.txt @@ -0,0 +1,3 @@ +482439|8123.4|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +3138|55.7|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t10_f1_r2/k6-summary.json b/evidence/track1/stampede/off/t10_f1_r2/k6-summary.json new file mode 100644 index 00000000..2fa716fa --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35008.465 + }, + "metrics": { + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.971811645793062, + "med": 12.357583, + "p(95)": 27.556191899999998, + "p(99)": 43.548467719999984, + "max": 301.066042 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "min": 200, + "max": 200, + "value": 200 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 163272210, + "rate": 4663792.3142302865 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "count": 459671, + "rate": 13130.281490490943 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 500835 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0.002, + "p(99)": 0.004, + "max": 11.55, + "avg": 0.0025598570387252726, + "med": 0.001 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 459671, + "rate": 0 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 500835, + "rate": 14306.111393344438 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 76126920, + "rate": 2174528.9317883546 + } + }, + "checks": { + "contains": "default", + "values": { + "rate": 1, + "passes": 500835, + "fails": 0 + }, + "type": "rate" + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.922364649036203, + "med": 12.311, + "p(95)": 27.503, + "p(99)": 43.46629999999998, + "max": 298.063 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 500835, + "rate": 14306.111393344438 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "max": 14.903, + "avg": 0.01962653967870299, + "med": 0.008, + "p(95)": 0.023, + "p(99)": 0.075 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 43.46629999999998, + "max": 298.063, + "avg": 13.922364649036203, + "med": 12.311, + "p(95)": 27.503 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "max": 2.199, + "avg": 0.0006517815248534946, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0.008, + "p(99)": 0.02, + "max": 10.114, + "avg": 0.004445907334733093, + "med": 0.003 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.898292202022757, + "med": 12.288, + "p(95)": 27.456299999999978, + "p(99)": 43.44193999999996, + "max": 297.729 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.999771181997382, + "med": 11.894, + "p(95)": 24.48249999999998, + "p(99)": 34.759299999999996, + "max": 132.111 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 500835, + "fails": 0 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t10_f1_r2/redis-stats.txt b/evidence/track1/stampede/off/t10_f1_r2/redis-stats.txt new file mode 100644 index 00000000..f0c5132c --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r2/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:453216 +keyspace_misses:2893 diff --git a/evidence/track1/stampede/off/t10_f1_r2/run.json b/evidence/track1/stampede/off/t10_f1_r2/run.json new file mode 100644 index 00000000..7f1ff5c9 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r2/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 2, "finished_at": "2026-10-08T22:38:24Z"} diff --git a/evidence/track1/stampede/off/t10_f1_r2/sql-calls.csv b/evidence/track1/stampede/off/t10_f1_r2/sql-calls.csv new file mode 100644 index 00000000..b85d5e72 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r2/sql-calls.csv @@ -0,0 +1 @@ +2893,458894,461790 diff --git a/evidence/track1/stampede/off/t10_f1_r2/top-queries.txt b/evidence/track1/stampede/off/t10_f1_r2/top-queries.txt new file mode 100644 index 00000000..819dc518 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r2/top-queries.txt @@ -0,0 +1,3 @@ +458894|8109.7|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +2893|52.2|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t10_f1_r3/k6-summary.json b/evidence/track1/stampede/off/t10_f1_r3/k6-summary.json new file mode 100644 index 00000000..a190b0d1 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "groups": [], + "checks": [ + { + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 512441, + "fails": 0, + "name": "status is 200" + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e" + }, + "options": { + "summaryTimeUnit": "", + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ] + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35009.332 + }, + "metrics": { + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 512441 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 512441, + "fails": 0 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "fails": 471574, + "rate": 0, + "passes": 0 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.585310328408484, + "med": 12.112, + "p(95)": 26.432, + "p(99)": 40.103, + "max": 247.074 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.609255598205488, + "med": 12.134, + "p(95)": 26.475, + "p(99)": 40.12, + "max": 247.095 + } + }, + "http_reqs{phase:measure}": { + "contains": "default", + "values": { + "count": 471574, + "rate": 13469.95138324833 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter" + }, + "http_req_connecting": { + "contains": "time", + "values": { + "avg": 0.0005967067428250276, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 1.851 + }, + "type": "trend" + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 512441, + "rate": 14637.268714524458 + } + }, + "vus": { + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.004, + "max": 9.416, + "avg": 0.002307846171539745, + "med": 0.001, + "p(95)": 0.002 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "rate": 14637.268714524458, + "count": 512441 + } + }, + "data_sent": { + "contains": "data", + "values": { + "count": 77891032, + "rate": 2224864.844607718 + }, + "type": "counter" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_receiving": { + "contains": "time", + "values": { + "avg": 0.01972432728837417, + "med": 0.007, + "p(95)": 0.023, + "p(99)": 0.063, + "max": 11.007 + }, + "type": "trend" + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.656716256718695, + "med": 12.17875, + "p(95)": 26.533416, + "p(99)": 40.185408399999986, + "max": 250.307292 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.004220942508480799, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.017, + "max": 10.49 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 31.976269999999996, + "max": 82.79, + "avg": 12.671386497135497, + "med": 11.711, + "p(95)": 23.41434999999998 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "max": 247.095, + "avg": 13.609255598205488, + "med": 12.134, + "p(95)": 26.475, + "p(99)": 40.12 + } + }, + "data_received": { + "values": { + "count": 167055766, + "rate": 4771749.600934974 + }, + "type": "counter", + "contains": "data" + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t10_f1_r3/redis-stats.txt b/evidence/track1/stampede/off/t10_f1_r3/redis-stats.txt new file mode 100644 index 00000000..e163c159 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r3/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:464462 +keyspace_misses:3500 diff --git a/evidence/track1/stampede/off/t10_f1_r3/run.json b/evidence/track1/stampede/off/t10_f1_r3/run.json new file mode 100644 index 00000000..896e309a --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r3/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 3, "finished_at": "2026-10-08T22:43:33Z"} diff --git a/evidence/track1/stampede/off/t10_f1_r3/sql-calls.csv b/evidence/track1/stampede/off/t10_f1_r3/sql-calls.csv new file mode 100644 index 00000000..0ea50942 --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r3/sql-calls.csv @@ -0,0 +1 @@ +3500,470505,474008 diff --git a/evidence/track1/stampede/off/t10_f1_r3/top-queries.txt b/evidence/track1/stampede/off/t10_f1_r3/top-queries.txt new file mode 100644 index 00000000..620100da --- /dev/null +++ b/evidence/track1/stampede/off/t10_f1_r3/top-queries.txt @@ -0,0 +1,3 @@ +470505|8002.9|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +3500|56.9|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t50_f0_r1/k6-summary.json b/evidence/track1/stampede/off/t50_f0_r1/k6-summary.json new file mode 100644 index 00000000..8fa52aad --- /dev/null +++ b/evidence/track1/stampede/off/t50_f0_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "metrics": { + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 25.801, + "p(99)": 39.69448, + "max": 228.629, + "avg": 13.349152643901954, + "med": 11.866 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_receiving": { + "values": { + "max": 16.947, + "avg": 0.020844683575970722, + "med": 0.007, + "p(95)": 0.022, + "p(99)": 0.057 + }, + "type": "trend", + "contains": "time" + }, + "vus_max": { + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + }, + "type": "gauge" + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "avg": 13.349152643901954, + "med": 11.866, + "p(95)": 25.801, + "p(99)": 39.69448, + "max": 228.629 + }, + "type": "trend" + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 170705149, + "rate": 4875918.584498691 + } + }, + "iteration_duration": { + "values": { + "avg": 13.396721453147958, + "med": 11.911416, + "p(95)": 25.851641999999995, + "p(99)": 39.75101315999998, + "max": 232.246958 + }, + "type": "trend", + "contains": "time" + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 522353, + "rate": 14920.175022773594 + } + }, + "http_req_failed{phase:measure}": { + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 478965 + } + }, + "http_req_connecting": { + "values": { + "avg": 0.0005988651352629358, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.072 + }, + "type": "trend", + "contains": "time" + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "fails": 0, + "rate": 1, + "passes": 522353 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 79397656, + "rate": 2267866.6034615864 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0023249277787053277, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 5.53 + } + }, + "http_req_tls_handshaking": { + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + }, + "type": "trend", + "contains": "time" + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.475792314678598, + "med": 11.461, + "p(95)": 23.26479999999998, + "p(99)": 32.12, + "max": 85.924 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_waiting": { + "contains": "time", + "values": { + "p(95)": 25.767, + "p(99)": 39.68043999999999, + "max": 228.529, + "avg": 13.323960245274511, + "med": 11.84 + }, + "type": "trend" + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.017, + "max": 8.827, + "avg": 0.004347715050915911, + "med": 0.003, + "p(95)": 0.008 + } + }, + "http_reqs{phase:measure}": { + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default", + "values": { + "count": 478965, + "rate": 13680.86644430635 + } + }, + "http_req_failed": { + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 522353 + }, + "type": "rate" + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 522353, + "rate": 14920.175022773594 + } + } + }, + "root_group": { + "checks": [ + { + "passes": 522353, + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f" + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + }, + "options": { + "summaryTimeUnit": "", + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ] + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35009.844 + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t50_f0_r1/redis-stats.txt b/evidence/track1/stampede/off/t50_f0_r1/redis-stats.txt new file mode 100644 index 00000000..55c9fca5 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f0_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:475982 +keyspace_misses:0 diff --git a/evidence/track1/stampede/off/t50_f0_r1/run.json b/evidence/track1/stampede/off/t50_f0_r1/run.json new file mode 100644 index 00000000..db676349 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f0_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 0, "flushes": 0, + "repeat": 1, "finished_at": "2026-10-08T22:51:03Z"} diff --git a/evidence/track1/stampede/off/t50_f0_r1/sql-calls.csv b/evidence/track1/stampede/off/t50_f0_r1/sql-calls.csv new file mode 100644 index 00000000..c1ea6c1f --- /dev/null +++ b/evidence/track1/stampede/off/t50_f0_r1/sql-calls.csv @@ -0,0 +1 @@ +0,477949,477952 diff --git a/evidence/track1/stampede/off/t50_f0_r1/top-queries.txt b/evidence/track1/stampede/off/t50_f0_r1/top-queries.txt new file mode 100644 index 00000000..31738e80 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f0_r1/top-queries.txt @@ -0,0 +1,2 @@ +477949|8265.3|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t50_f1_r1/k6-summary.json b/evidence/track1/stampede/off/t50_f1_r1/k6-summary.json new file mode 100644 index 00000000..79d3415e --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "metrics": { + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 26.006699999999977, + "p(99)": 38.50793999999995, + "max": 238.969, + "avg": 13.131629597681103, + "med": 11.648 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 530947, + "rate": 15167.316341101003 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0.002, + "p(99)": 0.004, + "max": 7.252, + "avg": 0.002755508553564804, + "med": 0.001 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.178676683733109, + "med": 11.689666, + "p(95)": 26.057599999999987, + "p(99)": 38.5775255, + "max": 242.992042 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.239011985028089, + "med": 11.229, + "p(95)": 22.969, + "p(99)": 31.842919999999996, + "max": 85.686 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "fails": 488109, + "rate": 0, + "passes": 0 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "med": 0.007, + "p(95)": 0.023, + "p(99)": 0.079, + "max": 19.329, + "avg": 0.020784202566305435 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 530947, + "rate": 15167.316341101003 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 3.711, + "avg": 0.000806897863628573 + } + }, + "data_sent": { + "values": { + "count": 80703944, + "rate": 2305432.0838473523 + }, + "type": "counter", + "contains": "data" + }, + "vus": { + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge", + "contains": "default" + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 530947, + "fails": 0 + } + }, + "http_reqs{phase:measure}": { + "values": { + "count": 488109, + "rate": 13943.583091981816 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default" + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.004504843232927631, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.02, + "max": 11.872 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 530947, + "rate": 0 + } + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "p(95)": 26.006699999999977, + "p(99)": 38.50793999999995, + "max": 238.969, + "avg": 13.131629597681103, + "med": 11.648 + }, + "type": "trend" + }, + "http_req_waiting": { + "values": { + "avg": 13.10634055188201, + "med": 11.62, + "p(95)": 25.974, + "p(99)": 38.39254, + "max": 237.769 + }, + "type": "trend", + "contains": "time" + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 173513417, + "rate": 4956677.192006684 + } + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 530947, + "fails": 0 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdErrTTY": false, + "testRunDurationMs": 35005.995, + "isStdOutTTY": false + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t50_f1_r1/redis-stats.txt b/evidence/track1/stampede/off/t50_f1_r1/redis-stats.txt new file mode 100644 index 00000000..6ff6c1df --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:479915 +keyspace_misses:4689 diff --git a/evidence/track1/stampede/off/t50_f1_r1/run.json b/evidence/track1/stampede/off/t50_f1_r1/run.json new file mode 100644 index 00000000..320bf09a --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 1, "finished_at": "2026-10-08T22:31:38Z"} diff --git a/evidence/track1/stampede/off/t50_f1_r1/sql-calls.csv b/evidence/track1/stampede/off/t50_f1_r1/sql-calls.csv new file mode 100644 index 00000000..8153a609 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r1/sql-calls.csv @@ -0,0 +1 @@ +4689,487009,491701 diff --git a/evidence/track1/stampede/off/t50_f1_r1/top-queries.txt b/evidence/track1/stampede/off/t50_f1_r1/top-queries.txt new file mode 100644 index 00000000..d3245cc0 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r1/top-queries.txt @@ -0,0 +1,3 @@ +487009|7930.1|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +4689|77.4|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t50_f1_r2/k6-summary.json b/evidence/track1/stampede/off/t50_f1_r2/k6-summary.json new file mode 100644 index 00000000..51388785 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 542956, + "fails": 0 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "testRunDurationMs": 35009.556, + "isStdOutTTY": false, + "isStdErrTTY": false + }, + "metrics": { + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.002948835633069887, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 9.56 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 255.710333, + "avg": 12.887780675263096, + "med": 11.551042, + "p(95)": 24.871780999999995, + "p(99)": 36.5859087 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 542956, + "rate": 15508.794227496057 + } + }, + "data_received": { + "contains": "data", + "values": { + "rate": 5067348.669031964, + "count": 177405627 + }, + "type": "counter" + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 542956 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.004573657902286502, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.018, + "max": 8.708 + } + }, + "vus": { + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge" + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 542956, + "rate": 15508.794227496057 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.816202102932435, + "med": 11.4825, + "p(95)": 24.775, + "p(99)": 36.503449999999994, + "max": 247.759 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 542956, + "fails": 0 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 24.823249999999977, + "p(99)": 36.527, + "max": 247.811, + "avg": 12.840207847413033, + "med": 11.507 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 247.811, + "avg": 12.840207847413033, + "med": 11.507, + "p(95)": 24.823249999999977, + "p(99)": 36.527 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 495366 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "med": 0.007, + "p(95)": 0.022, + "p(99)": 0.067, + "max": 14.303, + "avg": 0.01943208657787687 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0 + } + }, + "http_req_connecting": { + "values": { + "p(95)": 0, + "p(99)": 0, + "max": 4.132, + "avg": 0.0007799103426428663, + "med": 0 + }, + "type": "trend", + "contains": "time" + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 495366, + "rate": 14149.45108129906 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "rate": 2357336.7225794005, + "count": 82529312 + } + }, + "http_req_duration{phase:measure}": { + "values": { + "avg": 12.06067456183917, + "med": 11.095, + "p(95)": 22.443749999999977, + "p(99)": 31.58469999999999, + "max": 77.079 + }, + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time" + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t50_f1_r2/redis-stats.txt b/evidence/track1/stampede/off/t50_f1_r2/redis-stats.txt new file mode 100644 index 00000000..eb6f4f12 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r2/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:487510 +keyspace_misses:4622 diff --git a/evidence/track1/stampede/off/t50_f1_r2/run.json b/evidence/track1/stampede/off/t50_f1_r2/run.json new file mode 100644 index 00000000..06545f7c --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r2/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 2, "finished_at": "2026-10-08T22:36:49Z"} diff --git a/evidence/track1/stampede/off/t50_f1_r2/sql-calls.csv b/evidence/track1/stampede/off/t50_f1_r2/sql-calls.csv new file mode 100644 index 00000000..3531f2ea --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r2/sql-calls.csv @@ -0,0 +1 @@ +4622,494677,499302 diff --git a/evidence/track1/stampede/off/t50_f1_r2/top-queries.txt b/evidence/track1/stampede/off/t50_f1_r2/top-queries.txt new file mode 100644 index 00000000..5d48d3c8 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r2/top-queries.txt @@ -0,0 +1,3 @@ +494677|8221.1|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +4622|81.6|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/off/t50_f1_r3/k6-summary.json b/evidence/track1/stampede/off/t50_f1_r3/k6-summary.json new file mode 100644 index 00000000..e92d9b22 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "options": { + "summaryTimeUnit": "", + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ] + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35007.435 + }, + "metrics": { + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.269, + "p(95)": 22.938049999999976, + "p(99)": 31.582, + "max": 88.5, + "avg": 12.246399012376388 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_duration": { + "values": { + "avg": 13.073672586429906, + "med": 11.702, + "p(95)": 25.403499999999976, + "p(99)": 36.9679, + "max": 295.145 + }, + "type": "trend", + "contains": "time" + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 488040 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "fails": 533411, + "rate": 0, + "passes": 0 + } + }, + "http_reqs{phase:measure}": { + "values": { + "count": 488040, + "rate": 13941.038525101882 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter", + "contains": "default" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 25.371499999999976, + "p(99)": 36.92, + "max": 294.793, + "avg": 13.050688157912441, + "med": 11.679 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "max": 10.762, + "avg": 0.004443663516486211, + "med": 0.002, + "p(95)": 0.008, + "p(99)": 0.018 + } + }, + "http_reqs": { + "values": { + "count": 533411, + "rate": 15237.077495109254 + }, + "type": "counter", + "contains": "default" + }, + "data_sent": { + "values": { + "rate": 2316035.7792566065, + "count": 81078472 + }, + "type": "counter", + "contains": "data" + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 533411, + "rate": 15237.077495109254 + } + }, + "http_req_duration{expected_response:true}": { + "contains": "time", + "values": { + "avg": 13.073672586429906, + "med": 11.702, + "p(95)": 25.403499999999976, + "p(99)": 36.9679, + "max": 295.145 + }, + "type": "trend" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 174318595, + "rate": 4979473.503271519 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 299.65925, + "avg": 13.118099390438598, + "med": 11.74175, + "p(95)": 25.451791499999995, + "p(99)": 37.03097909999999 + } + }, + "vus": { + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge" + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.067, + "max": 13.888, + "avg": 0.018540765001085605, + "med": 0.007, + "p(95)": 0.022 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 533411, + "fails": 0 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "max": 11.772, + "avg": 0.002889177388523168, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 6.182, + "avg": 0.0008526427089055152, + "med": 0, + "p(95)": 0 + } + } + }, + "root_group": { + "checks": [ + { + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 533411, + "fails": 0, + "name": "status is 200" + } + ], + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [] + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/off/t50_f1_r3/redis-stats.txt b/evidence/track1/stampede/off/t50_f1_r3/redis-stats.txt new file mode 100644 index 00000000..7e8024ce --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r3/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:480518 +keyspace_misses:4651 diff --git a/evidence/track1/stampede/off/t50_f1_r3/run.json b/evidence/track1/stampede/off/t50_f1_r3/run.json new file mode 100644 index 00000000..acba879b --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r3/run.json @@ -0,0 +1,3 @@ +{"variant": "off", "single_flight": false, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 3, "finished_at": "2026-10-08T22:41:57Z"} diff --git a/evidence/track1/stampede/off/t50_f1_r3/sql-calls.csv b/evidence/track1/stampede/off/t50_f1_r3/sql-calls.csv new file mode 100644 index 00000000..6b503612 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r3/sql-calls.csv @@ -0,0 +1 @@ +4651,487431,492085 diff --git a/evidence/track1/stampede/off/t50_f1_r3/top-queries.txt b/evidence/track1/stampede/off/t50_f1_r3/top-queries.txt new file mode 100644 index 00000000..9ae52bd0 --- /dev/null +++ b/evidence/track1/stampede/off/t50_f1_r3/top-queries.txt @@ -0,0 +1,3 @@ +487431|8221.8|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +4651|83.6|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t10_f1_r1/k6-summary.json b/evidence/track1/stampede/on/t10_f1_r1/k6-summary.json new file mode 100644 index 00000000..ecf43654 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 502593, + "fails": 0 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "testRunDurationMs": 35009.588, + "isStdOutTTY": false, + "isStdErrTTY": false + }, + "metrics": { + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0038406782426092705, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.016, + "max": 5.29 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 502593, + "rate": 0 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0.002, + "p(99)": 0.003, + "max": 5.494, + "avg": 0.0025738798590311833, + "med": 0.001 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.01312351146955445, + "med": 0.007, + "p(95)": 0.022, + "p(99)": 0.046, + "max": 7.263 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 466931 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "passes": 502593, + "fails": 0, + "rate": 1 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.923763175225112, + "med": 12.24475, + "p(95)": 27.308300199999994, + "p(99)": 42.639930639999996, + "max": 510.789209 + } + }, + "http_reqs": { + "values": { + "rate": 14355.867312691596, + "count": 502593 + }, + "type": "counter", + "contains": "default" + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 76394136, + "rate": 2182091.831529123 + } + }, + "http_req_duration{phase:measure}": { + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time", + "values": { + "avg": 12.801811524614509, + "med": 11.79, + "p(95)": 23.741, + "p(99)": 32.65839999999999, + "max": 86.517 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.880014506767521, + "med": 12.204, + "p(95)": 27.259, + "p(99)": 42.58631999999998, + "max": 506.679 + } + }, + "vus_max": { + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.863050317055828, + "med": 12.186, + "p(95)": 27.239, + "p(99)": 42.570159999999994, + "max": 506.634 + } + }, + "data_received": { + "contains": "data", + "values": { + "count": 163845318, + "rate": 4680012.743937461 + }, + "type": "counter" + }, + "http_reqs{phase:measure}": { + "contains": "default", + "values": { + "count": 466931, + "rate": 13337.232074824758 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter" + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 2.303, + "avg": 0.0006501861347054176, + "med": 0, + "p(95)": 0 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 502593, + "rate": 14355.867312691596 + } + }, + "vus": { + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge" + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 27.259, + "p(99)": 42.58631999999998, + "max": 506.679, + "avg": 13.880014506767521, + "med": 12.204 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t10_f1_r1/redis-stats.txt b/evidence/track1/stampede/on/t10_f1_r1/redis-stats.txt new file mode 100644 index 00000000..3d788058 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:460346 +keyspace_misses:4037 diff --git a/evidence/track1/stampede/on/t10_f1_r1/run.json b/evidence/track1/stampede/on/t10_f1_r1/run.json new file mode 100644 index 00000000..886e7649 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 1, "finished_at": "2026-10-08T22:34:01Z"} diff --git a/evidence/track1/stampede/on/t10_f1_r1/sql-calls.csv b/evidence/track1/stampede/on/t10_f1_r1/sql-calls.csv new file mode 100644 index 00000000..5e35f128 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r1/sql-calls.csv @@ -0,0 +1 @@ +291,466489,466783 diff --git a/evidence/track1/stampede/on/t10_f1_r1/top-queries.txt b/evidence/track1/stampede/on/t10_f1_r1/top-queries.txt new file mode 100644 index 00000000..2f488a3e --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r1/top-queries.txt @@ -0,0 +1,3 @@ +466489|7988.2|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +291|9.2|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t10_f1_r2/k6-summary.json b/evidence/track1/stampede/on/t10_f1_r2/k6-summary.json new file mode 100644 index 00000000..118c0d31 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 514679, + "fails": 35 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdErrTTY": false, + "testRunDurationMs": 35009.058, + "isStdOutTTY": false + }, + "metrics": { + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "max": 132.753, + "avg": 12.673280401973658, + "med": 11.828, + "p(95)": 23.076, + "p(99)": 31.163279999999997 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_receiving": { + "contains": "time", + "values": { + "max": 11.427, + "avg": 0.01831377036566472, + "med": 0.008, + "p(95)": 0.023, + "p(99)": 0.067 + }, + "type": "trend" + }, + "http_req_failed{phase:measure}": { + "values": { + "rate": 0, + "passes": 0, + "fails": 471573 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate", + "contains": "default" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0023840676569701473, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 8.491 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.595750127620683, + "med": 12.3008125, + "p(95)": 25.650849449999995, + "p(99)": 38.72167499999999, + "max": 245.352125 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.233, + "p(95)": 25.575, + "p(99)": 38.64086999999999, + "max": 244.743, + "avg": 13.527029441592651 + } + }, + "checks": { + "values": { + "rate": 0.9999320010724402, + "passes": 514679, + "fails": 35 + }, + "type": "rate", + "contains": "default" + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.549814201673048, + "med": 12.258, + "p(95)": 25.603, + "p(99)": 38.663, + "max": 245.021 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.004470989714660517, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.018, + "max": 10.625 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 471573, + "rate": 13470.02824240515 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 514714, + "rate": 14702.309328060182 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "rate": 4792626.92529459, + "count": 167785354 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "rate": 2234751.017865148, + "count": 78236528 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0006380145090283145, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.211 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 514714, + "rate": 14702.309328060182 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "med": 12.259, + "p(95)": 25.604, + "p(99)": 38.663, + "max": 245.021, + "avg": 13.550534033834568 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0.00006799892755977105, + "passes": 35, + "fails": 514679 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t10_f1_r2/redis-stats.txt b/evidence/track1/stampede/on/t10_f1_r2/redis-stats.txt new file mode 100644 index 00000000..c335ac12 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r2/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:463418 +keyspace_misses:4069 diff --git a/evidence/track1/stampede/on/t10_f1_r2/run.json b/evidence/track1/stampede/on/t10_f1_r2/run.json new file mode 100644 index 00000000..73ff64bb --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r2/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 2, "finished_at": "2026-10-08T22:39:11Z"} diff --git a/evidence/track1/stampede/on/t10_f1_r2/sql-calls.csv b/evidence/track1/stampede/on/t10_f1_r2/sql-calls.csv new file mode 100644 index 00000000..9fabc134 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r2/sql-calls.csv @@ -0,0 +1 @@ +292,469849,470144 diff --git a/evidence/track1/stampede/on/t10_f1_r2/top-queries.txt b/evidence/track1/stampede/on/t10_f1_r2/top-queries.txt new file mode 100644 index 00000000..37567cf7 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r2/top-queries.txt @@ -0,0 +1,3 @@ +469849|7930.4|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +292|9.4|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t10_f1_r3/k6-summary.json b/evidence/track1/stampede/on/t10_f1_r3/k6-summary.json new file mode 100644 index 00000000..80a21ee3 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "fails": 0, + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 518155 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35011.858 + }, + "metrics": { + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 78759560, + "rate": 2249511.008527454 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.461965801739126, + "med": 12.099, + "p(95)": 25.932, + "p(99)": 38.47791999999999, + "max": 253.218 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "fails": 518155, + "rate": 0, + "passes": 0 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.016694462081820825, + "med": 0.008, + "p(95)": 0.022, + "p(99)": 0.055, + "max": 7.578 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "rate": 4824609.136710198, + "count": 168918530 + } + }, + "iterations": { + "contains": "default", + "values": { + "count": 518155, + "rate": 14799.414529785881 + }, + "type": "counter" + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0022896044619656474, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 5.151 + } + }, + "http_req_sending": { + "values": { + "p(95)": 0.008, + "p(99)": 0.016, + "max": 8.934, + "avg": 0.003978020090488736, + "med": 0.003 + }, + "type": "trend", + "contains": "time" + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 475444, + "rate": 13579.513546524724 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.5720696296517, + "med": 11.686, + "p(95)": 22.986, + "p(99)": 31.554569999999995, + "max": 75.303 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 475444 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.506961727654973, + "med": 12.14175, + "p(95)": 25.9800795, + "p(99)": 38.54904499999999, + "max": 256.551667 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 518155, + "rate": 14799.414529785881 + } + }, + "http_req_connecting": { + "contains": "time", + "values": { + "avg": 0.0006222520288330706, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 2.352 + }, + "type": "trend" + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.461965801739126, + "med": 12.099, + "p(95)": 25.932, + "p(99)": 38.47791999999999, + "max": 253.218 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 518155, + "fails": 0 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0, + "med": 0 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.441293319566043, + "med": 12.079, + "p(95)": 25.91, + "p(99)": 38.46291999999999, + "max": 253.186 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t10_f1_r3/redis-stats.txt b/evidence/track1/stampede/on/t10_f1_r3/redis-stats.txt new file mode 100644 index 00000000..7dfc9da6 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r3/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:468356 +keyspace_misses:3979 diff --git a/evidence/track1/stampede/on/t10_f1_r3/run.json b/evidence/track1/stampede/on/t10_f1_r3/run.json new file mode 100644 index 00000000..bbd6ee12 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r3/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 10, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 3, "finished_at": "2026-10-08T22:44:19Z"} diff --git a/evidence/track1/stampede/on/t10_f1_r3/sql-calls.csv b/evidence/track1/stampede/on/t10_f1_r3/sql-calls.csv new file mode 100644 index 00000000..34192757 --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r3/sql-calls.csv @@ -0,0 +1 @@ +291,474225,474519 diff --git a/evidence/track1/stampede/on/t10_f1_r3/top-queries.txt b/evidence/track1/stampede/on/t10_f1_r3/top-queries.txt new file mode 100644 index 00000000..4e79867c --- /dev/null +++ b/evidence/track1/stampede/on/t10_f1_r3/top-queries.txt @@ -0,0 +1,3 @@ +474225|8057.3|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +291|8.4|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t50_f0_r1/k6-summary.json b/evidence/track1/stampede/on/t50_f0_r1/k6-summary.json new file mode 100644 index 00000000..746545e9 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f0_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 530059, + "fails": 0, + "name": "status is 200" + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35013.678 + }, + "metrics": { + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.843042, + "p(95)": 25.325762499999996, + "p(99)": 38.14057686, + "max": 349.482417, + "avg": 13.203050528479139 + } + }, + "http_reqs": { + "values": { + "count": 530059, + "rate": 15138.626681835596 + }, + "type": "counter", + "contains": "default" + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "passes": 530059, + "fails": 0, + "rate": 1 + } + }, + "http_req_duration{phase:measure}": { + "values": { + "avg": 12.257553593918788, + "med": 11.383, + "p(95)": 22.381, + "p(99)": 30.630829999999996, + "max": 87.904 + }, + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time" + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0.07041999999999529, + "max": 15.628, + "avg": 0.018899631927725258, + "med": 0.007, + "p(95)": 0.022 + } + }, + "iterations": { + "contains": "default", + "values": { + "count": 530059, + "rate": 15138.626681835596 + }, + "type": "counter" + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_blocked": { + "contains": "time", + "values": { + "max": 6.748, + "avg": 0.0024500781988223215, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004 + }, + "type": "trend" + }, + "data_sent": { + "values": { + "count": 80568968, + "rate": 2301071.2556390106 + }, + "type": "counter", + "contains": "data" + }, + "http_reqs{phase:measure}": { + "contains": "default", + "values": { + "rate": 13923.644354072143, + "count": 487518 + }, + "thresholds": { + "count>=0": { + "ok": true + } + }, + "type": "counter" + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.799, + "p(95)": 25.279, + "p(99)": 38.08642, + "max": 345.154, + "avg": 13.155770491587024 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 173223284, + "rate": 4947303.279592621 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 530059 + } + }, + "http_req_connecting": { + "contains": "time", + "values": { + "avg": 0.000579809040125722, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 1.759 + }, + "type": "trend" + }, + "http_req_sending": { + "contains": "time", + "values": { + "avg": 0.004243308763725071, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.018, + "max": 17.572 + }, + "type": "trend" + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.799, + "p(95)": 25.279, + "p(99)": 38.08642, + "max": 345.154, + "avg": 13.155770491587024 + } + }, + "http_req_failed{phase:measure}": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 487518 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.774, + "p(95)": 25.255, + "p(99)": 38.072, + "max": 345.115, + "avg": 13.132627550895446 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t50_f0_r1/redis-stats.txt b/evidence/track1/stampede/on/t50_f0_r1/redis-stats.txt new file mode 100644 index 00000000..55a4d53d --- /dev/null +++ b/evidence/track1/stampede/on/t50_f0_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:484721 +keyspace_misses:0 diff --git a/evidence/track1/stampede/on/t50_f0_r1/run.json b/evidence/track1/stampede/on/t50_f0_r1/run.json new file mode 100644 index 00000000..8868e1a2 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f0_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 0, "flushes": 0, + "repeat": 1, "finished_at": "2026-10-08T22:51:51Z"} diff --git a/evidence/track1/stampede/on/t50_f0_r1/sql-calls.csv b/evidence/track1/stampede/on/t50_f0_r1/sql-calls.csv new file mode 100644 index 00000000..0ed4049f --- /dev/null +++ b/evidence/track1/stampede/on/t50_f0_r1/sql-calls.csv @@ -0,0 +1 @@ +0,486661,486664 diff --git a/evidence/track1/stampede/on/t50_f0_r1/top-queries.txt b/evidence/track1/stampede/on/t50_f0_r1/top-queries.txt new file mode 100644 index 00000000..2326c19c --- /dev/null +++ b/evidence/track1/stampede/on/t50_f0_r1/top-queries.txt @@ -0,0 +1,2 @@ +486661|8306.2|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t50_f1_r1/k6-summary.json b/evidence/track1/stampede/on/t50_f1_r1/k6-summary.json new file mode 100644 index 00000000..afc3613f --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r1/k6-summary.json @@ -0,0 +1,245 @@ +{ + "metrics": { + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.106461437707027, + "med": 11.804, + "p(95)": 24.7, + "p(99)": 37.602859999999986, + "max": 237.477 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "max": 237.477, + "avg": 13.106461437707027, + "med": 11.804, + "p(95)": 24.7, + "p(99)": 37.602859999999986 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.018524706890434395, + "med": 0.007, + "p(95)": 0.022, + "p(99)": 0.052, + "max": 13.378 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 532139, + "rate": 15201.013311381033 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 532139, + "rate": 15201.013311381033 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "avg": 12.26498744850593, + "med": 11.453, + "p(95)": 22.145, + "p(99)": 29.846, + "max": 84.089 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 487193, + "rate": 13917.091733948573 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_tls_handshaking": { + "values": { + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0, + "avg": 0 + }, + "type": "trend", + "contains": "time" + }, + "http_req_failed{phase:measure}": { + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 487193 + }, + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate" + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.000689643119560867, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 3.204 + } + }, + "checks": { + "type": "rate", + "contains": "default", + "values": { + "rate": 1, + "passes": 532139, + "fails": 0 + } + }, + "vus": { + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + }, + "type": "gauge" + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "max": 237.205, + "avg": 13.083690842054844, + "med": 11.783, + "p(95)": 24.662, + "p(99)": 37.56885999999999 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 80885128, + "rate": 2310554.0233299173 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "passes": 0, + "fails": 532139, + "rate": 0 + } + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.150458102397701, + "med": 11.844167, + "p(95)": 24.745291100000003, + "p(99)": 37.67327845999999, + "max": 241.4055 + } + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.004245888762128585, + "med": 0.002, + "p(95)": 0.008, + "p(99)": 0.016, + "max": 9.634 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0022561830649325512, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.003, + "max": 7.015 + } + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 173903122, + "rate": 4967693.915335504 + } + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 532139, + "fails": 0 + } + ] + }, + "options": { + "summaryTimeUnit": "", + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ] + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35006.811 + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t50_f1_r1/redis-stats.txt b/evidence/track1/stampede/on/t50_f1_r1/redis-stats.txt new file mode 100644 index 00000000..201dbf42 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r1/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:478297 +keyspace_misses:4653 diff --git a/evidence/track1/stampede/on/t50_f1_r1/run.json b/evidence/track1/stampede/on/t50_f1_r1/run.json new file mode 100644 index 00000000..fc8ace31 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r1/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 1, "finished_at": "2026-10-08T22:32:27Z"} diff --git a/evidence/track1/stampede/on/t50_f1_r1/sql-calls.csv b/evidence/track1/stampede/on/t50_f1_r1/sql-calls.csv new file mode 100644 index 00000000..bdbb5c11 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r1/sql-calls.csv @@ -0,0 +1 @@ +1451,485556,487010 diff --git a/evidence/track1/stampede/on/t50_f1_r1/top-queries.txt b/evidence/track1/stampede/on/t50_f1_r1/top-queries.txt new file mode 100644 index 00000000..a5e3ac4b --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r1/top-queries.txt @@ -0,0 +1,3 @@ +485556|8351.6|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +1451|31.8|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t50_f1_r2/k6-summary.json b/evidence/track1/stampede/on/t50_f1_r2/k6-summary.json new file mode 100644 index 00000000..7c0a5ba9 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r2/k6-summary.json @@ -0,0 +1,245 @@ +{ + "metrics": { + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "max": 7.571, + "avg": 0.004568457023414109, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.021 + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.2703004927516, + "med": 11.668, + "p(95)": 25.976, + "p(99)": 43.32899, + "max": 198.941 + } + }, + "data_sent": { + "type": "counter", + "contains": "data", + "values": { + "count": 79709104, + "rate": 2277005.8616063073 + } + }, + "data_received": { + "contains": "data", + "values": { + "count": 171374514, + "rate": 4895560.899893344 + }, + "type": "counter" + }, + "http_reqs": { + "contains": "default", + "values": { + "count": 524402, + "rate": 14980.301721094127 + }, + "type": "counter" + }, + "http_req_tls_handshaking": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0, + "max": 0 + } + }, + "checks": { + "values": { + "fails": 0, + "rate": 1, + "passes": 524402 + }, + "type": "rate", + "contains": "default" + }, + "http_req_receiving": { + "values": { + "p(95)": 0.023, + "p(99)": 0.08, + "max": 10.791, + "avg": 0.01937436546768642, + "med": 0.008 + }, + "type": "trend", + "contains": "time" + }, + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "max": 203.419, + "avg": 13.343592494675486, + "med": 11.735667, + "p(95)": 26.0535819, + "p(99)": 43.4172795 + } + }, + "vus_max": { + "values": { + "max": 200, + "value": 200, + "min": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_failed{phase:measure}": { + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 483185 + } + }, + "vus": { + "values": { + "min": 200, + "max": 200, + "value": 200 + }, + "type": "gauge", + "contains": "default" + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "fails": 524402, + "rate": 0, + "passes": 0 + } + }, + "http_req_blocked": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.0023768025293374145, + "med": 0.001, + "p(95)": 0.002, + "p(99)": 0.004, + "max": 10.47 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "p(99)": 0, + "max": 2.563, + "avg": 0.0006718433568140473, + "med": 0, + "p(95)": 0 + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.69, + "p(95)": 26.002, + "p(99)": 43.362989999999996, + "max": 199.394, + "avg": 13.29424331524263 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 524402, + "rate": 14980.301721094127 + } + }, + "http_req_duration{phase:measure}": { + "thresholds": { + "max>=0": { + "ok": true + } + }, + "type": "trend", + "contains": "time", + "values": { + "p(99)": 31.949, + "max": 123.271, + "avg": 12.362872301499115, + "med": 11.283, + "p(95)": 23.079 + } + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 483185, + "rate": 13802.87849227666 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_duration": { + "contains": "time", + "values": { + "max": 199.394, + "avg": 13.29424331524263, + "med": 11.69, + "p(95)": 26.002, + "p(99)": 43.362989999999996 + }, + "type": "trend" + } + }, + "root_group": { + "name": "", + "path": "", + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 524402, + "fails": 0 + } + ] + }, + "options": { + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "", + "noColor": false + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35006.104 + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t50_f1_r2/redis-stats.txt b/evidence/track1/stampede/on/t50_f1_r2/redis-stats.txt new file mode 100644 index 00000000..94cd7b39 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r2/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:474193 +keyspace_misses:4390 diff --git a/evidence/track1/stampede/on/t50_f1_r2/run.json b/evidence/track1/stampede/on/t50_f1_r2/run.json new file mode 100644 index 00000000..16ed5f88 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r2/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 2, "finished_at": "2026-10-08T22:37:37Z"} diff --git a/evidence/track1/stampede/on/t50_f1_r2/sql-calls.csv b/evidence/track1/stampede/on/t50_f1_r2/sql-calls.csv new file mode 100644 index 00000000..1e295e56 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r2/sql-calls.csv @@ -0,0 +1 @@ +1450,481934,483387 diff --git a/evidence/track1/stampede/on/t50_f1_r2/top-queries.txt b/evidence/track1/stampede/on/t50_f1_r2/top-queries.txt new file mode 100644 index 00000000..9d412856 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r2/top-queries.txt @@ -0,0 +1,3 @@ +481934|7819.9|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +1450|33.2|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/stampede/on/t50_f1_r3/k6-summary.json b/evidence/track1/stampede/on/t50_f1_r3/k6-summary.json new file mode 100644 index 00000000..eb9a88a0 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r3/k6-summary.json @@ -0,0 +1,245 @@ +{ + "root_group": { + "id": "d41d8cd98f00b204e9800998ecf8427e", + "groups": [], + "checks": [ + { + "name": "status is 200", + "path": "::status is 200", + "id": "6210a8cd14cd70477eba5c5e4cb3fb5f", + "passes": 529084, + "fails": 0 + } + ], + "name": "", + "path": "" + }, + "options": { + "noColor": false, + "summaryTrendStats": [ + "avg", + "med", + "p(95)", + "p(99)", + "max" + ], + "summaryTimeUnit": "" + }, + "state": { + "isStdOutTTY": false, + "isStdErrTTY": false, + "testRunDurationMs": 35009.956 + }, + "metrics": { + "iteration_duration": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 25.14090985, + "p(99)": 37.51666735999999, + "max": 237.225042, + "avg": 13.226783947478877, + "med": 11.8911665 + } + }, + "iterations": { + "type": "counter", + "contains": "default", + "values": { + "count": 529084, + "rate": 15112.386887889832 + } + }, + "http_req_duration{phase:measure}": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 22.571, + "p(99)": 29.937559999999984, + "max": 71.529, + "avg": 12.37915625808933, + "med": 11.483 + }, + "thresholds": { + "max>=0": { + "ok": true + } + } + }, + "http_req_waiting": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 25.068, + "p(99)": 37.42367999999998, + "max": 234.443, + "avg": 13.160434993308805, + "med": 11.828 + } + }, + "http_req_failed{phase:measure}": { + "thresholds": { + "rate>=0": { + "ok": true + } + }, + "type": "rate", + "contains": "default", + "values": { + "fails": 482887, + "rate": 0, + "passes": 0 + } + }, + "http_req_duration": { + "type": "trend", + "contains": "time", + "values": { + "avg": 13.180932817850906, + "med": 11.852, + "p(95)": 25.09384999999998, + "p(99)": 37.45833999999999, + "max": 234.479 + } + }, + "http_req_failed": { + "type": "rate", + "contains": "default", + "values": { + "rate": 0, + "passes": 0, + "fails": 529084 + } + }, + "http_req_receiving": { + "type": "trend", + "contains": "time", + "values": { + "med": 0.007, + "p(95)": 0.022, + "p(99)": 0.053, + "max": 7.697, + "avg": 0.016394130232661373 + } + }, + "checks": { + "contains": "default", + "values": { + "rate": 1, + "passes": 529084, + "fails": 0 + }, + "type": "rate" + }, + "http_reqs{phase:measure}": { + "type": "counter", + "contains": "default", + "values": { + "count": 482887, + "rate": 13792.84795445044 + }, + "thresholds": { + "count>=0": { + "ok": true + } + } + }, + "http_req_duration{expected_response:true}": { + "type": "trend", + "contains": "time", + "values": { + "med": 11.852, + "p(95)": 25.09384999999998, + "p(99)": 37.45833999999999, + "max": 234.479, + "avg": 13.180932817850906 + } + }, + "vus_max": { + "type": "gauge", + "contains": "default", + "values": { + "value": 200, + "min": 200, + "max": 200 + } + }, + "vus": { + "type": "gauge", + "contains": "default", + "values": { + "max": 200, + "value": 200, + "min": 200 + } + }, + "http_reqs": { + "type": "counter", + "contains": "default", + "values": { + "count": 529084, + "rate": 15112.386887889832 + } + }, + "http_req_connecting": { + "type": "trend", + "contains": "time", + "values": { + "p(95)": 0, + "p(99)": 0, + "max": 7.567, + "avg": 0.001968384982346848, + "med": 0 + } + }, + "data_sent": { + "values": { + "count": 80420768, + "rate": 2297082.8069592547 + }, + "type": "counter", + "contains": "data" + }, + "data_received": { + "type": "counter", + "contains": "data", + "values": { + "count": 172904498, + "rate": 4938723.659064296 + } + }, + "http_req_blocked": { + "contains": "time", + "values": { + "p(95)": 0.002, + "p(99)": 0.003, + "max": 10.084, + "avg": 0.0037807833916530553, + "med": 0.001 + }, + "type": "trend" + }, + "http_req_tls_handshaking": { + "values": { + "max": 0, + "avg": 0, + "med": 0, + "p(95)": 0, + "p(99)": 0 + }, + "type": "trend", + "contains": "time" + }, + "http_req_sending": { + "type": "trend", + "contains": "time", + "values": { + "avg": 0.00410369430938731, + "med": 0.003, + "p(95)": 0.008, + "p(99)": 0.016, + "max": 5.692 + } + } + } +} \ No newline at end of file diff --git a/evidence/track1/stampede/on/t50_f1_r3/redis-stats.txt b/evidence/track1/stampede/on/t50_f1_r3/redis-stats.txt new file mode 100644 index 00000000..0d26d96a --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r3/redis-stats.txt @@ -0,0 +1,2 @@ +keyspace_hits:475235 +keyspace_misses:4777 diff --git a/evidence/track1/stampede/on/t50_f1_r3/run.json b/evidence/track1/stampede/on/t50_f1_r3/run.json new file mode 100644 index 00000000..af2c7292 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r3/run.json @@ -0,0 +1,3 @@ +{"variant": "on", "single_flight": true, "tokens": 50, "vus": 200, + "warmup_s": 5, "duration_s": 30, "flush_interval_s": 1, "flushes": 30, + "repeat": 3, "finished_at": "2026-10-08T22:42:46Z"} diff --git a/evidence/track1/stampede/on/t50_f1_r3/sql-calls.csv b/evidence/track1/stampede/on/t50_f1_r3/sql-calls.csv new file mode 100644 index 00000000..803f410f --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r3/sql-calls.csv @@ -0,0 +1 @@ +1451,482275,483729 diff --git a/evidence/track1/stampede/on/t50_f1_r3/top-queries.txt b/evidence/track1/stampede/on/t50_f1_r3/top-queries.txt new file mode 100644 index 00000000..0d924174 --- /dev/null +++ b/evidence/track1/stampede/on/t50_f1_r3/top-queries.txt @@ -0,0 +1,3 @@ +482275|8230.0|SELECT users.id, users.username, users.display_name, users.password_hash, users.created_at FROM users WHERE users.id = $ +1451|47.7|SELECT sessions.id, sessions.user_id, sessions.token_hash, sessions.created_at, sessions.expires_at FROM sessions WHERE +3|0.0|SELECT $1 diff --git a/evidence/track1/summary.md b/evidence/track1/summary.md new file mode 100644 index 00000000..bdc05998 --- /dev/null +++ b/evidence/track1/summary.md @@ -0,0 +1,30 @@ +# Track 1 summary + +Generated by `python3 scripts/track1/aggregate.py`. Medians of the repeats, (min–max) in brackets. + +## Cache stampede: FLUSHALL every second under 200 VUs + +| Сессий | Сбросов кэша | Single-flight | Запросов к `sessions` | на один сброс | на сессию за сброс | Промахов Redis | Всего SQL | RPS | p50 / p95 / p99, мс | max, мс | Ошибки | +| ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | ---: | ---: | +| 50 | 30 | нет | 4651 (4622–4689) | 155.0 (154.1–156.3) | 3.10 (3.08–3.13) | 4651 (4622–4689) | 492085 (491701–499302) | 16270 (16268–16512) | 11.2 / 22.9 / 31.6 | 86 (77–88) | 0 | +| 50 | 30 | да | 1451 (1450–1451) | 48.4 (48.3–48.4) | 0.97 (0.97–0.97) | 4653 (4390–4777) | 483729 (483387–487010) | 16106 (16096–16240) | 11.5 / 22.6 / 29.9 | 84 (72–123) | 0 | +| 10 | 30 | нет | 3138 (2893–3500) | 104.6 (96.4–116.7) | 10.46 (9.64–11.67) | 3138 (2893–3500) | 474008 (461790–485580) | 15719 (15322–16108) | 11.7 / 23.4 / 32.0 | 84 (83–132) | 0 | +| 10 | 30 | да | 291 (291–292) | 9.7 (9.7–9.7) | 0.97 (0.97–0.97) | 4037 (3979–4069) | 470144 (466783–474519) | 15719 (15564–15848) | 11.8 / 23.1 / 31.6 | 87 (75–133) | 0 | +| 50 | нет | нет | 0 | — | — | 0 | 477952 | 15966 | 11.5 / 23.3 / 32.1 | 86 | 0 | +| 50 | нет | да | 0 | — | — | 0 | 486664 | 16251 | 11.4 / 22.4 / 30.6 | 88 | 0 | + +## Redis restart under 200 VUs, 50 sessions + +| Single-flight | `docker compose restart redis`, с | Кэш недоступен по логу API, с | Запросов к `sessions` за прогон | p99 до рестарта, мс | p99 в секунду рестарта, мс | max в секунду рестарта, мс | Не 200 | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| нет | 0.52 (0.48–0.59) | 0.71 (0.65–0.83) | 5625 (4700–6284) | 36 (34–39) | 76 (68–163) | 133 (112–225) | 0 | +| да | 0.51 (0.47–0.57) | 0.73 (0.70–0.75) | 3490 (3106–3805) | 37 (35–40) | 71 (70–89) | 138 (129–153) | 0 | + +## Read-after-write of login and logout, 16 concurrent readers + +| Single-flight | Redis | Итераций | Первый запрос после входа не 200 | Запросов до ответа logout | Запросов после ответа logout | Из них 200 (нарушение) | Другие коды | Токен жив через 1 с | +| --- | --- | ---: | ---: | ---: | ---: | ---: | --- | ---: | +| нет | остановлен | 300 | 0 | 43034 | 362801 | 0 | нет | 0 | +| нет | работает | 300 | 0 | 42545 | 396511 | 0 | нет | 0 | +| да | остановлен | 300 | 0 | 42973 | 361654 | 0 | нет | 0 | +| да | работает | 300 | 0 | 42692 | 405818 | 0 | нет | 0 | diff --git a/scripts/track1/aggregate.py b/scripts/track1/aggregate.py new file mode 100644 index 00000000..dc0744bd --- /dev/null +++ b/scripts/track1/aggregate.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Builds evidence/track1/summary.md from the raw results of run-all.sh.""" +import csv +import glob +import json +import os +import re +import statistics +from datetime import datetime + +ROOT = "evidence/track1" + + +def load_k6(path): + metrics = json.load(open(path))["metrics"] + duration = metrics["http_req_duration{phase:measure}"]["values"] + requests = metrics["http_reqs{phase:measure}"]["values"]["count"] + failed = metrics["http_req_failed{phase:measure}"]["values"] + return { + "requests": requests, + "failed": failed["passes"], + "p50": duration["med"], + "p95": duration["p(95)"], + "p99": duration["p(99)"], + "max": duration["max"], + } + + +def median_range(values, fmt="{:.0f}"): + values = [v for v in values if v is not None] + if not values: + return "—" + med = statistics.median(values) + if len(values) == 1: + return fmt.format(med) + return f"{fmt.format(med)} ({fmt.format(min(values))}–{fmt.format(max(values))})" + + +def stampede_rows(): + runs = [] + for run_dir in sorted(glob.glob(f"{ROOT}/stampede/*/*")): + run = json.load(open(f"{run_dir}/run.json")) + sessions, users, total = map(int, open(f"{run_dir}/sql-calls.csv").read().strip().split(",")) + redis = dict(line.strip().split(":") for line in open(f"{run_dir}/redis-stats.txt") if ":" in line) + k6 = load_k6(f"{run_dir}/k6-summary.json") + runs.append({**run, **k6, "sessions": sessions, "users": users, "total_sql": total, + "misses": int(redis["keyspace_misses"]), "hits": int(redis["keyspace_hits"])}) + with open(f"{ROOT}/stampede-runs.csv", "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(runs[0].keys())) + writer.writeheader() + writer.writerows(runs) + return runs + + +def stampede_table(runs): + lines = [ + "| Сессий | Сбросов кэша | Single-flight | Запросов к `sessions` | на один сброс | на сессию за сброс | Промахов Redis | Всего SQL | RPS | p50 / p95 / p99, мс | max, мс | Ошибки |", + "| ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | ---: | ---: |", + ] + keys = sorted({(r["tokens"], r["flush_interval_s"], r["variant"]) for r in runs}, key=lambda k: (-k[1], -k[0], k[2])) + for tokens, flush, variant in keys: + group = [r for r in runs if (r["tokens"], r["flush_interval_s"], r["variant"]) == (tokens, flush, variant)] + flushes = group[0]["flushes"] + per_flush = [r["sessions"] / r["flushes"] for r in group] if flushes else [None] + per_session = [r["sessions"] / r["flushes"] / tokens for r in group] if flushes else [None] + lines.append( + f"| {tokens} | {flushes if flushes else 'нет'} | {'да' if variant == 'on' else 'нет'} " + f"| {median_range([r['sessions'] for r in group])} " + f"| {median_range(per_flush, '{:.1f}')} | {median_range(per_session, '{:.2f}')} " + f"| {median_range([r['misses'] for r in group])} | {median_range([r['total_sql'] for r in group])} " + f"| {median_range([r['requests'] / r['duration_s'] for r in group])} " + f"| {statistics.median(r['p50'] for r in group):.1f} / {statistics.median(r['p95'] for r in group):.1f} / " + f"{statistics.median(r['p99'] for r in group):.1f} " + f"| {median_range([r['max'] for r in group], '{:.0f}')} | {sum(r['failed'] for r in group)} |" + ) + return lines + + +def parse_log_time(line): + stamp = line.split()[0] + return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() + + +def restart_rows(): + runs = [] + for run_dir in sorted(glob.glob(f"{ROOT}/redis-restart/*/*")): + run = json.load(open(f"{run_dir}/run.json")) + k6 = load_k6(f"{run_dir}/k6-summary.json") + seconds = list(csv.DictReader(open(f"{run_dir}/per-second.csv"))) + samples = list(csv.DictReader(open(f"{run_dir}/samples.csv"))) + lookups = max(int(s["session_lookups_total"]) for s in samples if s["session_lookups_total"]) + log = [line for line in open(f"{run_dir}/cache-availability.log")] + down = [parse_log_time(l) for l in log if "unavailable" in l and parse_log_time(l) >= run["measure_start"]] + up = [parse_log_time(l) for l in log if "available again" in l and parse_log_time(l) >= run["measure_start"]] + outage = (up[0] - down[0]) if down and up else None + restart_second = int(run["restart_begin"] - run["measure_start"]) + window = [s for s in seconds if restart_second - 1 <= int(s["second"]) <= restart_second + 1 and s["p99_ms"]] + before = [s for s in seconds if int(s["second"]) < restart_second - 1 and s["p99_ms"]] + runs.append({ + **run, **k6, + "session_lookups": lookups, + "cache_outage_s": outage, + "recovered_after_restart_s": (up[0] - run["restart_end"]) if up else None, + "restart_s": run["restart_end"] - run["restart_begin"], + "peak_p99_ms": max(float(s["p99_ms"]) for s in window), + "peak_max_ms": max(float(s["max_ms"]) for s in window), + "p99_before_ms": statistics.median(float(s["p99_ms"]) for s in before), + "non_200": sum(int(s["non_200"]) for s in seconds), + }) + with open(f"{ROOT}/redis-restart-runs.csv", "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(runs[0].keys())) + writer.writeheader() + writer.writerows(runs) + return runs + + +def restart_table(runs): + lines = [ + "| Single-flight | `docker compose restart redis`, с | Кэш недоступен по логу API, с | Запросов к `sessions` за прогон | p99 до рестарта, мс | p99 в секунду рестарта, мс | max в секунду рестарта, мс | Не 200 |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + for variant in ("off", "on"): + group = [r for r in runs if r["variant"] == variant] + if not group: + continue + lines.append( + f"| {'да' if variant == 'on' else 'нет'} | {median_range([r['restart_s'] for r in group], '{:.2f}')} " + f"| {median_range([r['cache_outage_s'] for r in group], '{:.2f}')} " + f"| {median_range([r['session_lookups'] for r in group])} " + f"| {median_range([r['p99_before_ms'] for r in group], '{:.0f}')} " + f"| {median_range([r['peak_p99_ms'] for r in group], '{:.0f}')} " + f"| {median_range([r['peak_max_ms'] for r in group], '{:.0f}')} | {sum(r['non_200'] for r in group)} |" + ) + return lines + + +def read_after_write_table(): + lines = [ + "| Single-flight | Redis | Итераций | Первый запрос после входа не 200 | Запросов до ответа logout | Запросов после ответа logout | Из них 200 (нарушение) | Другие коды | Токен жив через 1 с |", + "| --- | --- | ---: | ---: | ---: | ---: | ---: | --- | ---: |", + ] + for path in sorted(glob.glob(f"{ROOT}/read-after-write/*.json")): + variant, redis = re.match(r".*/(on|off)_redis-(up|down)\.json", path).groups() + d = json.load(open(path)) + lines.append( + f"| {'да' if variant == 'on' else 'нет'} | {'работает' if redis == 'up' else 'остановлен'} | {d['iterations']} " + f"| {d['first_request_after_login_not_200']} | {d['requests_started_before_logout_response']} " + f"| {d['requests_started_after_logout_response']} | {d['violations_200_after_logout']} " + f"| {d['unexpected_statuses'] or 'нет'} | {d['token_alive_one_second_later']} |" + ) + return lines + + +def main(): + out = ["# Track 1 summary", "", "Generated by `python3 scripts/track1/aggregate.py`. Medians of the repeats, (min–max) in brackets.", ""] + if os.path.isdir(f"{ROOT}/stampede"): + out += ["## Cache stampede: FLUSHALL every second under 200 VUs", ""] + stampede_table(stampede_rows()) + [""] + if os.path.isdir(f"{ROOT}/redis-restart"): + out += ["## Redis restart under 200 VUs, 50 sessions", ""] + restart_table(restart_rows()) + [""] + if os.path.isdir(f"{ROOT}/read-after-write"): + out += ["## Read-after-write of login and logout, 16 concurrent readers", ""] + read_after_write_table() + [""] + open(f"{ROOT}/summary.md", "w").write("\n".join(out)) + print("\n".join(out)) + + +if __name__ == "__main__": + main() diff --git a/scripts/track1/per_second.py b/scripts/track1/per_second.py new file mode 100755 index 00000000..18a0e725 --- /dev/null +++ b/scripts/track1/per_second.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Reduces a k6 CSV of single requests to per-second numbers of the measure phase: +second, requests, non-200 responses, p50/p99/max latency in ms.""" +import csv +import math +import sys +from collections import defaultdict + + +def percentile(values, q): + values = sorted(values) + return values[min(len(values) - 1, int(q * len(values)))] + + +def main(): + path, measure_start, duration = sys.argv[1], float(sys.argv[2]), int(sys.argv[3]) + durations = defaultdict(list) + failures = defaultdict(int) + statuses = {} + with open(path) as f: + for row in csv.DictReader(f): + if row["metric_name"] == "http_req_duration": + second = math.floor(float(row["timestamp"]) / 1000 - measure_start) + if 0 <= second < duration: + durations[second].append(float(row["metric_value"])) + if row.get("status") != "200": + failures[second] += 1 + print("second,requests,non_200,p50_ms,p99_ms,max_ms") + for second in range(duration): + values = durations.get(second, []) + if not values: + print(f"{second},0,0,,,") + continue + print(f"{second},{len(values)},{failures[second]},{percentile(values, 0.5):.2f}," + f"{percentile(values, 0.99):.2f},{max(values):.2f}") + + +if __name__ == "__main__": + main() diff --git a/scripts/track1/prepare_sessions.py b/scripts/track1/prepare_sessions.py new file mode 100755 index 00000000..1eae5fbb --- /dev/null +++ b/scripts/track1/prepare_sessions.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Registers N synthetic users, opens one session each and writes the tokens, one per line, to a file. + +The file holds live credentials of synthetic users only; the caller keeps it outside the repository +(mode 600) and deletes it after the run. +""" +import base64 +import json +import os +import sys +import urllib.request +import uuid + +PASSWORD = "track1-stampede-password" + + +def request(method, url, body=None, headers=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method, headers=headers or {}) + if data is not None: + req.add_header("Content-Type", "application/json") + with urllib.request.urlopen(req, timeout=10) as response: + return json.load(response) + + +def main(): + base_url, count, path = sys.argv[1], int(sys.argv[2]), sys.argv[3] + tokens = [] + for i in range(count): + username = f"t1_{uuid.uuid4().hex[:12]}" + request("POST", f"{base_url}/api/v1/users", + {"username": username, "display_name": f"Stampede {i}", "password": PASSWORD}) + basic = base64.b64encode(f"{username}:{PASSWORD}".encode()).decode() + session = request("POST", f"{base_url}/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"}) + tokens.append(session["token"]) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + f.write("\n".join(tokens) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/track1/read-after-write.sh b/scripts/track1/read-after-write.sh new file mode 100755 index 00000000..0ea791bc --- /dev/null +++ b/scripts/track1/read-after-write.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Read-after-write of login/logout under concurrent readers, see read_after_write.py. +# VARIANT=off|on (single-flight), REDIS=up|down, ITERATIONS, READERS +set -eu +cd "$(dirname "$0")/../.." + +VARIANT=${VARIANT:?set VARIANT=off or VARIANT=on} +REDIS=${REDIS:-up} +ITERATIONS=${ITERATIONS:-300} +READERS=${READERS:-16} +BASE_URL=${BASE_URL:-http://localhost:8080} + +case "$VARIANT" in + off) SINGLE_FLIGHT=false ;; + on) SINGLE_FLIGHT=true ;; + *) echo "VARIANT must be off or on" >&2; exit 2 ;; +esac + +OUT="evidence/track1/read-after-write" +mkdir -p "$OUT" + +SESSION_CACHE_SINGLE_FLIGHT=$SINGLE_FLIGHT docker compose up -d --force-recreate --wait api >/dev/null 2>&1 +if [ "$REDIS" = "down" ]; then + docker compose stop redis >/dev/null 2>&1 +fi + +python3 scripts/track1/read_after_write.py "$BASE_URL" "$ITERATIONS" "$READERS" > "$OUT/${VARIANT}_redis-${REDIS}.json" + +if [ "$REDIS" = "down" ]; then + docker compose up -d --wait redis >/dev/null 2>&1 +fi + +echo "$OUT/${VARIANT}_redis-${REDIS}.json" +cat "$OUT/${VARIANT}_redis-${REDIS}.json" diff --git a/scripts/track1/read_after_write.py b/scripts/track1/read_after_write.py new file mode 100755 index 00000000..cadac319 --- /dev/null +++ b/scripts/track1/read_after_write.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Read-after-write of sessions under concurrency. + +Every iteration logs in (fresh token, cold cache), checks that the very first request with the token succeeds, +starts READERS threads that call GET /users/me in a loop and logs out after a random 0-20 ms, i.e. while the +first cache fills race with the revocation. A violation is a 200 for a request that started after the client +had received the 204 of the logout. One second later the token is checked again: a stale cached copy must not +bring it back. Prints a JSON summary; tokens are never printed. +""" +import base64 +import http.client +import json +import random +import sys +import threading +import time +import urllib.parse +import uuid + +PASSWORD = "track1-read-after-write" + + +class Client: + def __init__(self, base_url): + url = urllib.parse.urlparse(base_url) + self.connection = http.client.HTTPConnection(url.hostname, url.port, timeout=10) + + def call(self, method, path, headers=None, body=None): + self.connection.request(method, path, body=body, headers=headers or {}) + response = self.connection.getresponse() + data = response.read() + return response.status, data + + +def main(): + base_url, iterations, readers = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) + rng = random.Random(42) + + setup = Client(base_url) + username = f"raw_{uuid.uuid4().hex[:12]}" + status, _ = setup.call("POST", "/api/v1/users", {"Content-Type": "application/json"}, + json.dumps({"username": username, "display_name": "RAW", "password": PASSWORD})) + assert status == 201, status + basic = "Basic " + base64.b64encode(f"{username}:{PASSWORD}".encode()).decode() + + reader_clients = [Client(base_url) for _ in range(readers)] + revoked = [] + totals = { + "iterations": iterations, "readers": readers, + "first_request_after_login_not_200": 0, + "requests_started_before_logout_response": 0, + "requests_started_after_logout_response": 0, + "violations_200_after_logout": 0, + "unexpected_statuses": {}, + "token_alive_one_second_later": 0, + "logout_not_204": 0, + } + + for _ in range(iterations): + status, body = setup.call("POST", "/api/v1/auth/sessions", {"Authorization": basic}) + assert status == 201, status + bearer = {"Authorization": "Bearer " + json.loads(body)["token"]} + + # Read-after-write of the login itself: no negative caching, the token works immediately. + status, _ = setup.call("GET", "/api/v1/users/me", bearer) + if status != 200: + totals["first_request_after_login_not_200"] += 1 + # The check above filled the cache; start the race from a cold key with a new session. + status, body = setup.call("POST", "/api/v1/auth/sessions", {"Authorization": basic}) + assert status == 201, status + bearer = {"Authorization": "Bearer " + json.loads(body)["token"]} + + stop = threading.Event() + results = [] + lock = threading.Lock() + + def read(client): + while not stop.is_set(): + started = time.monotonic() + status, _ = client.call("GET", "/api/v1/users/me", bearer) + with lock: + results.append((started, status)) + + threads = [threading.Thread(target=read, args=(c,)) for c in reader_clients] + for t in threads: + t.start() + time.sleep(rng.uniform(0, 0.02)) + status, _ = setup.call("DELETE", "/api/v1/auth/sessions/current", bearer) + logout_done = time.monotonic() + if status != 204: + totals["logout_not_204"] += 1 + time.sleep(0.1) + stop.set() + for t in threads: + t.join() + + for started, status in results: + if started > logout_done: + totals["requests_started_after_logout_response"] += 1 + if status == 200: + totals["violations_200_after_logout"] += 1 + elif status != 401: + key = str(status) + totals["unexpected_statuses"][key] = totals["unexpected_statuses"].get(key, 0) + 1 + else: + totals["requests_started_before_logout_response"] += 1 + + revoked.append(bearer) + + # Late check, one second after the last logout at the earliest: nothing cached resurrects a revoked token. + time.sleep(1) + for bearer in revoked: + status, _ = setup.call("GET", "/api/v1/users/me", bearer) + if status == 200: + totals["token_alive_one_second_later"] += 1 + + print(json.dumps(totals, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/track1/redis-restart.sh b/scripts/track1/redis-restart.sh new file mode 100755 index 00000000..32e8d9fe --- /dev/null +++ b/scripts/track1/redis-restart.sh @@ -0,0 +1,89 @@ +#!/bin/sh +# Cache restart under load: the same k6 load as stampede.sh, but instead of FLUSHALL the Redis container is +# restarted RESTART_AT_S seconds into the measure phase. Every second the script samples session lookups in +# pg_stat_statements and Redis keyspace hits/misses, k6 writes every request to a CSV that is reduced to +# per-second numbers afterwards. +# VARIANT=off|on, TOKENS, VUS, WARMUP_S, DURATION_S, RESTART_AT_S, REPEAT +set -eu +cd "$(dirname "$0")/../.." + +VARIANT=${VARIANT:?set VARIANT=off or VARIANT=on} +TOKENS=${TOKENS:-50} +VUS=${VUS:-200} +WARMUP_S=${WARMUP_S:-5} +DURATION_S=${DURATION_S:-30} +RESTART_AT_S=${RESTART_AT_S:-10} +REPEAT=${REPEAT:-1} +BASE_URL=${BASE_URL:-http://localhost:8080} + +case "$VARIANT" in + off) SINGLE_FLIGHT=false ;; + on) SINGLE_FLIGHT=true ;; + *) echo "VARIANT must be off or on" >&2; exit 2 ;; +esac + +OUT="evidence/track1/redis-restart/$VARIANT/t${TOKENS}_r${REPEAT}" +mkdir -p "$OUT" + +WORK=$(mktemp -d) +[ -z "${KEEP_WORK:-}" ] || echo "work dir: $WORK" +trap '[ -n "${KEEP_WORK:-}" ] || rm -rf "$WORK"' EXIT + +redis() { docker compose exec -T -e REDISCLI_AUTH="$(cat secrets/redis_password)" redis redis-cli "$@"; } +psql_() { docker compose exec -T postgres psql -U messenger -d messenger -X -q -At "$@"; } + +SESSION_CACHE_SINGLE_FLIGHT=$SINGLE_FLIGHT docker compose up -d --force-recreate --wait api >/dev/null 2>&1 +test "$(docker compose exec -T api printenv SESSION_CACHE_SINGLE_FLIGHT)" = "$SINGLE_FLIGHT" + +python3 scripts/track1/prepare_sessions.py "$BASE_URL" "$TOKENS" "$WORK/tokens" +psql_ -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements" >/dev/null 2>&1 + +K6_CSV_TIME_FORMAT=unix_milli k6 run --quiet --no-usage-report \ + -e BASE_URL="$BASE_URL" -e VUS="$VUS" -e WARMUP_S="$WARMUP_S" -e DURATION_S="$DURATION_S" \ + -e TOKENS_FILE="$WORK/tokens" -e SUMMARY_FILE="$OUT/k6-summary.json" \ + --out csv="$WORK/requests.csv" \ + scripts/track1/stampede.js > "$OUT/k6.log" 2>&1 & +K6_PID=$! + +sleep "$WARMUP_S" +psql_ -c "SELECT pg_stat_statements_reset()" >/dev/null +MEASURE_START=$(python3 -c 'import time; print(time.time())') + +sample() { + lookups=$(psql_ -c "SELECT coalesce(sum(calls), 0) FROM pg_stat_statements WHERE query ILIKE '%FROM sessions WHERE%'" 2>/dev/null || echo "") + stats=$(redis INFO stats 2>/dev/null | tr -d '\r' | grep -E '^keyspace_(hits|misses):' | cut -d: -f2 | tr '\n' ',' || true) + echo "$(python3 -c 'import time; print(round(time.time(), 3))'),$lookups,$stats" +} + +echo "unix_time,session_lookups_total,redis_hits_total,redis_misses_total," > "$OUT/samples.csv" +MEASURE_END=$(python3 -c "print($MEASURE_START + $DURATION_S)") +( + # Paced by the clock: one docker exec pair takes a noticeable part of a second. + next=$MEASURE_START + while python3 -c "import sys, time; sys.exit(0 if time.time() < $MEASURE_END else 1)"; do + sample >> "$OUT/samples.csv" + next=$(python3 -c "print($next + 1)") + python3 -c "import time; time.sleep(max(0, $next - time.time()))" + done +) & +SAMPLER_PID=$! + +sleep "$RESTART_AT_S" +RESTART_BEGIN=$(python3 -c 'import time; print(time.time())') +docker compose restart redis >/dev/null 2>&1 +RESTART_END=$(python3 -c 'import time; print(time.time())') + +wait "$SAMPLER_PID" +wait "$K6_PID" + +docker compose logs --no-log-prefix --since 2m api 2>&1 | grep -E "Session cache is (unavailable|available again)" > "$OUT/cache-availability.log" || true +python3 scripts/track1/per_second.py "$WORK/requests.csv" "$MEASURE_START" "$DURATION_S" > "$OUT/per-second.csv" + +cat > "$OUT/run.json" < /dev/null + done +done + +SESSION_CACHE_SINGLE_FLIGHT=true docker compose up -d --force-recreate --wait api >/dev/null 2>&1 +python3 scripts/track1/aggregate.py diff --git a/scripts/track1/stampede.js b/scripts/track1/stampede.js new file mode 100644 index 00000000..4528cba2 --- /dev/null +++ b/scripts/track1/stampede.js @@ -0,0 +1,41 @@ +// Closed-loop load on GET /api/v1/users/me: every VU reuses one of TOKENS sessions, so VUS / TOKENS requests +// per session are in flight at any moment. The shell script empties Redis once a second during the measure phase. +import http from 'k6/http'; +import { check } from 'k6'; +import exec from 'k6/execution'; + +const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080'; +const VUS = Number(__ENV.VUS || 200); +const WARMUP_S = Number(__ENV.WARMUP_S || 5); +const DURATION_S = Number(__ENV.DURATION_S || 30); +const tokens = open(__ENV.TOKENS_FILE).split('\n').filter((line) => line.length > 0); + +export const options = { + discardResponseBodies: true, + // One scenario for warm-up and measurement: the VUs keep their keep-alive connections, so the measure phase + // does not start with 200 fresh TCP connects through the Docker port forward. + scenarios: { + load: { executor: 'constant-vus', vus: VUS, duration: `${WARMUP_S + DURATION_S}s` }, + }, + summaryTrendStats: ['avg', 'med', 'p(95)', 'p(99)', 'max'], + thresholds: { + // Thresholds only make k6 report the measure-phase submetrics; they never fail the run. + 'http_req_duration{phase:measure}': ['max>=0'], + 'http_reqs{phase:measure}': ['count>=0'], + 'http_req_failed{phase:measure}': ['rate>=0'], + }, +}; + +export default function () { + const token = tokens[(__VU - 1) % tokens.length]; + const phase = Date.now() - exec.scenario.startTime < WARMUP_S * 1000 ? 'warmup' : 'measure'; + const response = http.get(`${BASE_URL}/api/v1/users/me`, { + headers: { Authorization: `Bearer ${token}` }, + tags: { phase }, + }); + check(response, { 'status is 200': (r) => r.status === 200 }); +} + +export function handleSummary(data) { + return { [__ENV.SUMMARY_FILE]: JSON.stringify(data, null, 2) }; +} diff --git a/scripts/track1/stampede.sh b/scripts/track1/stampede.sh new file mode 100755 index 00000000..615e05fb --- /dev/null +++ b/scripts/track1/stampede.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# One stampede run against the Compose stack. +# VARIANT=off|on single-flight disabled / enabled (SESSION_CACHE_SINGLE_FLIGHT) +# TOKENS distinct sessions shared by the VUs +# VUS, WARMUP_S, DURATION_S, FLUSH_INTERVAL_S (0 = never flush), REPEAT +# Results go to evidence/track1/stampede//t_f_r/. +set -eu +cd "$(dirname "$0")/../.." + +VARIANT=${VARIANT:?set VARIANT=off or VARIANT=on} +TOKENS=${TOKENS:-50} +VUS=${VUS:-200} +WARMUP_S=${WARMUP_S:-5} +DURATION_S=${DURATION_S:-30} +FLUSH_INTERVAL_S=${FLUSH_INTERVAL_S:-1} +REPEAT=${REPEAT:-1} +BASE_URL=${BASE_URL:-http://localhost:8080} + +case "$VARIANT" in + off) SINGLE_FLIGHT=false ;; + on) SINGLE_FLIGHT=true ;; + *) echo "VARIANT must be off or on" >&2; exit 2 ;; +esac + +OUT="evidence/track1/stampede/$VARIANT/t${TOKENS}_f${FLUSH_INTERVAL_S}_r${REPEAT}" +mkdir -p "$OUT" + +TOKENS_FILE=$(mktemp) +trap 'rm -f "$TOKENS_FILE"' EXIT + +redis() { docker compose exec -T -e REDISCLI_AUTH="$(cat secrets/redis_password)" redis redis-cli "$@"; } +psql_() { docker compose exec -T postgres psql -U messenger -d messenger -X -q -At "$@"; } + +# Fresh API process for every run, same image, only the flag differs. +SESSION_CACHE_SINGLE_FLIGHT=$SINGLE_FLIGHT docker compose up -d --force-recreate --wait api >/dev/null 2>&1 +test "$(docker compose exec -T api printenv SESSION_CACHE_SINGLE_FLIGHT)" = "$SINGLE_FLIGHT" + +python3 scripts/track1/prepare_sessions.py "$BASE_URL" "$TOKENS" "$TOKENS_FILE" +psql_ -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements" >/dev/null 2>&1 + +k6 run --quiet --no-usage-report \ + -e BASE_URL="$BASE_URL" -e VUS="$VUS" -e WARMUP_S="$WARMUP_S" -e DURATION_S="$DURATION_S" \ + -e TOKENS_FILE="$TOKENS_FILE" -e SUMMARY_FILE="$OUT/k6-summary.json" \ + scripts/track1/stampede.js > "$OUT/k6.log" 2>&1 & +K6_PID=$! + +sleep "$WARMUP_S" +psql_ -c "SELECT pg_stat_statements_reset()" >/dev/null +redis CONFIG RESETSTAT >/dev/null + +FLUSHES=0 +if [ "$FLUSH_INTERVAL_S" -gt 0 ]; then + FLUSHES=$((DURATION_S / FLUSH_INTERVAL_S)) + # The loop runs inside the Redis container, so the interval is not stretched by docker exec latency. + docker compose exec -T -e REDISCLI_AUTH="$(cat secrets/redis_password)" -e N="$FLUSHES" -e I="$FLUSH_INTERVAL_S" redis \ + sh -c 'i=0; while [ $i -lt $N ]; do sleep $I; redis-cli FLUSHALL >/dev/null; i=$((i+1)); done' +else + sleep "$DURATION_S" +fi + +wait "$K6_PID" + +psql_ -F ',' -c " + SELECT coalesce(sum(calls) FILTER (WHERE query ILIKE '%FROM sessions WHERE%'), 0), + coalesce(sum(calls) FILTER (WHERE query ILIKE '%FROM users WHERE%'), 0), + coalesce(sum(calls), 0) + FROM pg_stat_statements + WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'messenger') + AND query NOT ILIKE '%pg_stat_statements%'" > "$OUT/sql-calls.csv" +psql_ -c " + SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, left(regexp_replace(query, '\s+', ' ', 'g'), 120) + FROM pg_stat_statements + WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'messenger') AND query NOT ILIKE '%pg_stat_statements%' + ORDER BY calls DESC LIMIT 10" > "$OUT/top-queries.txt" +redis INFO stats | tr -d '\r' | grep -E '^keyspace_(hits|misses):' > "$OUT/redis-stats.txt" + +cat > "$OUT/run.json" <>() + + /** + * Only availability changes are logged: with Redis down every request would otherwise add a warning. + */ + private val isCacheAvailable = AtomicBoolean(true) + private val dummyPasswordHash by lazy { hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing") } @@ -94,13 +111,44 @@ class DefaultAuthenticationService( null -> Unit } - val session = suspendedTransaction { + if (!config.sessionCacheSingleFlight) { + return selectSession(tokenHash, now)?.also { cacheSession(it, now) } + } + + val flight = CompletableDeferred() + + inFlightLookups.putIfAbsent(tokenHash, flight)?.let { leader -> + return leader.await() + } + + try { + // The query is shared with the followers, so the leader's own cancellation must not abort it. + val session = withContext(NonCancellable) { + selectSession(tokenHash, now) + } + + flight.complete(session) + + // Requests arriving until the cache write lands reuse this result instead of starting a new lookup. + // A logout drops the flight first (see revokeSession), so a revoked session is never handed out here. + session?.let { cacheSession(it, now) } + + return session + } catch (e: Throwable) { + flight.completeExceptionally(e) + throw e + } finally { + inFlightLookups.remove(tokenHash, flight) + } + } + + private suspend fun selectSession( + tokenHash: String, + now: Instant + ): Session? { + return suspendedTransaction { sessionRepository.findActiveByTokenHash(tokenHash, now) - } ?: return null - - cacheSession(session, now) - - return session + } } override suspend fun revokeSession( @@ -111,11 +159,10 @@ class DefaultAuthenticationService( sessionRepository.deleteById(session.id) } - try { - sessionCacheRepository.revoke(session) - } catch (e: RedisException) { - logger.warn("Session cache is unavailable, revoked session is not tombstoned: ${e.message}") - } + // A lookup that started before the delete must not be joined by requests arriving after the logout. + inFlightLookups.remove(session.tokenHash) + + withCache { sessionCacheRepository.revoke(session) } return isDeleted } @@ -123,26 +170,49 @@ class DefaultAuthenticationService( private suspend fun findCachedSession( tokenHash: String ): CachedSession? { - return try { - sessionCacheRepository.find(tokenHash) - } catch (e: RedisException) { - logger.warn("Session cache is unavailable, reading from the database: ${e.message}") - null - } + return withCache { sessionCacheRepository.find(tokenHash) } } private suspend fun cacheSession( session: Session, now: Instant ) { - try { + withCache { sessionCacheRepository.putIfAbsent( session = session, cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds) ) - } catch (e: RedisException) { - logger.warn("Session cache is unavailable, session is not cached: ${e.message}") } } + /** + * Runs a cache operation, treating an unavailable Redis as a miss: the database stays the source of truth. + * A command already written when Redis drops the connection fails with the raw [IOException] (connection + * reset), not with a [RedisException]; it means the same. + */ + private suspend fun withCache( + operation: suspend () -> T + ): T? { + return try { + operation().also { + if (isCacheAvailable.compareAndSet(false, true)) { + logger.info("Session cache is available again") + } + } + } catch (e: RedisException) { + onCacheUnavailable(e) + } catch (e: IOException) { + onCacheUnavailable(e) + } + } + + private fun onCacheUnavailable( + cause: Exception + ): Nothing? { + if (isCacheAvailable.compareAndSet(true, false)) { + logger.warn("Session cache is unavailable, sessions are read from the database: ${cause.message}") + } + return null + } + } diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf index 0927c5d7..0f2d4033 100644 --- a/src/main/resources/application.conf +++ b/src/main/resources/application.conf @@ -46,4 +46,7 @@ authentication { sessionTtlSeconds = 3600 sessionTtlSeconds = ${?SESSION_TTL_SECONDS} sessionCacheTtlSeconds = 60 + # Collapse concurrent cache misses for one token into a single database lookup (track 1 compares on/off). + sessionCacheSingleFlight = true + sessionCacheSingleFlight = ${?SESSION_CACHE_SINGLE_FLIGHT} } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt index ea0b63e4..f58f9053 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt @@ -85,7 +85,7 @@ class ChatControllerTest { } @Test - fun `failed chat creation leaves no partial rows`() = runApp { client -> + fun `unknown member is rejected before anything is written`() = runApp { client -> val alice = client.register("alice") val title = "atomic-${UUID.randomUUID()}" diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepositoryTest.kt new file mode 100644 index 00000000..e6964807 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepositoryTest.kt @@ -0,0 +1,62 @@ +package com.mtusi.messenger.main.infrastructure.repositories.chat + +import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.exceptions.ExposedSQLException +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +private const val FOREIGN_KEY_VIOLATION = "23503" + +/** + * The service validates members before writing, so the rollback is exercised here directly: the chat row is + * inserted, the membership batch then fails on the foreign key, and the whole transaction must disappear. + */ +class ExposedChatRepositoryTest { + + private val repository = ExposedChatRepository() + + @Test + fun `chat row is rolled back when inserting members fails`() = runApp { client -> + val alice = client.register("alice") + val title = "rollback-${UUID.randomUUID()}" + + val error = assertFailsWith { + transaction { + repository.create(title = title, memberIds = listOf(alice.id, UUID.randomUUID())) + } + } + assertEquals(FOREIGN_KEY_VIOLATION, error.sqlState) + + val (chats, memberships) = transaction { + val chats = ChatModel.selectAll().where(ChatModel.title eq title).count() + val memberships = ChatMemberModel.selectAll().where(ChatMemberModel.userId eq alice.id).count() + chats to memberships + } + assertEquals(0, chats) + assertEquals(0, memberships) + } + + @Test + fun `successful creation commits the chat and every member`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + + val chat = transaction { + repository.create(title = "committed", memberIds = listOf(alice.id, bob.id)) + } + + val memberships = transaction { + ChatMemberModel.selectAll().where(ChatMemberModel.chatId eq chat.id).count() + } + assertEquals(2, memberships) + } + +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt new file mode 100644 index 00000000..06791e4c --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt @@ -0,0 +1,159 @@ +package com.mtusi.messenger.main.infrastructure.services.authentication + +import com.mtusi.messenger.main.config.authentication.SerialAuthenticationConfig +import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository +import com.mtusi.messenger.main.infrastructure.repositories.user.ExposedUserRepository +import com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingService +import com.mtusi.messenger.main.support.TestDatabase +import com.mtusi.messenger.main.utils.computeSha256 +import com.mtusi.messenger.main.utils.nowMicros +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.jetbrains.exposed.v1.jdbc.Database +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant + +private const val CONCURRENT_REQUESTS = 50 +private const val SLOW_QUERY_MS = 200L + +/** + * Cold cache and a deliberately slow lookup, so every request is guaranteed to overlap with the first one. + */ +class SessionLookupSingleFlightTest { + + private val token = "token-${UUID.randomUUID()}" + private val tokenHash = token.toByteArray().computeSha256() + + private val session = Clock.System.nowMicros().let { + Session( + id = UUID.randomUUID(), + userId = UUID.randomUUID(), + tokenHash = tokenHash, + createdAt = it, + expiresAt = it + 1.hours + ) + } + + private class CountingSessionRepository(private val session: Session) : SessionRepository { + + val lookups = AtomicInteger() + + override fun findActiveByTokenHash(tokenHash: String, now: Instant): Session? { + lookups.incrementAndGet() + Thread.sleep(SLOW_QUERY_MS) + return session.takeIf { it.tokenHash == tokenHash } + } + + override fun create(userId: UUID, tokenHash: String, ttl: Duration) = error("not used") + + override fun deleteById(id: UUID) = true + + } + + private class ColdCache : SessionCacheRepository { + + val writes = AtomicInteger() + + override suspend fun find(tokenHash: String): CachedSession? = null + + override suspend fun putIfAbsent(session: Session, cachedUntil: Instant) { + writes.incrementAndGet() + } + + override suspend fun revoke(session: Session) = Unit + + } + + @BeforeTest + fun connect() { + // The fakes do not touch the database, but the service still opens a transaction around the lookup. + TestDatabase.container.let { Database.connect(it.jdbcUrl, user = it.username, password = it.password) } + } + + private fun service(singleFlight: Boolean, repository: SessionRepository, cache: SessionCacheRepository) = + DefaultAuthenticationService( + userRepository = ExposedUserRepository(), + sessionRepository = repository, + sessionCacheRepository = cache, + hashingService = DefaultHashingService(), + config = SerialAuthenticationConfig( + realm = "messenger", + sessionTtlSeconds = 3600, + sessionCacheTtlSeconds = 60, + sessionCacheSingleFlight = singleFlight + ) + ) + + private fun stampede(service: AuthenticationService): List = runBlocking(Dispatchers.Default) { + (0 until CONCURRENT_REQUESTS).map { + async { service.findSessionByToken(token) } + }.awaitAll() + } + + @Test + fun `without single-flight every concurrent miss queries the database`() { + val repository = CountingSessionRepository(session) + val cache = ColdCache() + + val results = stampede(service(singleFlight = false, repository, cache)) + + assertTrue(results.all { it == session }) + assertEquals(CONCURRENT_REQUESTS, repository.lookups.get()) + assertEquals(CONCURRENT_REQUESTS, cache.writes.get()) + } + + @Test + fun `with single-flight concurrent misses share one database lookup`() { + val repository = CountingSessionRepository(session) + val cache = ColdCache() + + val results = stampede(service(singleFlight = true, repository, cache)) + + assertTrue(results.all { it == session }) + assertEquals(1, repository.lookups.get()) + assertEquals(1, cache.writes.get()) + } + + @Test + fun `request arriving after logout does not join a lookup started before it`() = runBlocking(Dispatchers.Default) { + val repository = CountingSessionRepository(session) + val service = service(singleFlight = true, repository, ColdCache()) + + // The leader's query is still running (SLOW_QUERY_MS) when the logout completes. + val leader = async { service.findSessionByToken(token) } + delay(SLOW_QUERY_MS / 4) + service.revokeSession(session) + + val afterLogout = async { service.findSessionByToken(token) } + leader.await() + afterLogout.await() + + assertEquals(2, repository.lookups.get(), "the request after logout must run its own lookup") + } + + @Test + fun `lookup that finished before a request arrived is not reused`() = runBlocking { + val repository = CountingSessionRepository(session) + val service = service(singleFlight = true, repository, ColdCache()) + + service.findSessionByToken(token) + service.findSessionByToken(token) + + assertEquals(2, repository.lookups.get()) + } + +} -- 2.54.0 From ee6e40cc4ecb34bfbcfa00ec5985bf35ea9e298c Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Sat, 10 Oct 2026 00:47:27 +0300 Subject: [PATCH 7/7] Keep logout revocations until written to Redis --- REPORT.md | 6 +- evidence/gradle-tests.txt | 30 +++--- evidence/lost-tombstone.txt | 6 ++ .../dto/authentication/SessionRevocation.kt | 8 ++ .../authentication/SessionRevocationModel.kt | 11 +++ .../cache/RedisSessionCacheRepository.kt | 7 +- .../session/cache/SessionCacheRepository.kt | 5 +- .../ExposedSessionRevocationRepository.kt | 52 ++++++++++ .../revocation/SessionRevocationRepository.kt | 31 ++++++ .../DefaultAuthenticationService.kt | 95 ++++++++++++++++++- .../mtusi/messenger/main/plugins/Database.kt | 4 +- .../migrations/V2__session_revocations.sql | 6 ++ .../cache/RedisSessionCacheRepositoryTest.kt | 4 +- .../SessionLookupSingleFlightTest.kt | 17 +++- .../main/plugins/DependencyFailureTest.kt | 85 +++++++++++++++++ 15 files changed, 341 insertions(+), 26 deletions(-) create mode 100644 evidence/lost-tombstone.txt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/SessionRevocation.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionRevocationModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/ExposedSessionRevocationRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/SessionRevocationRepository.kt create mode 100644 src/main/resources/migrations/V2__session_revocations.sql diff --git a/REPORT.md b/REPORT.md index b711f71d..9bd74764 100644 --- a/REPORT.md +++ b/REPORT.md @@ -74,6 +74,7 @@ docker compose down -v - Чтение по схеме cache-aside: сначала Redis, если ключа нет — PostgreSQL, потом запись в Redis через `SET ... NX PXAT`. - Срок жизни ключа — меньшее из `expires_at` сессии и 60 секунд (`sessionCacheTtlSeconds`). Срок сессии к тому же сверяется в коде при каждом запросе, так что просроченная сессия не пройдёт, даже если ключ ещё жив. - Logout сначала удаляет сессию в PostgreSQL, потом пишет в ключ метку `revoked` до `expires_at`. Заполнение кэша идёт только через `NX`, поэтому запрос, который прочитал сессию из базы до logout и пишет её в кэш после, метку не перетрёт. +- Метка может не дойти до Redis, если он в этот момент лежит или завис, а копия сессии, закэшированная до сбоя, в Redis при этом останется. Поэтому logout в той же транзакции, что и удаление сессии, пишет строку в `session_revocations` (миграция `V2`) и удаляет её только после того, как метка записана. После любой ошибки Redis и при старте API кэшу не доверяют: чтения идут в базу, пока один запрос не допишет в Redis все метки из `session_revocations`. Неудачная попытка повторяется не чаще раза в секунду. - Если Redis недоступен (отказ соединения или таймаут 500 мс), чтение идёт мимо кэша в PostgreSQL, logout тоже работает: он нужен только базе. После неудачного подключения следующая попытка не раньше чем через секунду, а команды без соединения сразу отклоняются, поэтому лежащий Redis не тормозит запросы. - Промахи по одному токену схлопываются (single-flight): если поиск сессии в базе для этого токена уже идёт, следующие запросы ждут его результат, а не отправляют свой SELECT. Это защита от cache stampede, подробно в треке 1. Включается `SESSION_CACHE_SINGLE_FLIGHT` (по умолчанию `true`), выключатель оставлен для сравнения в эксперименте. - В лог пишется только смена состояния кэша («unavailable» и «available again»), а не каждый промах. Иначе при лежащем Redis API пишет по предупреждению на запрос. @@ -119,8 +120,9 @@ docker compose down -v | Rollback составной операции | `chat row is rolled back when inserting members fails` | см. строку про атомарность выше | evidence/gradle-tests.txt | | Индекс истории и EXPLAIN на ≥ 10 000 сообщений | `./scripts/explain-history.sh` | 70 000 сообщений, глубокая страница по курсору: Index Scan, 4 буфера, 0,03 мс. Без индекса: Seq Scan, 914 буферов. Разбор ниже | evidence/explain-history.txt | | Недоступность Redis | `docker compose stop redis`; `DependencyFailureTest` (отказ соединения и `docker pause`) | запросы с токеном 200, вход 201, logout 204 и токен сразу 401, анонимный запрос 401; при зависшем Redis запрос дольше максимум на один таймаут | evidence/failures.txt, evidence/gradle-tests.txt | +| Logout при недоступном Redis, потом рестарт API | `DependencyFailureTest`: `logout during a Redis outage is not undone by a stale cached copy`, `... survives an API restart`; то же на живом стенде (`docker compose pause redis`, logout, `unpause`, вернул в ключ старую копию сессии, `restart api`) | logout 204; после восстановления Redis и после рестарта API тот же токен 401 на чтение и на отправку сообщения, в ключе снова `revoked`, в логе `Wrote 1 pending session revocations to the cache`. Без исправления оба теста падали: токен получал 200 | evidence/lost-tombstone.txt, evidence/gradle-tests.txt | | Недоступность БД | `docker compose stop postgres`; `DependencyFailureTest` | `/health/live` 200, `/health/ready` 503, запросы с токеном и вход — 503 `unavailable` примерно за 2 с, без токена и с `X-User-Id` — 401. После старта базы тот же токен снова 200 | evidence/failures.txt | -| Свои автотесты | `./gradlew test` | 56 тестов, все проходят | evidence/gradle-tests.txt | +| Свои автотесты | `./gradlew test` | 58 тестов, все проходят | evidence/gradle-tests.txt | | Трек 1: cache stampede на конкурентном сценарии | `./scripts/track1/stampede.sh` с `VARIANT=off`, 200 VU, `FLUSHALL` раз в секунду | на каждую сессию за один сброс кэша в базу уходит 3,1 SELECT при 50 сессиях и 10,5 при 10 сессиях; запросов к `sessions` 4 651 и 3 138 за 30 с | evidence/track1/summary.md, evidence/track1/stampede/off/ | | Трек 1: защита и измерение до/после | то же с `VARIANT=on` (single-flight) | 0,97 SELECT на сессию за сброс в обоих случаях: запросов к `sessions` в 3,2 и 10,8 раза меньше. RPS и p50/p95/p99 в пределах шума | evidence/track1/summary.md, evidence/track1/stampede-runs.csv | | Трек 1: read-after-write из контракта | `./scripts/track1/read-after-write.sh`: 300 итераций, 16 параллельных читателей, logout посреди первого заполнения кэша; с защитой и без, Redis работает и остановлен | 1 200 итераций, 1,53 млн запросов, начатых после ответа 204 на logout: ни одного 200. Первый запрос после входа всегда 200. Через секунду ни один отозванный токен не ожил | evidence/track1/read-after-write/ | @@ -260,7 +262,7 @@ Redis у меня без persistence, поэтому после рестарта ## Ограничения и следующие шаги -- Если logout пришёлся на время, когда Redis лежал, метка `revoked` не записывается. Тогда копия сессии, закэшированная до сбоя, после возвращения Redis может прожить ещё до 60 секунд. Поэтому TTL кэша и ограничен 60 секундами, а не сроком сессии. Пока Redis недоступен, такой проблемы нет: все чтения идут в базу. +- Недоверие к кэшу после сбоя Redis живёт внутри процесса. С несколькими репликами API (lab3) реплика, которая сама не видела ошибку Redis, может прочитать старую копию отозванной сессии, пока метку не допишет другая реплика (обычно на первом же её запросе) или пока не истечёт TTL копии (до 60 с). Для реплик нужен общий признак, например номер поколения кэша в PostgreSQL. - Неизвестный токен при лежащей базе получает 503, а не 401. Проверить его без базы нельзя, а пустить нельзя, так что это осознанно. - PostgreSQL один, без реплик и бэкапов. Если пропадёт volume, пропадут данные. Durability — стандартная для PostgreSQL (`fsync`, `synchronous_commit` по умолчанию включены): после ответа 201 запись уже в WAL на диске. - Просроченные сессии из таблицы `sessions` не удаляются, они только перестают проходить проверку. Нужна периодическая чистка, сейчас её нет. diff --git a/evidence/gradle-tests.txt b/evidence/gradle-tests.txt index bd16314f..07f856b0 100644 --- a/evidence/gradle-tests.txt +++ b/evidence/gradle-tests.txt @@ -1,7 +1,7 @@ # ./gradlew test (Testcontainers: postgres:17.6-alpine3.22, redis:8.4.0-alpine) -total: 56 tests, 0 failed +total: 58 tests, 0 failed -infrastructure.controllers.authentication.AuthenticationControllerTest: 9 tests, 0 failed, 7.771 s +infrastructure.controllers.authentication.AuthenticationControllerTest: 9 tests, 0 failed, 4.301 s - logout revokes only the current token - Bearer token cannot open a session - password containing a colon and non-ASCII characters works @@ -11,19 +11,19 @@ infrastructure.controllers.authentication.AuthenticationControllerTest: 9 tests, - valid Basic credentials open a session - missing or malformed Basic header returns 401 - wrong password and unknown user get the same 401 -infrastructure.controllers.chat.ChatControllerTest: 6 tests, 0 failed, 2.042 s +infrastructure.controllers.chat.ChatControllerTest: 6 tests, 0 failed, 2.154 s - member can read own chat and members keep their order - unknown member is rejected before anything is written - foreign chat returns 404 for non-member - cursor issued to another user is rejected - chat list contains only own chats and is paginated - invalid member lists are rejected with 400 -infrastructure.controllers.health.HealthControllerTest: 2 tests, 0 failed, 0.128 s +infrastructure.controllers.health.HealthControllerTest: 2 tests, 0 failed, 0.125 s - live returns 200 - ready returns 200 when database is reachable -infrastructure.controllers.message.MessageConcurrencyTest: 1 tests, 0 failed, 0.281 s +infrastructure.controllers.message.MessageConcurrencyTest: 1 tests, 0 failed, 0.308 s - parallel senders produce exactly N unique messages -infrastructure.controllers.message.MessageControllerTest: 7 tests, 0 failed, 1.864 s +infrastructure.controllers.message.MessageControllerTest: 7 tests, 0 failed, 1.846 s - foreign chat returns 404 when sending - last page has null next_cursor - pagination walks all messages exactly once @@ -31,7 +31,7 @@ infrastructure.controllers.message.MessageControllerTest: 7 tests, 0 failed, 1.8 - empty text returns 400 invalid_request - history that is an exact multiple of limit ends with null next_cursor - foreign cursor returns 400 -infrastructure.controllers.user.UserControllerTest: 11 tests, 0 failed, 1.7 s +infrastructure.controllers.user.UserControllerTest: 11 tests, 0 failed, 1.861 s - password shorter than 12 code points returns 400 - concurrent registrations of one username create exactly one user - X-User-Id alone gives no access @@ -43,30 +43,32 @@ infrastructure.controllers.user.UserControllerTest: 11 tests, 0 failed, 1.7 s - Basic credentials are rejected on business endpoints - me returns the session owner - X-User-Id does not override bearer identity -infrastructure.repositories.authentication.session.cache.RedisSessionCacheRepositoryTest: 3 tests, 0 failed, 0.1 s +infrastructure.repositories.authentication.session.cache.RedisSessionCacheRepositoryTest: 3 tests, 0 failed, 0.141 s - cached session round-trips and expires together with the session - revoke replaces a cached session with a tombstone - late cache fill cannot overwrite a tombstone -infrastructure.repositories.chat.ExposedChatRepositoryTest: 2 tests, 0 failed, 0.529 s +infrastructure.repositories.chat.ExposedChatRepositoryTest: 2 tests, 0 failed, 0.479 s - chat row is rolled back when inserting members fails - successful creation commits the chat and every member -infrastructure.services.authentication.SessionLookupSingleFlightTest: 4 tests, 0 failed, 1.107 s +infrastructure.services.authentication.SessionLookupSingleFlightTest: 4 tests, 0 failed, 1.102 s - request arriving after logout does not join a lookup started before it - without single-flight every concurrent miss queries the database - with single-flight concurrent misses share one database lookup - lookup that finished before a request arrived is not reused -infrastructure.services.hashing.DefaultHashingServiceTest: 4 tests, 0 failed, 0.425 s +infrastructure.services.hashing.DefaultHashingServiceTest: 4 tests, 0 failed, 0.426 s - passwords differing only after 72 bytes are distinguished - validates the right password and rejects a wrong one - malformed hash is rejected instead of throwing - hash is a salted Argon2id PHC string -plugins.DatabaseMigrationTest: 1 tests, 0 failed, 0.206 s +plugins.DatabaseMigrationTest: 1 tests, 0 failed, 0.182 s - re-running migrations applies nothing and keeps data -plugins.DependencyFailureTest: 3 tests, 0 failed, 8.502 s +plugins.DependencyFailureTest: 5 tests, 0 failed, 25.189 s - without PostgreSQL requests fail with a bounded 503 + - logout during a Redis outage survives an API restart + - logout during a Redis outage is not undone by a stale cached copy - without Redis requests bypass the cache - hanging Redis costs one command timeout and recovers -plugins.SessionCacheTest: 3 tests, 0 failed, 0.963 s +plugins.SessionCacheTest: 3 tests, 0 failed, 1.025 s - emptied cache falls back to PostgreSQL - first authenticated request fills the cache - logout leaves a tombstone and the token is rejected diff --git a/evidence/lost-tombstone.txt b/evidence/lost-tombstone.txt new file mode 100644 index 00000000..47c8c12e --- /dev/null +++ b/evidence/lost-tombstone.txt @@ -0,0 +1,6 @@ +me: 200 +logout (redis paused): 204 +redis before restart: {"id":"3aa6c510-992e-45ed-9bb3-61f04e23d +me after api restart: 401 +redis after: revoked +mtusi-lab2-api | 2026-10-09T20:53:02.205Z INFO [DefaultDispatcher-worker-1] c.m.m.m.i.s.a.DefaultAuthenticationService - Wrote 1 pending session revocations to the cache diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/SessionRevocation.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/SessionRevocation.kt new file mode 100644 index 00000000..a02cf062 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/SessionRevocation.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.infrastructure.dto.authentication + +import kotlin.time.Instant + +data class SessionRevocation( + val tokenHash: String, + val expiresAt: Instant, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionRevocationModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionRevocationModel.kt new file mode 100644 index 00000000..13e791dc --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionRevocationModel.kt @@ -0,0 +1,11 @@ +package com.mtusi.messenger.main.infrastructure.models.authentication + +import org.jetbrains.exposed.v1.core.Table +import org.jetbrains.exposed.v1.datetime.timestamp + +object SessionRevocationModel : Table("session_revocations") { + val tokenHash = varchar("token_hash", 64) + val expiresAt = timestamp("expires_at") + + override val primaryKey = PrimaryKey(tokenHash, name = "session_revocations_pkey") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt index 2035dd4a..5cd22fc3 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepository.kt @@ -45,12 +45,13 @@ class RedisSessionCacheRepository( } override suspend fun revoke( - session: Session + tokenHash: String, + expiresAt: Instant ) { redis.commands().set( - key(session.tokenHash), + key(tokenHash), REVOKED, - SetArgs.Builder.pxAt(session.expiresAt.toEpochMilliseconds()) + SetArgs.Builder.pxAt(expiresAt.toEpochMilliseconds()) ).await() } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt index c35340c1..c244cc95 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/SessionCacheRepository.kt @@ -24,10 +24,11 @@ interface SessionCacheRepository : Repository { ) /** - * Replaces the entry with a tombstone that lives until the session would have expired. + * Replaces the entry with a tombstone that lives until [expiresAt], when the session would have expired. */ suspend fun revoke( - session: Session + tokenHash: String, + expiresAt: Instant ) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/ExposedSessionRevocationRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/ExposedSessionRevocationRepository.kt new file mode 100644 index 00000000..9ca4227a --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/ExposedSessionRevocationRepository.kt @@ -0,0 +1,52 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation + +import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation +import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.greater +import org.jetbrains.exposed.v1.core.lessEq +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.insertIgnore +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.koin.core.annotation.Single +import kotlin.time.Instant + +@Single +class ExposedSessionRevocationRepository : SessionRevocationRepository { + + override fun add( + revocation: SessionRevocation + ) { + SessionRevocationModel.insertIgnore { + it[tokenHash] = revocation.tokenHash + it[expiresAt] = revocation.expiresAt + } + } + + override fun findPending( + now: Instant + ): List { + return SessionRevocationModel + .selectAll() + .where(SessionRevocationModel.expiresAt greater now) + .map { + SessionRevocation( + tokenHash = it[SessionRevocationModel.tokenHash], + expiresAt = it[SessionRevocationModel.expiresAt] + ) + } + } + + override fun delete( + tokenHash: String + ) { + SessionRevocationModel.deleteWhere { SessionRevocationModel.tokenHash eq tokenHash } + } + + override fun deleteExpired( + now: Instant + ) { + SessionRevocationModel.deleteWhere { SessionRevocationModel.expiresAt lessEq now } + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/SessionRevocationRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/SessionRevocationRepository.kt new file mode 100644 index 00000000..8612e876 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/revocation/SessionRevocationRepository.kt @@ -0,0 +1,31 @@ +package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation + +import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation +import com.mtusi.messenger.main.infrastructure.repositories.Repository +import kotlin.time.Instant + +/** + * Logouts that still have to be written to the session cache as tombstones (outbox). + */ +interface SessionRevocationRepository : Repository { + + fun add( + revocation: SessionRevocation + ) + + /** + * Revocations of sessions that have not expired yet: an expired session is rejected even if its copy is cached. + */ + fun findPending( + now: Instant + ): List + + fun delete( + tokenHash: String + ) + + fun deleteExpired( + now: Instant + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt index 8c4f6e59..9bfc3df9 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt @@ -4,17 +4,21 @@ import com.mtusi.messenger.main.config.authentication.AuthenticationConfig import com.mtusi.messenger.main.infrastructure.dto.User import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation.SessionRevocationRepository import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm import com.mtusi.messenger.main.plugins.suspendedTransaction import com.mtusi.messenger.main.utils.computeSha256 import io.lettuce.core.RedisException +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withContext import org.koin.core.annotation.Single import org.slf4j.LoggerFactory @@ -24,17 +28,22 @@ import java.util.Base64 import java.util.UUID import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong import kotlin.time.Clock import kotlin.time.Instant import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource private const val TOKEN_BYTES = 32 +private val CACHE_RESTORE_BACKOFF = 1.seconds + @Single class DefaultAuthenticationService( private val userRepository: UserRepository, private val sessionRepository: SessionRepository, private val sessionCacheRepository: SessionCacheRepository, + private val sessionRevocationRepository: SessionRevocationRepository, private val hashingService: HashingService, private val config: AuthenticationConfig ) : AuthenticationService { @@ -54,6 +63,21 @@ class DefaultAuthenticationService( */ private val isCacheAvailable = AtomicBoolean(true) + /** + * Number of failed cache operations. A failure may have lost a logout tombstone, so the cache is trusted only + * after the pending revocations were written to it with no failure since: [trustedAtFailures] equals this counter. + * A fresh process starts untrusted, as the previous one may have stopped with revocations still pending. + */ + private val cacheFailures = AtomicLong() + + @Volatile + private var trustedAtFailures = -1L + + private val cacheRestoreMutex = Mutex() + + @Volatile + private var nextCacheRestoreAttempt = TimeSource.Monotonic.markNow() + private val dummyPasswordHash by lazy { hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing") } @@ -155,14 +179,20 @@ class DefaultAuthenticationService( session: Session ): Boolean { + // The revocation is kept in PostgreSQL until its tombstone is in Redis: if Redis is unavailable now, + // the tombstone is written when the cache is trusted again (see restoreCache), even after a restart. val isDeleted = suspendedTransaction { + sessionRevocationRepository.add(SessionRevocation(session.tokenHash, session.expiresAt)) sessionRepository.deleteById(session.id) } // A lookup that started before the delete must not be joined by requests arriving after the logout. inFlightLookups.remove(session.tokenHash) - withCache { sessionCacheRepository.revoke(session) } + if (withCache { sessionCacheRepository.revoke(session.tokenHash, session.expiresAt) } != null) { + // Best effort: a leftover row only costs one more tombstone write on the next restore. + runCatchingDatabase { sessionRevocationRepository.delete(session.tokenHash) } + } return isDeleted } @@ -170,9 +200,71 @@ class DefaultAuthenticationService( private suspend fun findCachedSession( tokenHash: String ): CachedSession? { + if (trustedAtFailures != cacheFailures.get() && !restoreCache()) { + return null + } return withCache { sessionCacheRepository.find(tokenHash) } } + /** + * Writes the tombstones of logouts that happened while Redis was unavailable. Until that succeeds the cache + * is bypassed: a copy cached before the outage could otherwise outlive the logout. One request restores, + * the others go to the database meanwhile; a failed attempt is repeated after [CACHE_RESTORE_BACKOFF]. + */ + private suspend fun restoreCache(): Boolean { + + if (!cacheRestoreMutex.tryLock()) { + return false + } + + try { + val failures = cacheFailures.get() + + if (trustedAtFailures == failures) { + return true + } + if (nextCacheRestoreAttempt.hasNotPassedNow()) { + return false + } + nextCacheRestoreAttempt = TimeSource.Monotonic.markNow() + CACHE_RESTORE_BACKOFF + + val now = Clock.System.now() + + val pending = runCatchingDatabase { + sessionRevocationRepository.deleteExpired(now) + sessionRevocationRepository.findPending(now) + } ?: return false + + for (revocation in pending) { + withCache { sessionCacheRepository.revoke(revocation.tokenHash, revocation.expiresAt) } ?: return false + } + + if (pending.isNotEmpty()) { + runCatchingDatabase { pending.forEach { sessionRevocationRepository.delete(it.tokenHash) } } + logger.info("Wrote ${pending.size} pending session revocations to the cache") + } + + // A failure while restoring changed the counter, so the cache stays untrusted. + trustedAtFailures = failures + return trustedAtFailures == cacheFailures.get() + } finally { + cacheRestoreMutex.unlock() + } + } + + private suspend fun runCatchingDatabase( + statement: () -> T + ): T? { + return try { + suspendedTransaction { statement() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.warn("Unable to update pending session revocations: ${e.message}") + null + } + } + private suspend fun cacheSession( session: Session, now: Instant @@ -209,6 +301,7 @@ class DefaultAuthenticationService( private fun onCacheUnavailable( cause: Exception ): Nothing? { + cacheFailures.incrementAndGet() if (isCacheAvailable.compareAndSet(true, false)) { logger.warn("Session cache is unavailable, sessions are read from the database: ${cause.message}") } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt index f3ea24ed..32001ed3 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -3,6 +3,7 @@ package com.mtusi.messenger.main.plugins import com.mtusi.messenger.main.config.database.DatabaseConfig import com.mtusi.messenger.main.config.database.SerialDatabaseConfig import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel +import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel import com.mtusi.messenger.main.infrastructure.models.message.MessageModel @@ -95,7 +96,8 @@ private fun generateMigration(description: String) { ChatModel, ChatMemberModel, MessageModel, - SessionModel + SessionModel, + SessionRevocationModel ) val config = HoconApplicationConfig(ConfigFactory.parseFile(File(DEVELOPMENT_DATABASE_CONFIG)).resolve()) diff --git a/src/main/resources/migrations/V2__session_revocations.sql b/src/main/resources/migrations/V2__session_revocations.sql new file mode 100644 index 00000000..4b15c00c --- /dev/null +++ b/src/main/resources/migrations/V2__session_revocations.sql @@ -0,0 +1,6 @@ +-- Logouts whose tombstone has not reached Redis yet. Written in the same transaction as the session delete and +-- removed once the tombstone is stored, so a copy cached before an outage cannot outlive the logout. +CREATE TABLE session_revocations ( + token_hash varchar(64) PRIMARY KEY, + expires_at timestamptz NOT NULL +); diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt index ed2007dc..8f27e66f 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/cache/RedisSessionCacheRepositoryTest.kt @@ -63,7 +63,7 @@ class RedisSessionCacheRepositoryTest { val session = session() repository.putIfAbsent(session, cachedUntil = session.expiresAt) - repository.revoke(session) + repository.revoke(session.tokenHash, session.expiresAt) assertEquals(CachedSession.Revoked, repository.find(session.tokenHash)) assertTrue(ttlSeconds(session) in 590..600, "tombstone must live until the session would expire") @@ -74,7 +74,7 @@ class RedisSessionCacheRepositoryTest { val session = session() // A lookup read the session from PostgreSQL before logout and stores it after the logout finished. - repository.revoke(session) + repository.revoke(session.tokenHash, session.expiresAt) repository.putIfAbsent(session, cachedUntil = session.expiresAt) assertEquals(CachedSession.Revoked, repository.find(session.tokenHash)) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt index 06791e4c..01df4eed 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/SessionLookupSingleFlightTest.kt @@ -2,9 +2,11 @@ package com.mtusi.messenger.main.infrastructure.services.authentication import com.mtusi.messenger.main.config.authentication.SerialAuthenticationConfig import com.mtusi.messenger.main.infrastructure.dto.authentication.Session +import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository +import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation.SessionRevocationRepository import com.mtusi.messenger.main.infrastructure.repositories.user.ExposedUserRepository import com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingService import com.mtusi.messenger.main.support.TestDatabase @@ -74,7 +76,19 @@ class SessionLookupSingleFlightTest { writes.incrementAndGet() } - override suspend fun revoke(session: Session) = Unit + override suspend fun revoke(tokenHash: String, expiresAt: Instant) = Unit + + } + + private object NoRevocations : SessionRevocationRepository { + + override fun add(revocation: SessionRevocation) = Unit + + override fun findPending(now: Instant) = emptyList() + + override fun delete(tokenHash: String) = Unit + + override fun deleteExpired(now: Instant) = Unit } @@ -89,6 +103,7 @@ class SessionLookupSingleFlightTest { userRepository = ExposedUserRepository(), sessionRepository = repository, sessionCacheRepository = cache, + sessionRevocationRepository = NoRevocations, hashingService = DefaultHashingService(), config = SerialAuthenticationConfig( realm = "messenger", diff --git a/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt b/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt index eaec7e10..2a171457 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/plugins/DependencyFailureTest.kt @@ -1,8 +1,11 @@ package com.mtusi.messenger.main.plugins import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest +import com.mtusi.messenger.main.infrastructure.dto.Chat import com.mtusi.messenger.main.support.TestDatabase import com.mtusi.messenger.main.support.TestRedis +import com.mtusi.messenger.main.support.TestUser import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat import com.mtusi.messenger.main.support.register @@ -15,8 +18,12 @@ import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post +import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import org.testcontainers.containers.GenericContainer import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -101,6 +108,84 @@ class DependencyFailureTest { } } + /** + * The tombstone written by a logout during an outage can be lost while the copy cached before it survives + * (here: put back by hand). The revocation kept in PostgreSQL must still win once Redis is reachable again. + */ + private fun loseTombstone(redis: GenericContainer<*>, user: TestUser, cachedCopy: String) { + TestRedis.cli(redis, "SET", "session:${user.token.toByteArray().computeSha256()}", cachedCopy, "PX", "60000") + } + + private fun cachedCopy(redis: GenericContainer<*>, user: TestUser): String { + return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}") + .also { assertTrue(it.contains(user.id.toString()), "session must be cached before the outage") } + } + + @Test + fun `logout during a Redis outage is not undone by a stale cached copy`() { + val redis = TestRedis.create().also { it.start() } + val docker = redis.dockerClient + + try { + runApp(redis = TestRedis.endpoint(redis)) { client -> + val alice = client.register("alice") + assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) + val copy = cachedCopy(redis, alice) + + docker.pauseContainerCmd(redis.containerId).exec() + assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + docker.unpauseContainerCmd(redis.containerId).exec() + + loseTombstone(redis, alice, copy) + + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + assertEquals("revoked", TestRedis.cli(redis, "GET", "session:${alice.token.toByteArray().computeSha256()}")) + } + } finally { + redis.stop() + } + } + + @Test + fun `logout during a Redis outage survives an API restart`() { + val redis = TestRedis.create().also { it.start() } + val docker = redis.dockerClient + + lateinit var alice: TestUser + lateinit var chat: Chat + lateinit var copy: String + + try { + runApp(redis = TestRedis.endpoint(redis)) { client -> + alice = client.register("alice") + val bob = client.register("bob") + chat = client.createChat(alice, "restart", listOf(alice.id, bob.id)) + copy = cachedCopy(redis, alice) + + docker.pauseContainerCmd(redis.containerId).exec() + assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status) + } + + docker.unpauseContainerCmd(redis.containerId).exec() + loseTombstone(redis, alice, copy) + + runApp(redis = TestRedis.endpoint(redis)) { client -> + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/chats/${chat.id}/messages") { auth(alice) }.status) + assertEquals( + HttpStatusCode.Unauthorized, + client.post("/api/v1/chats/${chat.id}/messages") { + auth(alice) + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest(text = "after logout")) + }.status + ) + } + } finally { + redis.stop() + } + } + @Test fun `without PostgreSQL requests fail with a bounded 503`() { val database = TestDatabase.create().also { it.start() } -- 2.54.0