new files added

This commit is contained in:
AK
2026-07-22 21:44:05 +03:00
commit c8ff305aa6
38 changed files with 1127 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
.DS_Store
.env
+53
View File
@@ -0,0 +1,53 @@
# UserService
This project was created using the [Ktor Project Generator](https://start.ktor.io).
Here are some useful links to get you started:
* [Ktor Documentation](https://ktor.io/docs/home.html)
* [Ktor GitHub page](https://github.com/ktorio/ktor)
* [Ktor Slack chat](https://app.slack.com/client/T09229ZC6/C0A974TJ9). [Request an invite](https://surveys.jetbrains.com/s3/kotlin-slack-sign-up).
## Features
Here's a list of features included in this project:
| Name | Description |
|------|-------------|
| [kotlinx.serialization](https://start.ktor.io/p/io.ktor/server-kotlinx-serialization) | Handles JSON serialization using kotlinx.serialization library |
| [Content Negotiation](https://start.ktor.io/p/io.ktor/server-content-negotiation) | Provides automatic content conversion according to Content-Type and Accept headers |
| [gRPC](https://start.ktor.io/p/org.jetbrains/kotlinx-rpc-grpc) | Adds gRPC services to your Ktor server with kotlinx.rpc |
| [Rate Limiting](https://start.ktor.io/p/io.github.flaxoos/server-rate-limiting) | Manage request rate limiting as you see fit |
| [Kafka](https://start.ktor.io/p/io.github.flaxoos/server-kafka) | Adds Kafka support to your application |
| [Exposed](https://start.ktor.io/p/org.jetbrains/server-exposed) | Adds Exposed database to your application |
| [Dependency Injection](https://start.ktor.io/p/io.ktor/server-di) | Enables dependency injection for your server |
| [OpenTelemetry](https://start.ktor.io/p/io.opentelemetry.instrumentation/server-open-telemetry) | Instruments applications with distributed tracing, metrics, and logging for comprehensive observability |
| [Sessions](https://start.ktor.io/p/io.ktor/server-sessions) | Adds support for persistent sessions through cookies or headers |
| [Authentication](https://start.ktor.io/p/io.ktor/server-auth) | Provides extension point for handling the Authorization header |
| [Authentication Basic](https://start.ktor.io/p/io.ktor/server-auth-basic) | Handles 'Basic' username / password authentication scheme |
| [Swagger](https://start.ktor.io/p/io.ktor/server-swagger) | Serves Swagger UI for your project |
## Structure
This project includes the following modules:
| Path | Description |
|------|-------------|
| | null |
| client | null |
| core | null |
| server | null |
## Building & Running
To build or run the project, use one of the following tasks:
| Task | Description |
|------|-------------|
| `./gradlew :server:test` | Run the tests |
| `./gradlew :server:build` | Build the project |
| `./gradlew :server:run` | Run the server |
If the server starts successfully, you'll see the following output:
```
2024-12-04 14:32:45.584 [main] INFO Application - Application started in 0.303 seconds.
2024-12-04 14:32:45.682 [main] INFO Application - Responding at http://0.0.0.0:8080
```
+12
View File
@@ -0,0 +1,12 @@
plugins {
alias(libs.plugins.kotlin.multiplatform) apply false
alias(libs.plugins.kotlin.jvm) apply false
alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.kotlinx.rpc.grpc) apply false
}
subprojects {
group = "tech.aklivtsov"
version = "1.0.0-SNAPSHOT"
}
+23
View File
@@ -0,0 +1,23 @@
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.kotlinx.rpc.grpc)
}
rpc {
protoc()
}
kotlin {
jvm()
sourceSets {
commonMain.dependencies {
implementation(ktorLibs.client.core)
implementation(libs.kotlinx.rpc.grpc.client)
implementation(project(":core"))
}
}
}
@@ -0,0 +1,22 @@
package tech.aklivtsov
import kotlinx.rpc.grpc.client.GrpcClient
import kotlinx.rpc.withService
suspend fun main() {
val client = GrpcClient("localhost", GRPC_PORT) {
credentials = plaintext()
}
val service = client.withService<SampleService>()
val response = service.greeting(
ClientGreeting {
name = "World"
}
)
println("Response: ${response.content}")
client.shutdown()
client.awaitTermination()
}
@@ -0,0 +1,25 @@
package tech.aklivtsov
import io.ktor.client.HttpClient
import io.ktor.client.*
import io.ktor.http.*
import io.opentelemetry.instrumentation.ktor.v3_0.KtorClientTelemetry
val httpClient = HttpClient {
val openTelemetry = getOpenTelemetry(serviceName = "opentelemetry-ktor-sample-client")
install(KtorClientTelemetry) {
setOpenTelemetry(openTelemetry)
capturedRequestHeaders(HttpHeaders.Accept)
attributesExtractor {
onStart {
attributes.put("start-time", System.currentTimeMillis())
}
onEnd {
attributes.put("end-time", System.currentTimeMillis())
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.kotlinx.rpc.grpc)
alias(libs.plugins.kotlin.serialization)
}
rpc {
protoc()
}
kotlin {
jvm()
sourceSets {
commonMain.dependencies {
api(libs.opentelemetry.exporterOtlp)
api(libs.opentelemetry.ktorInstrumentation)
api(libs.opentelemetry.sdkAutoconfigure)
api(libs.opentelemetry.semconv)
implementation(libs.kotlinx.rpc.grpc.core)
implementation(libs.kotlinx.rpc.protobufCore)
}
}
}
@@ -0,0 +1,15 @@
package tech.aklivtsov
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk
import io.opentelemetry.semconv.ServiceAttributes
fun getOpenTelemetry(serviceName: String): OpenTelemetry {
System.setProperty("otel.metrics.exporter", "none")
return AutoConfiguredOpenTelemetrySdk.builder().addResourceCustomizer { oldResource, _ ->
oldResource.toBuilder()
.putAll(oldResource.attributes)
.put(ServiceAttributes.SERVICE_NAME, serviceName)
.build()
}.build().openTelemetrySdk
}
+3
View File
@@ -0,0 +1,3 @@
package tech.aklivtsov
const val GRPC_PORT = 8081
+15
View File
@@ -0,0 +1,15 @@
syntax = "proto3";
package tech.aklivtsov;
message ClientGreeting {
string name = 1;
}
message ServerGreeting {
string content = 2;
}
service SampleService {
rpc greeting(ClientGreeting) returns (ServerGreeting);
}
+2
View File
@@ -0,0 +1,2 @@
kotlin.code.style=official
+36
View File
@@ -0,0 +1,36 @@
[versions]
exposed = "1.3.0"
flaxoos = "2.3.0"
grpc-netty = "1.82.1"
h2 = "2.4.240"
h2-r2dbc = "1.1.0.RELEASE"
kotlin = "2.4.0"
kotlinx-rpc-grpc = "0.11.0-grpc-188"
logback = "1.5.35"
opentelemetry = "1.63.0"
opentelemetry-ktor = "2.29.0-alpha"
opentelemetry-semconv = "1.42.0"
[libraries]
exposed-core = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" }
exposed-r2dbc = { module = "org.jetbrains.exposed:exposed-r2dbc", version.ref = "exposed" }
flaxoos-ktor-server-kafka = { module = "io.github.flaxoos:ktor-server-kafka", version.ref = "flaxoos" }
flaxoos-ktor-server-rateLimiting = { module = "io.github.flaxoos:ktor-server-rate-limiting", version.ref = "flaxoos" }
grpc-netty = { module = "io.grpc:grpc-netty", version.ref = "grpc-netty" }
h2database-h2 = { module = "com.h2database:h2", version.ref = "h2" }
h2database-r2dbc = { module = "io.r2dbc:r2dbc-h2", version.ref = "h2-r2dbc" }
kotlinx-rpc-grpc-client = { module = "org.jetbrains.kotlinx:kotlinx-rpc-grpc-client", version.ref = "kotlinx-rpc-grpc" }
kotlinx-rpc-grpc-core = { module = "org.jetbrains.kotlinx:kotlinx-rpc-grpc-core", version.ref = "kotlinx-rpc-grpc" }
kotlinx-rpc-grpc-ktorServer = { module = "org.jetbrains.kotlinx:kotlinx-rpc-grpc-ktor-server", version.ref = "kotlinx-rpc-grpc" }
kotlinx-rpc-protobufCore = { module = "org.jetbrains.kotlinx:kotlinx-rpc-protobuf-core", version.ref = "kotlinx-rpc-grpc" }
logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
opentelemetry-exporterOtlp = { module = "io.opentelemetry:opentelemetry-exporter-otlp", version.ref = "opentelemetry" }
opentelemetry-ktorInstrumentation = { module = "io.opentelemetry.instrumentation:opentelemetry-ktor-3.0", version.ref = "opentelemetry-ktor" }
opentelemetry-sdkAutoconfigure = { module = "io.opentelemetry:opentelemetry-sdk-extension-autoconfigure", version.ref = "opentelemetry" }
opentelemetry-semconv = { module = "io.opentelemetry.semconv:opentelemetry-semconv", version.ref = "opentelemetry-semconv" }
[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
kotlinx-rpc-grpc = { id = "org.jetbrains.kotlinx.rpc.plugin", version.ref = "kotlinx-rpc-grpc" }
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 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
#
##############################################################################
#
# gradlew 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 gradlew
#
# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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
# 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" )
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" \
-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
+82
View File
@@ -0,0 +1,82 @@
@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 gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
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
"%COMSPEC%" /c exit 1
: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
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+46
View File
@@ -0,0 +1,46 @@
plugins {
alias(libs.plugins.kotlin.jvm)
alias(ktorLibs.plugins.ktor)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.kotlinx.rpc.grpc)
}
application {
mainClass = "io.ktor.server.netty.EngineMain"
}
rpc {
protoc()
}
kotlin {
jvmToolchain(21)
}
dependencies {
implementation(ktorLibs.client.core)
implementation(ktorLibs.serialization.kotlinx.json)
implementation(ktorLibs.server.auth)
implementation(ktorLibs.server.config.yaml)
implementation(ktorLibs.server.contentNegotiation)
implementation(ktorLibs.server.core)
implementation(ktorLibs.server.di)
implementation(ktorLibs.server.netty)
implementation(ktorLibs.server.routingOpenapi)
implementation(ktorLibs.server.sessions)
implementation(ktorLibs.server.swagger)
implementation(libs.exposed.core)
implementation(libs.exposed.r2dbc)
implementation(libs.flaxoos.ktor.server.kafka)
implementation(libs.flaxoos.ktor.server.rateLimiting)
implementation(libs.grpc.netty)
implementation(libs.h2database.h2)
implementation(libs.h2database.r2dbc)
implementation(libs.kotlinx.rpc.grpc.ktorServer)
implementation(libs.logback.classic)
implementation(project(":core"))
testImplementation(kotlin("test"))
testImplementation(ktorLibs.server.testHost)
testImplementation(libs.kotlinx.rpc.grpc.client)
}
+11
View File
@@ -0,0 +1,11 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.ktor.server.plugins.di.*
// The contents of the `install` function will be used for the project template
fun Application.configureDependencyInjection() {
dependencies {
provide { GreetingService { "Hello, World!" } }
}
}
+55
View File
@@ -0,0 +1,55 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.github.flaxoos.ktor.server.plugins.kafka.Kafka
import io.github.flaxoos.ktor.server.plugins.kafka.MessageTimestampType
import io.github.flaxoos.ktor.server.plugins.kafka.TopicName
import io.github.flaxoos.ktor.server.plugins.kafka.admin
import io.github.flaxoos.ktor.server.plugins.kafka.common
import io.github.flaxoos.ktor.server.plugins.kafka.consumer
import io.github.flaxoos.ktor.server.plugins.kafka.consumerConfig
import io.github.flaxoos.ktor.server.plugins.kafka.consumerRecordHandler
import io.github.flaxoos.ktor.server.plugins.kafka.producer
import io.github.flaxoos.ktor.server.plugins.kafka.registerSchemas
import io.github.flaxoos.ktor.server.plugins.kafka.topic
import io.ktor.client.HttpClient
import io.ktor.server.application.Application
import io.ktor.server.application.install
fun Application.configureDatabases() {
install(Kafka) {
schemaRegistryUrl = "my.schemaRegistryUrl"
val myTopic = TopicName.named("my-topic")
topic(myTopic) {
partitions = 1
replicas = 1
configs {
messageTimestampType = MessageTimestampType.CreateTime
}
}
common { // <-- Define common properties
bootstrapServers = listOf("my-kafka")
retries = 1
clientId = "my-client-id"
}
admin { } // <-- Creates an admin client
producer { // <-- Creates a producer
clientId = "my-client-id"
}
consumer { // <-- Creates a consumer
groupId = "my-group-id"
clientId = "my-client-id-override" //<-- Override common properties
}
consumerConfig {
consumerRecordHandler(myTopic) { record ->
// Do something with record
}
}
registerSchemas {
using { // <-- optionally provide a client, by default CIO is used
HttpClient()
}
// MyRecord::class at myTopic // <-- Will register schema upon startup
}
}
}
+58
View File
@@ -0,0 +1,58 @@
package tech.aklivtsov
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.*
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.put
import io.ktor.server.routing.routing
import org.jetbrains.exposed.v1.r2dbc.R2dbcDatabase
suspend fun Application.configureExposed() {
val database = R2dbcDatabase.connect(
url = "r2dbc:h2:file:///./h2",
user = "root",
password = "",
)
val userService = ExposedUserService(database).also {
it.createSchema()
}
routing {
// Create user
post("/users") {
val user = call.receive<ExposedUser>()
val id = userService.create(user)
call.respond(HttpStatusCode.Created, id)
}
// Read user
get("/users/{id}") {
val id = call.parameters["id"]?.toUInt() ?: throw IllegalArgumentException("Invalid ID")
val user = userService.read(id)
if (user != null) {
call.respond(HttpStatusCode.OK, user)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
// Update user
put("/users/{id}") {
val id = call.parameters["id"]?.toUInt() ?: throw IllegalArgumentException("Invalid ID")
val user = call.receive<ExposedUser>()
userService.update(id, user)
call.respond(HttpStatusCode.NoContent)
}
// Delete user
delete("/users/{id}") {
val id = call.parameters["id"]?.toUInt() ?: throw IllegalArgumentException("Invalid ID")
userService.delete(id)
call.respond(HttpStatusCode.NoContent)
}
}
}
@@ -0,0 +1,5 @@
package tech.aklivtsov
fun interface GreetingService {
fun sayHello(): String
}
+13
View File
@@ -0,0 +1,13 @@
package tech.aklivtsov
import io.ktor.server.application.Application
import kotlinx.rpc.grpc.ktor.server.grpc
import kotlinx.rpc.registerService
fun Application.configureGrpc() {
grpc(GRPC_PORT) {
services {
registerService<SampleService> { SampleServiceImpl() }
}
}
}
+19
View File
@@ -0,0 +1,19 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.routing.*
fun Application.configureHttp() {
routing {
swaggerUI(path = "openapi") {
/*
Documentation source configuration goes here.
This can be from file (documentation.yaml), or it can be served dynamically from your sources using the
`describe {}` API on routes. When `openApi` enabled in Gradle, these calls will be automatically injected
based on your code and comments.
*/
}
}
}
+6
View File
@@ -0,0 +1,6 @@
package tech.aklivtsov
import kotlinx.serialization.Serializable
@Serializable
data class MySession(val count: Int = 0)
+21
View File
@@ -0,0 +1,21 @@
package tech.aklivtsov
import io.github.flaxoos.ktor.server.plugins.ratelimiter.*
import io.github.flaxoos.ktor.server.plugins.ratelimiter.implementations.*
import io.ktor.server.application.*
import io.ktor.server.routing.*
import kotlin.time.Duration.Companion.seconds
fun Application.configureRateLimiting() {
routing {
route("/"){
install(RateLimiting) {
rateLimiter {
type = TokenBucket::class
capacity = 100
rate = 10.seconds
}
}
}
}
}
+35
View File
@@ -0,0 +1,35 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.auth.*
import io.ktor.server.sessions.*
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Hello, World!")
}
authenticate("myauth1") {
get("/protected/route/basic") {
val principal = call.principal<UserIdPrincipal>()!!
call.respondText("Hello ${principal.name}")
}
}
authenticate("myauth2") {
get("/protected/route/form") {
val principal = call.principal<UserIdPrincipal>()!!
call.respondText("Hello ${principal.name}")
}
}
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
get("/session/increment") {
val session = call.sessions.get<MySession>() ?: MySession()
call.sessions.set(session.copy(count = session.count + 1))
call.respondText("Counter is ${session.count}. Refresh to increment.")
}
}
}
@@ -0,0 +1,7 @@
package tech.aklivtsov
class SampleServiceImpl : SampleService {
override suspend fun greeting(name: ClientGreeting): ServerGreeting {
return ServerGreeting { content = "Hello, ${name.name}!" }
}
}
+34
View File
@@ -0,0 +1,34 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.sessions.*
fun Application.configureSecurity() {
authentication {
basic(name = "myauth1") {
realm = "Ktor Server"
validate { credentials ->
if (credentials.name == credentials.password) {
UserIdPrincipal(credentials.name)
} else {
null
}
}
}
form(name = "myauth2") {
userParamName = "user"
passwordParamName = "password"
challenge {
/**/
}
}
}
install(Sessions) {
cookie<MySession>("MY_SESSION") {
cookie.extensions["SameSite"] = "lax"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
package tech.aklivtsov
import io.ktor.server.application.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
@@ -0,0 +1,29 @@
package tech.aklivtsov
import io.ktor.http.*
import io.ktor.server.request.*
import io.ktor.server.application.*
import io.opentelemetry.api.trace.SpanKind
import io.opentelemetry.instrumentation.ktor.v3_0.KtorServerTelemetry
fun Application.configureOpenTelemetry() {
install(KtorServerTelemetry) {
setOpenTelemetry(getOpenTelemetry(serviceName = "ktor-sample"))
capturedRequestHeaders(HttpHeaders.UserAgent)
spanKindExtractor {
if (httpMethod == HttpMethod.Post) {
SpanKind.PRODUCER
} else {
SpanKind.CLIENT
}
}
attributesExtractor {
onStart {
attributes.put("start-time", System.currentTimeMillis())
}
onEnd {
attributes.put("end-time", System.currentTimeMillis())
}
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package tech.aklivtsov
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.singleOrNull
import kotlinx.serialization.Serializable
import org.jetbrains.exposed.v1.core.*
import org.jetbrains.exposed.v1.core.dao.id.UIntIdTable
import org.jetbrains.exposed.v1.r2dbc.*
import org.jetbrains.exposed.v1.r2dbc.transactions.suspendTransaction
import org.jetbrains.exposed.v1.r2dbc.R2dbcDatabase
@Serializable
data class ExposedUser(val name: String, val age: Int)
class ExposedUserService(val database: R2dbcDatabase) {
object Users : UIntIdTable() {
val name = varchar("name", length = 50)
val age = integer("age")
}
suspend fun createSchema() {
suspendTransaction(database) {
SchemaUtils.create(Users)
}
}
suspend fun create(user: ExposedUser): UInt = suspendTransaction(database) {
val newRecord = Users.insert {
it[name] = user.name
it[age] = user.age
}
newRecord[Users.id].value
}
suspend fun read(id: UInt): ExposedUser? {
return suspendTransaction(database) {
Users.selectAll()
.where { Users.id eq id }
.map { ExposedUser(it[Users.name], it[Users.age]) }
.singleOrNull()
}
}
suspend fun update(id: UInt, user: ExposedUser) {
suspendTransaction(database) {
Users.update({ Users.id eq id }) {
it[name] = user.name
it[age] = user.age
}
}
}
suspend fun delete(id: UInt) {
suspendTransaction(database) { Users.deleteWhere { Users.id.eq(id) } }
}
}
+8
View File
@@ -0,0 +1,8 @@
package tech.aklivtsov
import io.ktor.server.engine.*
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
@@ -0,0 +1,15 @@
ktor:
deployment:
port: 8080
application:
modules:
- tech.aklivtsov.HttpKt.configureHttp
- tech.aklivtsov.SerializationKt.configureSerialization
- tech.aklivtsov.DatabasesKt.configureDatabases
- tech.aklivtsov.SecurityKt.configureSecurity
- tech.aklivtsov.GrpcKt.configureGrpc
- tech.aklivtsov.RateLimitingKt.configureRateLimiting
- tech.aklivtsov.ExposedKt.configureExposed
- tech.aklivtsov.DIKt.configureDependencyInjection
- tech.aklivtsov.ServerOpenTelemetryKt.configureOpenTelemetry
- tech.aklivtsov.RoutingKt.configureRouting
@@ -0,0 +1,23 @@
openapi: "3.0.3"
info:
title: "Application API"
description: "Application API"
version: "1.0.0"
servers:
- url: "http://0.0.0.0:8080"
paths:
/:
get:
description: "Hello World!"
responses:
"200":
description: "OK"
content:
text/plain:
schema:
type: "string"
examples:
Example#1:
value: "Hello World!"
components:
schemas: {}
+12
View File
@@ -0,0 +1,12 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
</configuration>
+40
View File
@@ -0,0 +1,40 @@
package tech.aklivtsov
import io.ktor.server.testing.testApplication
import kotlinx.rpc.grpc.client.GrpcClient
import kotlinx.rpc.grpc.ktor.server.grpc
import kotlinx.rpc.registerService
import kotlinx.rpc.withService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.minutes
class ApplicationRpcTest {
@Test
fun testRpc() = testApplication {
application {
grpc(8081) {
services {
registerService<SampleService> { SampleServiceImpl() }
}
}
}
startApplication()
val client = GrpcClient("localhost", 8081) {
credentials = plaintext()
}
val response = client.withService<SampleService>().greeting(
ClientGreeting {
name = "Alex"
}
)
assertEquals("Hello, Alex!", response.content, "Wrong response message")
client.shutdown()
client.awaitTermination(1.minutes)
}
}
+18
View File
@@ -0,0 +1,18 @@
package tech.aklivtsov
import io.ktor.client.request.get
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import kotlin.test.*
class ServerTest {
@Test
fun `test root endpoint`() = testApplication {
// loads default configuration
configure()
// verify server root returns 200
assertEquals(HttpStatusCode.OK, client.get("/").status)
}
}
+29
View File
@@ -0,0 +1,29 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven("https://redirector.kotlinlang.org/maven/kxrpc-grpc")
maven("https://packages.confluent.io/maven")
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
dependencyResolutionManagement {
repositories {
mavenCentral()
maven("https://redirector.kotlinlang.org/maven/kxrpc-grpc")
maven("https://packages.confluent.io/maven")
}
versionCatalogs {
create("ktorLibs").from("io.ktor:ktor-version-catalog:3.5.0")
}
}
rootProject.name = "UserService"
include(":client")
include(":core")
include(":server")