forked from mtusi2026/mtusi2026lab2
Move lab1 to lab2
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
+19
@@ -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"]
|
||||
@@ -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<JavaExec>("run") {
|
||||
workingDir = file("run/development")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
kotlin.code.style=official
|
||||
@@ -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" }
|
||||
Vendored
BIN
Binary file not shown.
+7
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# 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" "$@"
|
||||
Vendored
+94
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
ktor {
|
||||
application {
|
||||
modules = [com.mtusi.messenger.main.AppKt.module]
|
||||
}
|
||||
|
||||
deployment {
|
||||
host = "127.0.0.1"
|
||||
port = 8080
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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<String>): 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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
+67
@@ -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<CreateChatRequest>()
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+9
@@ -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<String>,
|
||||
)
|
||||
+10
@@ -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<Chat>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
+20
@@ -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())
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -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")
|
||||
+65
@@ -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<CreateMessageRequest>()
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message.requests
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CreateMessageRequest(
|
||||
val text: String,
|
||||
)
|
||||
+10
@@ -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<Message>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
+41
@@ -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<CreateUserRequest>()
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -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,
|
||||
)
|
||||
@@ -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<String>,
|
||||
val createdAt: String,
|
||||
)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories
|
||||
|
||||
interface Repository<TId, TEntity>
|
||||
+12
@@ -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<String, Chat> {
|
||||
fun findById(id: String): Chat?
|
||||
|
||||
fun insert(chat: Chat)
|
||||
|
||||
fun findAllAccessible(userId: String): List<Chat>
|
||||
}
|
||||
+24
@@ -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<String, Chat>()
|
||||
|
||||
override fun findById(id: String): Chat? = byId[id]
|
||||
|
||||
override fun insert(chat: Chat) {
|
||||
byId[chat.id] = chat
|
||||
}
|
||||
|
||||
override fun findAllAccessible(userId: String): List<Chat> =
|
||||
byId.values
|
||||
.filter { userId in it.memberIds }
|
||||
.sortedWith(
|
||||
compareBy(
|
||||
{ it.createdAt },
|
||||
{ it.id }
|
||||
)
|
||||
)
|
||||
}
|
||||
+45
@@ -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<String, CopyOnWriteArrayList<Message>>()
|
||||
private val locks = ConcurrentHashMap<String, Any>()
|
||||
|
||||
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<Message> {
|
||||
|
||||
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] }
|
||||
}
|
||||
}
|
||||
+9
@@ -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<String, Message> {
|
||||
fun append(chatId: String, message: Message)
|
||||
fun findRangeByChatId(chatId: String, offset: Int, count: Int): List<Message>
|
||||
}
|
||||
+18
@@ -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<String, User>()
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
+12
@@ -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<String, User> {
|
||||
fun insert(user: User)
|
||||
|
||||
fun findById(id: String): User?
|
||||
|
||||
fun findByUsername(username: String): User?
|
||||
}
|
||||
@@ -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<String>,
|
||||
): Chat
|
||||
|
||||
fun findAccessible(
|
||||
userId: String,
|
||||
chatId: String,
|
||||
): Chat
|
||||
|
||||
fun findPageAccessible(
|
||||
userId: String,
|
||||
rawLimit: String?,
|
||||
rawCursor: String?,
|
||||
): Page<Chat>
|
||||
}
|
||||
+92
@@ -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<String>,
|
||||
): 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<Chat> {
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+74
@@ -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<Message> {
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -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<Message>
|
||||
}
|
||||
+33
@@ -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)
|
||||
}
|
||||
@@ -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?
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.mtusi.messenger.main.infrastructure.types
|
||||
|
||||
class ApiException(val code: ErrorCode, message: String) : RuntimeException(message)
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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<String> = 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)
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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<ApiException> { call, cause ->
|
||||
call.respondError(cause.code, cause.message ?: cause.code.wire)
|
||||
}
|
||||
exception<JsonConvertException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
|
||||
}
|
||||
exception<SerializationException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
|
||||
}
|
||||
exception<BadRequestException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid request")
|
||||
}
|
||||
exception<NotFoundException> { call, _ ->
|
||||
call.respondError(ErrorCode.NOT_FOUND, "not found")
|
||||
}
|
||||
exception<UnsupportedMediaTypeException> { call, _ ->
|
||||
call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type")
|
||||
}
|
||||
exception<Throwable> { 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")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
data class Page<T>(
|
||||
val items: List<T>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%thread] %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
<logger name="io.netty" level="WARN"/>
|
||||
<logger name="org.eclipse.jetty" level="WARN"/>
|
||||
</configuration>
|
||||
+43
@@ -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<ErrorBody>().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<Chat>().id)
|
||||
}
|
||||
}
|
||||
+22
@@ -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)
|
||||
}
|
||||
}
|
||||
+74
@@ -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<String>()
|
||||
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<MessagePageResponse>()
|
||||
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())
|
||||
}
|
||||
}
|
||||
+190
@@ -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<ErrorBody>().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<ErrorBody>().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<String>()
|
||||
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<MessagePageResponse>()
|
||||
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<MessagePageResponse>()
|
||||
|
||||
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<MessagePageResponse>()
|
||||
|
||||
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<MessagePageResponse>()
|
||||
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<MessagePageResponse>()
|
||||
|
||||
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<ErrorBody>().error.code)
|
||||
}
|
||||
}
|
||||
+72
@@ -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<ErrorBody>()
|
||||
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<ErrorBody>().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<ErrorBody>().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)
|
||||
}
|
||||
}
|
||||
+58
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
): 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]
|
||||
@@ -0,0 +1,10 @@
|
||||
ktor {
|
||||
application {
|
||||
modules = [com.mtusi.messenger.main.AppKt.module]
|
||||
}
|
||||
|
||||
deployment {
|
||||
host = "127.0.0.1"
|
||||
port = 0
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user