initial commit

This commit is contained in:
2026-05-09 22:39:06 +03:00
commit 99800e9d37
60 changed files with 2276 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
plugins {
id 'org.jetbrains.kotlin.jvm' version '2.2.0'
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.0'
id 'com.gradleup.shadow' version '9.3.1'
id 'org.jetbrains.dokka' version '2.2.0'
}
group = 'lab6.prog'
version = '1.0'
repositories {
mavenCentral()
}
shadowJar {
archiveBaseName.set('Lab6-server')
archiveVersion.set('1.0')
manifest {
attributes 'Main-Class': 'MainKt'
}
}
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test'
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0'
implementation 'io.github.microutils:kotlin-logging-jvm:3.0.5'
implementation "io.ktor:ktor-network:3.4.2"
implementation "io.github.oshai:kotlin-logging-jvm:7.0.3"
implementation "org.slf4j:slf4j-api:2.0.13"
implementation "ch.qos.logback:logback-classic:1.5.6"
implementation project(':common')
}
kotlin {
jvmToolchain(17)
}
+83
View File
@@ -0,0 +1,83 @@
import collection.CollectionManager
import commands.*
import file.FileManager
import mu.KotlinLogging
import network.NetworkManager
import runner.CommandInvoker
import kotlin.system.exitProcess
private val logger = KotlinLogging.logger {}
fun main(args: Array<String>) {
System.setProperty("slf4j.internal.verbosity", "WARN")
val filePath = if (args.isNotEmpty()) args[0] else "data.csv"
val port = if (args.isNotEmpty() && args.size > 1) args[1].toInt() else 8080
logger.info{ "[startup] Starting server on port $port with $args args" }
val fileManager = FileManager(filePath)
val manager = CollectionManager()
val invoker = CommandInvoker()
// Загружаем коллекцию из файла
manager.loadFromFile(fileManager.read())
// Регистрируем команды
registerServerCommands(invoker, manager, fileManager)
// Сохранение при завершении (Ctrl+C или kill)
val server = NetworkManager(port = port, invoker = invoker)
Runtime.getRuntime().addShutdownHook(Thread {
logger.info{ "Saving collection before exit..." }
fileManager.write(manager.getAll())
server.stop()
})
// Консоль на сервере
Thread {
val scanner = java.util.Scanner(System.`in`)
logger.info{ "[Server-console] Server-side commands: save, exit" }
while (scanner.hasNextLine()) {
when (scanner.nextLine().trim().lowercase()) {
"save" -> {
fileManager.write(manager.getAll())
logger.info{ "[Server-console] Collection is saved" }
}
"exit" -> {
logger.info{ "[Server-console] Shutting down..." }
exitProcess(0)
}
else -> logger.info{ "[Server-console] Server-side commands: save, exit" }
}
}
}.also { it.isDaemon = true }.start()
server.start()
}
fun registerServerCommands(
invoker: CommandInvoker,
manager: CollectionManager,
fileManager: FileManager
) {
listOf(
// HelpCommand(invoker),
InfoCommand(manager),
ShowCommand(manager),
AddCommand(manager),
UpdateCommand(manager),
RemoveByIdCommand(manager),
ClearCommand(manager),
SaveCommand(manager, fileManager), // только на сервере
AddIfMaxCommand(manager),
AddIfMinCommand(manager),
HistoryCommand(invoker),
SyncCommand(invoker),
SumOfMinutesCommand(manager),
MinByNameCommand(manager),
PrintDescendingMinutesCommand(manager),
ExitCommand()
).forEach { invoker.register(it)}
logger.info{ " [startup] Registered commands: ${invoker.getCommands().keys}" }
}
@@ -0,0 +1,92 @@
package collection
import models.HumanBeing
import mu.KotlinLogging
import java.time.LocalDate
import java.util.TreeSet
import java.util.UUID
private val logger = KotlinLogging.logger {}
class CollectionManager {
private val collection: TreeSet<HumanBeing> = TreeSet()
val initDate: LocalDate = LocalDate.now()
fun add(humanBeing: HumanBeing): Boolean {
logger.info { "[ADD] Element created ${humanBeing.id}" }
return collection.add(humanBeing)
}
fun update(id: UUID, updated: HumanBeing): Boolean {
val old = getById(id) ?: return false
collection.remove(old)
val replaced = updated.copy(id = old.id, creationDate = old.creationDate)
logger.info { "[UPDATE] Element updated ${old.id}" }
return collection.add(replaced)
}
fun removeById(id: UUID): Boolean {
val target = getById(id) ?: return false
logger.info { "[REMOVE] Element deleted ${target.id}" }
return collection.remove(target)
}
fun clear() {
collection.clear()
logger.info { "[CLEAR] Collection cleared" }
}
fun getAll(): TreeSet<HumanBeing> = TreeSet(collection)
fun getById(id: UUID): HumanBeing? =
collection.stream()
.filter { it.id == id }
.findFirst()
.orElse(null)
fun size(): Int = collection.size
fun isEmpty(): Boolean = collection.isEmpty()
fun getMax(): HumanBeing? =
collection.stream()
.max(Comparator.naturalOrder())
.orElse(null)
fun getMin(): HumanBeing? =
collection.stream()
.min(Comparator.naturalOrder())
.orElse(null)
fun sumOfMinutesOfWaiting(): Double =
collection.stream()
.mapToDouble { it.minutesOfWaiting.toDouble() }
.sum()
fun minByName(): HumanBeing? =
collection.stream()
.min(Comparator.comparing { it.name })
.orElse(null)
fun getMinutesOfWaitingDescending(): List<Float> =
collection.stream()
.map { it.minutesOfWaiting }
.sorted(Comparator.reverseOrder())
.toList()
fun loadFromFile(items: List<HumanBeing>) {
collection.clear()
items.stream().forEach { collection.add(it) }
logger.info { "[LOAD] loaded ${items.size} elements" }
}
fun getInfo(): String =
"""
|Тип коллекции : ${collection::class.simpleName}
|Тип элементов : ${HumanBeing::class.simpleName}
|Дата инициал. : $initDate
|Кол-во элемен.: ${collection.size}
""".trimMargin()
}
@@ -0,0 +1,23 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class AddCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "add"
override val description = "добавить новый элемент в коллекцию"
override val args = listOf(CommandArgType.NONE)
override val type = CommandType.MODEL
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
humanBeing ?: return Response(false, "[Ошибка] Объект HumanBeing не передан.")
return if (manager.add(humanBeing))
Response(true, "Элемент добавлен: ${humanBeing.name} [${humanBeing.id}]")
else
Response(false, "Элемент уже существует в коллекции.")
}
}
@@ -0,0 +1,23 @@
package commands
import collection.CollectionManager
import models.HumanBeing
import network.Response
class AddIfMaxCommand(private val manager: CollectionManager) : Command {
override val name = "add_if_max"
override val description = "добавить элемент, если он больше максимального"
override val type = CommandType.MODEL
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
humanBeing ?: return Response(false, "[Ошибка] Объект HumanBeing не передан.")
val max = manager.getMax()
return if (max == null || humanBeing > max) {
manager.add(humanBeing)
Response(true, "Элемент добавлен (превышает максимум).")
} else {
Response(false, "Элемент не добавлен: не превышает текущий максимум (${max.name}).")
}
}
}
@@ -0,0 +1,26 @@
package commands
import collection.CollectionManager
import models.HumanBeing
import kotlinx.serialization.Serializable
import kotlinx.serialization.Contextual
import network.Response
@Serializable
class AddIfMinCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "add_if_min"
override val description = "добавить элемент, если он меньше минимального"
override val type = CommandType.MODEL
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
humanBeing ?: return Response(false, "[Ошибка] Объект HumanBeing не передан.")
val min = manager.getMin()
return if (min == null || humanBeing < min) {
manager.add(humanBeing)
Response(true, "Элемент добавлен (меньше минимума).")
} else {
Response(false, "Элемент не добавлен: не меньше текущего минимума (${min.name}).")
}
}
}
@@ -0,0 +1,20 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class ClearCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "clear"
override val description = "очистить коллекцию"
override val args = listOf(CommandArgType.NONE)
override val type = CommandType.SIMPLE
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
manager.clear()
return Response(true, "Коллекция очищена.")
}
}
@@ -0,0 +1,24 @@
package commands
import models.HumanBeing
import network.Response
/**
* Базовый интерфейс команды.
*
* Теперь execute() возвращает String — результат для отправки клиенту.
* Зависимость от IOManager полностью убрана из команд.
*/
interface Command {
val name: String
val description: String
val type : CommandType
val args : List<CommandArgType>
/**
* @param args строковые аргументы (UUID и т.п.)
* @param humanBeing объект из запроса — только для add/update/add_if_max/add_if_min
* @return строка-результат для клиента
*/
fun execute(args: List<String>, humanBeing: HumanBeing? = null): Response
}
@@ -0,0 +1,18 @@
package commands
/**
* Завершает программу без сохранения.
*/
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class ExitCommand() : Command {
override val name = "exit"
override val description = "завершить программу"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response = Response(true, "")
}
@@ -0,0 +1,21 @@
package commands
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import runner.CommandInvoker
import models.HumanBeing
import network.Response
@Serializable
class HistoryCommand(@Contextual private val invoker: CommandInvoker) : Command {
override val name = "history"
override val description = "вывести последние 12 команд"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
val history = invoker.getHistory()
if (history.isEmpty()) return Response(true, "История пуста.")
return Response(true, history.mapIndexed { i, cmd -> " ${i + 1}. $cmd" }.joinToString("\n"))
}
}
@@ -0,0 +1,18 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class InfoCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "info"
override val description = "вывести информацию о коллекции"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response =
Response(true, manager.getInfo())
}
@@ -0,0 +1,21 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
/**
* Выводит любой элемент с минимальным значением поля [HumanBeing.name].
*/
@Serializable
class MinByNameCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "min_by_name"
override val description = "вывести элемент с минимальным именем"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response =
Response(true, manager.minByName()?.toString() ?: "Коллекция пуста.")
}
@@ -0,0 +1,24 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
/**
* Выводит значения поля [models.HumanBeing.minutesOfWaiting] в порядке убывания.
*/
@Serializable
class PrintDescendingMinutesCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "print_field_descending_minutes_of_waiting"
override val description = "вывести minutesOfWaiting в порядке убывания"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
val values = manager.getMinutesOfWaitingDescending()
return if (values.isEmpty()) Response(true, "Коллекция пуста.")
else Response(true, values.joinToString("\n"))
}
}
@@ -0,0 +1,29 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import java.util.UUID
import models.HumanBeing
import network.Response
@Serializable
class RemoveByIdCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "remove_by_id"
override val description = "удалить элемент по id: remove_by_id <uuid>"
override val type = CommandType.MODEL
override val args = listOf(CommandArgType.STRING)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
if (args.isEmpty()) return Response(false, "[Ошибка] Укажите id. Пример: remove_by_id <uuid>")
val id = try {
UUID.fromString(args[0])
} catch (e: IllegalArgumentException) {
return Response(false, "[Ошибка] Некорректный UUID: '${args[0]}'")
}
return if (manager.removeById(id)) Response(true, "Элемент удалён.")
else Response(false, "[Ошибка] Элемент с id '$id' не найден.")
}
}
@@ -0,0 +1,24 @@
package commands
import collection.CollectionManager
import file.FileManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class SaveCommand(
@Contextual private val manager: CollectionManager,
@Contextual private val fileManager: FileManager
) : Command {
override val name = "save"
override val description = "[SERVER] сохранить коллекцию в файл"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
return if (fileManager.write(manager.getAll())) Response(true, "Коллекция сохранена.")
else Response(false, "[Ошибка] Не удалось сохранить коллекцию.")
}
}
@@ -0,0 +1,20 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
@Serializable
class ShowCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "show"
override val description = "вывести все элементы коллекции"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
if (manager.isEmpty()) return Response(true, "Коллекция пуста.")
return Response(true, manager.getAll().joinToString("\n") { it.toString() })
}
}
@@ -0,0 +1,21 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
/**
* Выводит сумму значений поля [models.HumanBeing.minutesOfWaiting].
*/
@Serializable
class SumOfMinutesCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "sum_of_minutes_of_waiting"
override val description = "вывести сумму minutesOfWaiting всех элементов"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response =
Response(true, "Сумма minutesOfWaiting: ${manager.sumOfMinutesOfWaiting()}")
}
@@ -0,0 +1,45 @@
package commands
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.CommandInfo
import network.Response
import runner.CommandInvoker
@Serializable
class SyncCommand(
@Contextual private val invoker: CommandInvoker
) : Command {
override val name: String = "sync"
override val description: String = "Получает все доступные с сервера команды"
override val type = CommandType.SIMPLE
override val args = listOf(CommandArgType.NONE)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
val commands = mutableMapOf<String, Command>()
for (command in invoker.getCommands().values) {
if (command.name == "sync" || command.name == "exit") {
continue
}
commands[command.name] = command
}
val commandInfos = commands.values.map { command ->
CommandInfo(
name = command.name,
description = command.description,
type = command.type,
args = command.args
)
}
return Response(
success = true,
message = "хуй",
commands = commandInfos
)
}
}
@@ -0,0 +1,30 @@
package commands
import collection.CollectionManager
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import models.HumanBeing
import network.Response
import java.util.UUID
@Serializable
class UpdateCommand(@Contextual private val manager: CollectionManager) : Command {
override val name = "update"
override val description = "обновить элемент по id: update <uuid>"
override val type = CommandType.MODEL
override val args = listOf(CommandArgType.STRING)
override fun execute(args: List<String>, humanBeing: HumanBeing?): Response {
if (args.isEmpty()) return Response(false, "[Ошибка] Укажите id. Пример: update <uuid>")
humanBeing ?: return Response(false, "[Ошибка] Объект HumanBeing не передан.")
val id = try {
UUID.fromString(args[0])
} catch (e: IllegalArgumentException) {
return Response(false, "[Ошибка] Некорректный UUID: '${args[0]}'")
}
return if (manager.update(id, humanBeing)) Response(true, "Элемент обновлён.")
else Response(false, "[Ошибка] Элемент с id '$id' не найден.")
}
}
+179
View File
@@ -0,0 +1,179 @@
package file
import models.Car
import models.Coordinates
import models.HumanBeing
import models.WeaponType
import mu.KotlinLogging
import java.io.File
import java.io.FileNotFoundException
import java.io.OutputStreamWriter
import java.time.LocalDate
import java.time.format.DateTimeParseException
import java.util.Scanner
import java.util.UUID
private val logger = KotlinLogging.logger {}
/**
* Менеджер файлового хранилища коллекции.
*
* Читает данные с помощью [Scanner], записывает через [OutputStreamWriter].
* Формат хранения — CSV, одна строка = один объект [HumanBeing].
*
* Порядок полей в CSV:
* `id,name,coordX,coordY,creationDate,realHero,hasToothpick,
* impactSpeed,soundtrackName,minutesOfWaiting,weaponType,carCool`
*
* @property filePath путь к CSV-файлу, полученный из аргумента командной строки
*/
class FileManager(private val filePath: String) {
companion object {
private const val DELIMITER = ","
private const val HEADER =
"id,name,coordX,coordY,creationDate,realHero," +
"hasToothpick,impactSpeed,soundtrackName,minutesOfWaiting,weaponType,carCool"
}
/**
* Читает коллекцию из CSV-файла с помощью [Scanner].
*
* Пропускает заголовок и битые строки (с предупреждением в stderr).
* При отсутствии файла или проблемах с доступом возвращает пустой список.
*
* @return список корректно распарсенных объектов [HumanBeing]
*/
fun read(): List<HumanBeing> {
val file = File(filePath)
if (!file.exists()) {
logger.warn{"There's no '$filePath'. Collection will be empty."}
return emptyList()
}
if (!file.canRead()) {
logger.warn{"Permission denied: '$filePath'. Collection will be empty."}
return emptyList()
}
val result = mutableListOf<HumanBeing>()
var lineNumber = 0
try {
Scanner(file, Charsets.UTF_8).use { scanner ->
while (scanner.hasNextLine()) {
val line = scanner.nextLine().trim()
lineNumber++
// skip header and empty lines
if (lineNumber == 1 && line.startsWith("id")) continue
if (line.isBlank()) continue
val parsedLine = parseLine(line, lineNumber)
if (parsedLine != null) {
result.add(parsedLine)
} else {
logger.warn { "Line $lineNumber of $filePath is skipped: invalid data → '$line'" }
}
}
}
} catch (e: FileNotFoundException) {
logger.warn(e) {"File not found: ${e.message}"}
}
logger.info {"${result.size} elements loaded from'$filePath'"}
return result
}
/**
* Парсит одну CSV-строку в объект [HumanBeing].
*
* @param line строка CSV
* @param lineNumber номер строки (для сообщений об ошибках)
* @return объект [HumanBeing] или null при ошибке парсинга
*/
private fun parseLine(line: String, lineNumber: Int): HumanBeing? {
return try {
val parts = line.split(DELIMITER, limit = 12)
if (parts.size < 12) {
logger.warn {"Line $lineNumber: expected 12 fields, found ${parts.size}"}
return null
}
val id = UUID.fromString(parts[0].trim())
val name = parts[1].trim()
val coordX = parts[2].trim().toLong()
val coordY = parts[3].trim().toInt()
val creationDate = LocalDate.parse(parts[4].trim())
val realHero = parts[5].trim().toBoolean()
val hasToothpick = parts[6].trim().toBoolean()
val impactSpeed = parts[7].trim().toDouble()
val soundtrackName = parts[8].trim()
val minutesOfWaiting = parts[9].trim().toFloat()
val weaponType = parts[10].trim().let {
if (it.equals("null", ignoreCase = true) || it.isBlank()) null
else WeaponType.valueOf(it)
}
val carCool = parts[11].trim().toBoolean()
require(name.isNotBlank()) { "name не может быть пустым" }
HumanBeing(
id = id, name = name, coordinates = Coordinates(coordX, coordY),
creationDate = creationDate, realHero = realHero, hasToothpick = hasToothpick,
impactSpeed = impactSpeed, soundtrackName = soundtrackName,
minutesOfWaiting = minutesOfWaiting, weaponType = weaponType, car = Car(carCool)
)
} catch (e: Exception) {
logger.warn(e) {"Line $lineNumber: ${e.message}"}
null
}
}
/**
* Записывает коллекцию в CSV-файл с помощью [OutputStreamWriter].
*
* @param items коллекция объектов [HumanBeing] для записи
* @return true если запись прошла успешно
*/
fun write(items: Collection<HumanBeing>): Boolean {
val file = File(filePath)
if (file.exists() && !file.canWrite()) {
logger.warn{"Permission denied: '$filePath'."}
return false
}
return try {
OutputStreamWriter(file.outputStream(), Charsets.UTF_8).use { writer ->
writer.write(HEADER)
writer.write("\n")
items.forEach { h ->
writer.write(toCSVLine(h))
writer.write("\n")
}
}
logger.info {"Collection saved to'$filePath' (${items.size} elements)."}
true
} catch (e: SecurityException) {
logger.warn(e) {"Permission denied: '$filePath'."}
false
} catch (e: Exception) {
logger.warn(e) {"An error occurred: '$filePath'."}
false
}
}
/**
* Сериализует объект [HumanBeing] в строку CSV.
*
* @param h объект для сериализации
* @return строка в формате CSV
*/
private fun toCSVLine(h: HumanBeing): String = listOf(
h.id, h.name, h.coordinates.x, h.coordinates.y, h.creationDate,
h.realHero, h.hasToothpick, h.impactSpeed, h.soundtrackName,
h.minutesOfWaiting, h.weaponType ?: "null", h.car.cool
).joinToString(DELIMITER)
}
@@ -0,0 +1,64 @@
package network
import kotlinx.serialization.SerializationException
import mu.KotlinLogging
import runner.CommandInvoker
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
private val logger = KotlinLogging.logger {}
/**
* UDP-сервер на основе DatagramSocket (датаграммы).
*
* Однопоточный: receive → deserialize → execute → send.
*
* @property port порт прослушивания
* @property invoker инвокер серверных команд
*/
class NetworkManager(
private val port: Int,
private val invoker: CommandInvoker
) {
private val socket = DatagramSocket(port)
fun start() {
logger.info{"Server started on port $port. Waiting for connection..."}
val buf = ByteArray(65507)
while (!socket.isClosed) {
try {
val packet = DatagramPacket(buf, buf.size)
socket.receive(packet)
val json = String(packet.data, 0, packet.length, Charsets.UTF_8)
val request = try {
AppJson.decodeFromString<Request>(json)
} catch (e: SerializationException) {
logger.warn(e) { "Invalid request: ${e.message}" }
sendResponse(Response(false, "Некорректный формат запроса"), packet.address, packet.port)
continue
}
logger.info{"'${request.commandName}' from ${packet.address}:${packet.port}."}
val response = invoker.execute(request)
sendResponse(response, packet.address, packet.port)
} catch (e: Exception) {
if (!socket.isClosed)
logger.warn(e) { "Error: ${e.message}" }
}
}
}
private fun sendResponse(response: Response, address: InetAddress, port: Int) {
val bytes = AppJson.encodeToString(Response.serializer(), response).toByteArray(Charsets.UTF_8)
socket.send(DatagramPacket(bytes, bytes.size, address, port))
}
fun stop() {
logger.info{ "Shutting down..." }
socket.close()
}
}
@@ -0,0 +1,47 @@
package runner
import commands.Command
import network.Request
import network.Response
/**
* Серверный инвокер.
*
* Принимает Request, находит команду, выполняет,
* возвращает Response готовый для отправки клиенту.
*/
class CommandInvoker {
private val serverOnlyCommands = setOf("save", "sync-server")
private val commands = mutableMapOf<String, Command>()
private val history = ArrayDeque<String>()
fun register(command: Command) {
commands[command.name] = command
}
fun execute(request: Request): Response {
if (request.commandName in serverOnlyCommands) {
return Response(false, "Команда '${request.commandName}' недоступна клиенту.")
}
val command = commands[request.commandName]
?: return Response(false, "Неизвестная команда: '${request.commandName}'")
addToHistory(request.commandName)
return try {
command.execute(request.args, request.humanBeing)
} catch (e: Exception) {
Response(false, "[Ошибка выполнения] ${e.message}")
}
}
fun getHistory(): List<String> = history.toList()
fun getCommands(): Map<String, Command> = commands.toMap()
private fun addToHistory(name: String) {
if (history.size >= 12) history.removeFirst()
history.addLast(name)
}
}
+20
View File
@@ -0,0 +1,20 @@
<configuration>
<appender name="server_log" class="ch.qos.logback.core.FileAppender">
<file>logs/server.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="console" 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="TRACE">
<appender-ref ref="server_log" />
<appender-ref ref="console" />
</root>
</configuration>