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 00000000..1b33c55b Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ca025c83 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..23d15a93 --- /dev/null +++ b/gradlew @@ -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" "$@" 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 + } +}