commit 8d4b15dbcf60d2975a804cfa79f7947c759df896 Author: roma-dxunvrs Date: Sat Oct 3 22:09:58 2026 +0300 Pizdec diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cbfe05e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM eclipse-temurin:21-jre-alpine + +WORKDIR /app + +COPY build/libs/*.jar app.jar + +EXPOSE 8080 + +ENTRYPOINT ["java", "-Djava.net.preferIPv4Stack=true", "-jar", "app.jar"] diff --git a/MONITORING_GUIDE.md b/MONITORING_GUIDE.md new file mode 100644 index 0000000..0ee6502 --- /dev/null +++ b/MONITORING_GUIDE.md @@ -0,0 +1,316 @@ +# Гайд по метрикам и мониторингу + +## Быстрый старт + +1. **Доступ к сервисам:** + - Приложение: http://localhost:8080 + - Prometheus: http://localhost:9090 + - Grafana: http://localhost:3000 (admin/admin) + +2. **Дашборды автоматически загружены:** + - Spring Boot Application Metrics + - PostgreSQL & HikariCP Monitoring + +## Основные метрики + +### HTTP метрики + +**Что смотреть:** +- `http_server_requests_seconds_count` — количество запросов +- `http_server_requests_seconds_sum` — суммарное время выполнения +- `http_server_requests_seconds_bucket` — распределение времени ответа + +**Зачем:** +- Отслеживать нагрузку на эндпоинты +- Находить медленные запросы (p95, p99) +- Видеть ошибки по статус-кодам + +**Пример запроса в Prometheus:** +```promql +# Request rate по эндпоинтам +rate(http_server_requests_seconds_count{application="todo"}[1m]) + +# 95-й перцентиль времени ответа +histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le, uri)) + +# Количество ошибок 5xx +sum(rate(http_server_requests_seconds_count{status=~"5.."}[1m])) +``` + +### JVM метрики + +**Что смотреть:** +- `jvm_memory_used_bytes` — используемая память (heap/non-heap) +- `jvm_memory_max_bytes` — максимальная доступная память +- `jvm_gc_pause_seconds` — время на GC паузах +- `jvm_threads_live_threads` — количество потоков + +**Зачем:** +- Проверить утечки памяти (постоянный рост heap) +- Оптимизировать GC (частые паузы = проблема) +- Контролировать создание потоков + +**Алерты:** +```promql +# Память heap больше 80% +(jvm_memory_used_bytes{area="heap"} / jvm_memory_max_bytes{area="heap"}) > 0.8 + +# GC паузы больше 100ms +rate(jvm_gc_pause_seconds_sum[1m]) > 0.1 +``` + +### Database Connection Pool (HikariCP) + +**Что смотреть:** +- `hikaricp_connections_active` — активные соединения +- `hikaricp_connections_idle` — простаивающие соединения +- `hikaricp_connections_pending` — ожидающие потоки +- `hikaricp_connections_timeout_total` — таймауты соединений +- `hikaricp_connections_acquire_seconds` — время получения соединения + +**Зачем:** +- Настроить размер пула (если active = max постоянно, увеличить) +- Найти медленные запросы (высокое usage time) +- Обнаружить connection leaks (timeouts растут) + +**Оптимальные значения:** +- Active connections < 70% от max +- Acquire time < 10ms (p95) +- Pending threads = 0 +- Timeouts = 0 + +**Алерты:** +```promql +# Пул заполнен больше 80% +(hikaricp_connections_active / hikaricp_connections_max) > 0.8 + +# Таймауты соединений +rate(hikaricp_connections_timeout_total[1m]) > 0 + +# Медленное получение соединений (p95 > 50ms) +histogram_quantile(0.95, rate(hikaricp_connections_acquire_seconds_bucket[1m])) > 0.05 +``` + +### System метрики + +**Что смотреть:** +- `system_cpu_usage` — CPU системы +- `process_cpu_usage` — CPU процесса +- `disk_free_bytes` — свободное место на диске + +**Зачем:** +- Контролировать нагрузку на CPU +- Предотвратить переполнение диска + +## Использование Grafana + +### Навигация по дашбордам + +1. **Spring Boot Application Metrics:** + - HTTP Request Rate — количество запросов в секунду по эндпоинтам + - HTTP Request Duration — время ответа (p95, p99) + - HTTP Status Codes — распределение статус-кодов + - JVM Memory — использование heap/non-heap памяти + - Database Connection Pool — состояние пула соединений + - JVM Threads — количество потоков + - GC Pause Time — время на сборку мусора + - System CPU Usage — нагрузка на CPU + +2. **PostgreSQL & HikariCP Monitoring:** + - Connection Pool Status — статистика пула (active, idle, total, pending) + - Connection Pool Utilization — процент использования пула + - Connection Acquire Time — время получения соединения (перцентили) + - Connection Timeout Count — количество таймаутов + - Connection Creation Time — время создания нового соединения + - Connection Usage Time — среднее время использования соединения + +### Полезные функции Grafana + +**Time Range:** +- Последние 5 минут — реал-тайм мониторинг +- Последний час — анализ недавних инцидентов +- Последние 24 часа — дневные паттерны + +**Refresh:** +- 5s — активный мониторинг +- 30s — обычный режим +- Off — анализ истории + +**Zoom:** +- Выдели область на графике для zoom-in +- Двойной клик — zoom-out + +**Legend:** +- Клик на метрику — скрыть/показать +- Shift+клик — изолировать метрику + +## Практические сценарии + +### 1. Медленный эндпоинт + +**Признаки:** +- Request Duration (p95) > 1s для конкретного URI +- Connection Acquire Time растет + +**Диагностика:** +```promql +# Найти медленный эндпоинт +topk(5, histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le, uri))) + +# Проверить время получения соединения +histogram_quantile(0.95, rate(hikaricp_connections_acquire_seconds_bucket[1m])) +``` + +**Решение:** +- Оптимизировать SQL запрос +- Добавить индексы +- Включить кеширование + +### 2. Memory Leak + +**Признаки:** +- Heap memory постоянно растет +- Частые Full GC паузы +- OutOfMemoryError в логах + +**Диагностика:** +```promql +# Рост памяти +jvm_memory_used_bytes{area="heap"} + +# Частота GC +rate(jvm_gc_pause_seconds_count[1m]) +``` + +**Решение:** +- Heap dump анализ (jmap) +- Проверить кеши и коллекции +- Закрывать ресурсы (connections, streams) + +### 3. Connection Pool Exhausted + +**Признаки:** +- Active connections = Max connections +- Pending threads > 0 +- Timeouts растут +- Медленные запросы + +**Диагностика:** +```promql +# Утилизация пула +(hikaricp_connections_active / hikaricp_connections_max) * 100 + +# Ожидающие потоки +hikaricp_connections_pending + +# Таймауты +rate(hikaricp_connections_timeout_total[1m]) +``` + +**Решение:** +- Увеличить `spring.datasource.hikari.maximum-pool-size` +- Найти медленные запросы +- Проверить connection leaks (незакрытые соединения) + +### 4. Высокая нагрузка + +**Признаки:** +- Request rate резко вырос +- CPU usage > 80% +- Response time увеличилось + +**Диагностика:** +```promql +# Request rate +sum(rate(http_server_requests_seconds_count[1m])) + +# CPU +system_cpu_usage + +# Response time +histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le)) +``` + +**Решение:** +- Горизонтальное масштабирование (больше инстансов) +- Rate limiting +- Кеширование частых запросов + +## Настройка алертов (опционально) + +Создай файл `prometheus-alerts.yml`: + +```yaml +groups: + - name: app_alerts + interval: 30s + rules: + - alert: HighErrorRate + expr: rate(http_server_requests_seconds_count{status=~"5.."}[1m]) > 0.1 + for: 1m + labels: + severity: critical + annotations: + summary: "High 5xx error rate" + + - alert: HighMemoryUsage + expr: (jvm_memory_used_bytes{area="heap"} / jvm_memory_max_bytes{area="heap"}) > 0.9 + for: 2m + labels: + severity: warning + annotations: + summary: "JVM heap usage > 90%" + + - alert: ConnectionPoolExhausted + expr: (hikaricp_connections_active / hikaricp_connections_max) > 0.9 + for: 1m + labels: + severity: critical + annotations: + summary: "Connection pool almost full" + + - alert: SlowEndpoint + expr: histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le, uri)) > 2 + for: 5m + labels: + severity: warning + annotations: + summary: "Endpoint p95 latency > 2s" +``` + +Добавь в `prometheus.yml`: +```yaml +rule_files: + - /etc/prometheus/prometheus-alerts.yml +``` + +## Best Practices + +1. **Регулярно проверяй метрики** — открывай Grafana хотя бы раз в день +2. **Настрой алерты** — получай уведомления о проблемах +3. **Анализируй тренды** — сравнивай метрики по неделям +4. **Документируй инциденты** — записывай что пошло не так и как исправил +5. **Тестируй под нагрузкой** — используй JMeter/Gatling + метрики для нагрузочного тестирования +6. **Не игнорируй warning** — маленькие проблемы перерастают в большие + +## Полезные PromQL запросы + +```promql +# Top 5 медленных эндпоинтов +topk(5, histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket[5m])) by (le, uri))) + +# Request rate по методам +sum(rate(http_server_requests_seconds_count[1m])) by (method) + +# Error rate % +(sum(rate(http_server_requests_seconds_count{status=~"[45].."}[1m])) / sum(rate(http_server_requests_seconds_count[1m]))) * 100 + +# Memory growth rate (MB/hour) +rate(jvm_memory_used_bytes{area="heap"}[1h]) * 3600 / 1024 / 1024 + +# Database connection wait time +sum(rate(hikaricp_connections_pending[1m])) + +# Thread count trend +jvm_threads_live_threads - jvm_threads_live_threads offset 1h +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..ceb790a --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# Todo REST API + +Spring Boot приложение для управления задачами. + +## Эндпоинты + +- `GET /api/tasks/{id}` — получить задачу по ID +- `POST /api/tasks` — создать задачу +- `PUT /api/tasks/{id}` — обновить задачу +- `DELETE /api/tasks/{id}` — удалить задачу + +## Запуск + +```bash +docker-compose up --build +``` + +Приложение доступно на `http://localhost:8080` + +## Пример запроса + +```bash +# Создать задачу +curl -X POST http://localhost:8080/api/tasks \ + -H "Content-Type: application/json" \ + -d '{"title": "Test task", "description": "Description", "completed": false}' + +# Получить задачу +curl http://localhost:8080/api/tasks/1 + +# Обновить задачу +curl -X PUT http://localhost:8080/api/tasks/1 \ + -H "Content-Type: application/json" \ + -d '{"title": "Updated", "description": "New description", "completed": true}' + +# Удалить задачу +curl -X DELETE http://localhost:8080/api/tasks/1 +``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..c7174dd --- /dev/null +++ b/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'ru.dxunvrs' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'io.micrometer:micrometer-registry-prometheus' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'org.postgresql:postgresql' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a467683 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,73 @@ +version: '3.8' + +services: + postgres: + image: postgres:16-alpine + container_name: todo-postgres + environment: + POSTGRES_DB: tododb + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 10s + timeout: 5s + retries: 5 + + app: + build: + context: . + dockerfile: Dockerfile + container_name: todo-app + environment: + DB_HOST: postgres + DB_PORT: 5432 + DB_NAME: tododb + DB_USER: postgres + DB_PASSWORD: postgres + ports: + - "8080:8080" + depends_on: + postgres: + condition: service_healthy + + prometheus: + image: prom/prometheus:latest + container_name: todo-prometheus + volumes: + - ./prometheus.yml:/etc/prometheus/prometheus.yml + - prometheus-data:/prometheus + command: + - '--config.file=/etc/prometheus/prometheus.yml' + - '--storage.tsdb.path=/prometheus' + ports: + - "9090:9090" + depends_on: + - app + + grafana: + image: grafana/grafana:latest + container_name: todo-grafana + volumes: + - grafana-data:/var/lib/grafana + - ./grafana-datasource.yml:/etc/grafana/provisioning/datasources/datasource.yml + - ./grafana-dashboard-provider.yml:/etc/grafana/provisioning/dashboards/provider.yml + - ./grafana-dashboard-app.json:/etc/grafana/provisioning/dashboards/app.json + - ./grafana-dashboard-db.json:/etc/grafana/provisioning/dashboards/db.json + environment: + - GF_SECURITY_ADMIN_USER=admin + - GF_SECURITY_ADMIN_PASSWORD=admin + - GF_USERS_ALLOW_SIGN_UP=false + ports: + - "3000:3000" + depends_on: + - prometheus + +volumes: + postgres-data: + prometheus-data: + grafana-data: diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 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 0000000..ad7845b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/gradlew.bat @@ -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% diff --git a/grafana-dashboard-app.json b/grafana-dashboard-app.json new file mode 100644 index 0000000..6bc8fe9 --- /dev/null +++ b/grafana-dashboard-app.json @@ -0,0 +1,195 @@ +{ + "dashboard": { + "title": "Spring Boot Application Metrics", + "tags": ["spring-boot", "todo-app"], + "timezone": "browser", + "panels": [ + { + "id": 1, + "title": "HTTP Request Rate", + "type": "graph", + "gridPos": {"x": 0, "y": 0, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(http_server_requests_seconds_count{application=\"todo\"}[1m])", + "legendFormat": "{{method}} {{uri}} - {{status}}" + } + ], + "yaxes": [ + {"format": "reqps", "label": "Requests/sec"}, + {"format": "short"} + ] + }, + { + "id": 2, + "title": "HTTP Request Duration (p95, p99)", + "type": "graph", + "gridPos": {"x": 12, "y": 0, "w": 12, "h": 8}, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum(rate(http_server_requests_seconds_bucket{application=\"todo\"}[5m])) by (le, uri))", + "legendFormat": "p95 - {{uri}}" + }, + { + "expr": "histogram_quantile(0.99, sum(rate(http_server_requests_seconds_bucket{application=\"todo\"}[5m])) by (le, uri))", + "legendFormat": "p99 - {{uri}}" + } + ], + "yaxes": [ + {"format": "s", "label": "Duration"}, + {"format": "short"} + ] + }, + { + "id": 3, + "title": "HTTP Status Codes", + "type": "graph", + "gridPos": {"x": 0, "y": 8, "w": 12, "h": 8}, + "targets": [ + { + "expr": "sum(rate(http_server_requests_seconds_count{application=\"todo\"}[1m])) by (status)", + "legendFormat": "{{status}}" + } + ], + "yaxes": [ + {"format": "reqps"}, + {"format": "short"} + ] + }, + { + "id": 4, + "title": "JVM Memory Used", + "type": "graph", + "gridPos": {"x": 12, "y": 8, "w": 12, "h": 8}, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"todo\", area=\"heap\"}", + "legendFormat": "Heap" + }, + { + "expr": "jvm_memory_used_bytes{application=\"todo\", area=\"nonheap\"}", + "legendFormat": "Non-Heap" + }, + { + "expr": "jvm_memory_max_bytes{application=\"todo\", area=\"heap\"}", + "legendFormat": "Heap Max" + } + ], + "yaxes": [ + {"format": "bytes"}, + {"format": "short"} + ] + }, + { + "id": 5, + "title": "Database Connection Pool", + "type": "graph", + "gridPos": {"x": 0, "y": 16, "w": 12, "h": 8}, + "targets": [ + { + "expr": "hikaricp_connections_active{application=\"todo\"}", + "legendFormat": "Active" + }, + { + "expr": "hikaricp_connections_idle{application=\"todo\"}", + "legendFormat": "Idle" + }, + { + "expr": "hikaricp_connections{application=\"todo\"}", + "legendFormat": "Total" + }, + { + "expr": "hikaricp_connections_max{application=\"todo\"}", + "legendFormat": "Max" + } + ], + "yaxes": [ + {"format": "short", "label": "Connections"}, + {"format": "short"} + ] + }, + { + "id": 6, + "title": "Database Connection Acquire Time", + "type": "graph", + "gridPos": {"x": 12, "y": 16, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(hikaricp_connections_acquire_seconds_sum{application=\"todo\"}[1m]) / rate(hikaricp_connections_acquire_seconds_count{application=\"todo\"}[1m])", + "legendFormat": "Avg Acquire Time" + } + ], + "yaxes": [ + {"format": "s"}, + {"format": "short"} + ] + }, + { + "id": 7, + "title": "JVM Threads", + "type": "graph", + "gridPos": {"x": 0, "y": 24, "w": 8, "h": 8}, + "targets": [ + { + "expr": "jvm_threads_live_threads{application=\"todo\"}", + "legendFormat": "Live" + }, + { + "expr": "jvm_threads_daemon_threads{application=\"todo\"}", + "legendFormat": "Daemon" + }, + { + "expr": "jvm_threads_peak_threads{application=\"todo\"}", + "legendFormat": "Peak" + } + ], + "yaxes": [ + {"format": "short", "label": "Threads"}, + {"format": "short"} + ] + }, + { + "id": 8, + "title": "GC Pause Time", + "type": "graph", + "gridPos": {"x": 8, "y": 24, "w": 8, "h": 8}, + "targets": [ + { + "expr": "rate(jvm_gc_pause_seconds_sum{application=\"todo\"}[1m])", + "legendFormat": "{{action}} - {{cause}}" + } + ], + "yaxes": [ + {"format": "s", "label": "GC Time"}, + {"format": "short"} + ] + }, + { + "id": 9, + "title": "System CPU Usage", + "type": "graph", + "gridPos": {"x": 16, "y": 24, "w": 8, "h": 8}, + "targets": [ + { + "expr": "system_cpu_usage{application=\"todo\"}", + "legendFormat": "System" + }, + { + "expr": "process_cpu_usage{application=\"todo\"}", + "legendFormat": "Process" + } + ], + "yaxes": [ + {"format": "percentunit", "label": "CPU"}, + {"format": "short"} + ] + } + ], + "refresh": "5s", + "time": { + "from": "now-15m", + "to": "now" + } + }, + "overwrite": true +} diff --git a/grafana-dashboard-db.json b/grafana-dashboard-db.json new file mode 100644 index 0000000..aafb3b5 --- /dev/null +++ b/grafana-dashboard-db.json @@ -0,0 +1,187 @@ +{ + "dashboard": { + "title": "PostgreSQL & HikariCP Monitoring", + "tags": ["database", "postgres", "hikaricp"], + "timezone": "browser", + "panels": [ + { + "id": 1, + "title": "Connection Pool Status", + "type": "stat", + "gridPos": {"x": 0, "y": 0, "w": 6, "h": 4}, + "targets": [ + { + "expr": "hikaricp_connections_active{application=\"todo\"}", + "legendFormat": "Active" + } + ], + "options": { + "colorMode": "value", + "graphMode": "area" + } + }, + { + "id": 2, + "title": "Idle Connections", + "type": "stat", + "gridPos": {"x": 6, "y": 0, "w": 6, "h": 4}, + "targets": [ + { + "expr": "hikaricp_connections_idle{application=\"todo\"}", + "legendFormat": "Idle" + } + ], + "options": { + "colorMode": "value", + "graphMode": "area" + } + }, + { + "id": 3, + "title": "Total Connections", + "type": "stat", + "gridPos": {"x": 12, "y": 0, "w": 6, "h": 4}, + "targets": [ + { + "expr": "hikaricp_connections{application=\"todo\"}", + "legendFormat": "Total" + } + ], + "options": { + "colorMode": "value", + "graphMode": "area" + } + }, + { + "id": 4, + "title": "Pending Threads", + "type": "stat", + "gridPos": {"x": 18, "y": 0, "w": 6, "h": 4}, + "targets": [ + { + "expr": "hikaricp_connections_pending{application=\"todo\"}", + "legendFormat": "Pending" + } + ], + "options": { + "colorMode": "value", + "graphMode": "area" + } + }, + { + "id": 5, + "title": "Connection Pool Utilization (%)", + "type": "graph", + "gridPos": {"x": 0, "y": 4, "w": 12, "h": 8}, + "targets": [ + { + "expr": "(hikaricp_connections_active{application=\"todo\"} / hikaricp_connections_max{application=\"todo\"}) * 100", + "legendFormat": "Active %" + }, + { + "expr": "(hikaricp_connections{application=\"todo\"} / hikaricp_connections_max{application=\"todo\"}) * 100", + "legendFormat": "Total %" + } + ], + "yaxes": [ + {"format": "percent", "label": "Utilization", "min": 0, "max": 100}, + {"format": "short"} + ] + }, + { + "id": 6, + "title": "Connection Acquire Time", + "type": "graph", + "gridPos": {"x": 12, "y": 4, "w": 12, "h": 8}, + "targets": [ + { + "expr": "histogram_quantile(0.5, rate(hikaricp_connections_acquire_seconds_bucket{application=\"todo\"}[1m]))", + "legendFormat": "p50" + }, + { + "expr": "histogram_quantile(0.95, rate(hikaricp_connections_acquire_seconds_bucket{application=\"todo\"}[1m]))", + "legendFormat": "p95" + }, + { + "expr": "histogram_quantile(0.99, rate(hikaricp_connections_acquire_seconds_bucket{application=\"todo\"}[1m]))", + "legendFormat": "p99" + } + ], + "yaxes": [ + {"format": "s", "label": "Time"}, + {"format": "short"} + ] + }, + { + "id": 7, + "title": "Connection Timeout Count", + "type": "graph", + "gridPos": {"x": 0, "y": 12, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(hikaricp_connections_timeout_total{application=\"todo\"}[1m])", + "legendFormat": "Timeouts/sec" + } + ], + "yaxes": [ + {"format": "short"}, + {"format": "short"} + ] + }, + { + "id": 8, + "title": "Connection Creation Time", + "type": "graph", + "gridPos": {"x": 12, "y": 12, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(hikaricp_connections_creation_seconds_sum{application=\"todo\"}[1m]) / rate(hikaricp_connections_creation_seconds_count{application=\"todo\"}[1m])", + "legendFormat": "Avg Creation Time" + } + ], + "yaxes": [ + {"format": "s"}, + {"format": "short"} + ] + }, + { + "id": 9, + "title": "Connection Usage Time", + "type": "graph", + "gridPos": {"x": 0, "y": 20, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(hikaricp_connections_usage_seconds_sum{application=\"todo\"}[1m]) / rate(hikaricp_connections_usage_seconds_count{application=\"todo\"}[1m])", + "legendFormat": "Avg Usage Time" + } + ], + "yaxes": [ + {"format": "s"}, + {"format": "short"} + ] + }, + { + "id": 10, + "title": "JDBC Queries Rate", + "type": "graph", + "gridPos": {"x": 12, "y": 20, "w": 12, "h": 8}, + "targets": [ + { + "expr": "rate(jdbc_connections_active{application=\"todo\"}[1m])", + "legendFormat": "Active JDBC Connections" + } + ], + "yaxes": [ + {"format": "short"}, + {"format": "short"} + ] + } + ], + "refresh": "5s", + "time": { + "from": "now-15m", + "to": "now" + } + }, + "overwrite": true +} diff --git a/grafana-dashboard-provider.yml b/grafana-dashboard-provider.yml new file mode 100644 index 0000000..06525c8 --- /dev/null +++ b/grafana-dashboard-provider.yml @@ -0,0 +1,12 @@ +apiVersion: 1 + +providers: + - name: 'Default' + orgId: 1 + folder: '' + type: file + disableDeletion: false + updateIntervalSeconds: 10 + allowUiUpdates: true + options: + path: /etc/grafana/provisioning/dashboards diff --git a/grafana-datasource.yml b/grafana-datasource.yml new file mode 100644 index 0000000..1a57b69 --- /dev/null +++ b/grafana-datasource.yml @@ -0,0 +1,9 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: true diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2132b5a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "todo", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/package.json @@ -0,0 +1 @@ +{} diff --git a/prometheus.yml b/prometheus.yml new file mode 100644 index 0000000..945d8f9 --- /dev/null +++ b/prometheus.yml @@ -0,0 +1,9 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +scrape_configs: + - job_name: 'spring-boot-app' + metrics_path: '/actuator/prometheus' + static_configs: + - targets: ['app:8080'] diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b63869e --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'todo' diff --git a/src/main/java/ru/dxunvrs/todo/TodoApplication.java b/src/main/java/ru/dxunvrs/todo/TodoApplication.java new file mode 100644 index 0000000..9fcd9eb --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/TodoApplication.java @@ -0,0 +1,13 @@ +package ru.dxunvrs.todo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TodoApplication { + + public static void main(String[] args) { + SpringApplication.run(TodoApplication.class, args); + } + +} diff --git a/src/main/java/ru/dxunvrs/todo/controller/TaskController.java b/src/main/java/ru/dxunvrs/todo/controller/TaskController.java new file mode 100644 index 0000000..c8f6398 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/controller/TaskController.java @@ -0,0 +1,45 @@ +package ru.dxunvrs.todo.controller; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import ru.dxunvrs.todo.dto.TaskCreateRequest; +import ru.dxunvrs.todo.dto.TaskResponse; +import ru.dxunvrs.todo.dto.TaskUpdateRequest; +import ru.dxunvrs.todo.service.TaskService; + +@RestController +@RequestMapping("/api/tasks") +@RequiredArgsConstructor +public class TaskController { + + private final TaskService taskService; + + @GetMapping("/{id}") + public ResponseEntity getTask(@PathVariable Long id) { + TaskResponse response = taskService.getById(id); + return ResponseEntity.ok(response); + } + + @PostMapping + public ResponseEntity createTask(@Valid @RequestBody TaskCreateRequest request) { + TaskResponse response = taskService.create(request); + return ResponseEntity.status(HttpStatus.CREATED).body(response); + } + + @PutMapping("/{id}") + public ResponseEntity updateTask( + @PathVariable Long id, + @Valid @RequestBody TaskUpdateRequest request) { + TaskResponse response = taskService.update(id, request); + return ResponseEntity.ok(response); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteTask(@PathVariable Long id) { + taskService.delete(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/ru/dxunvrs/todo/dto/TaskCreateRequest.java b/src/main/java/ru/dxunvrs/todo/dto/TaskCreateRequest.java new file mode 100644 index 0000000..6c729a3 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/dto/TaskCreateRequest.java @@ -0,0 +1,19 @@ +package ru.dxunvrs.todo.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TaskCreateRequest { + + @NotBlank(message = "Title is required") + private String title; + + private String description; + + private Boolean completed; +} diff --git a/src/main/java/ru/dxunvrs/todo/dto/TaskResponse.java b/src/main/java/ru/dxunvrs/todo/dto/TaskResponse.java new file mode 100644 index 0000000..437f93b --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/dto/TaskResponse.java @@ -0,0 +1,20 @@ +package ru.dxunvrs.todo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TaskResponse { + + private Long id; + private String title; + private String description; + private Boolean completed; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/src/main/java/ru/dxunvrs/todo/dto/TaskUpdateRequest.java b/src/main/java/ru/dxunvrs/todo/dto/TaskUpdateRequest.java new file mode 100644 index 0000000..0fdceec --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/dto/TaskUpdateRequest.java @@ -0,0 +1,19 @@ +package ru.dxunvrs.todo.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TaskUpdateRequest { + + @NotBlank(message = "Title is required") + private String title; + + private String description; + + private Boolean completed; +} diff --git a/src/main/java/ru/dxunvrs/todo/entity/Task.java b/src/main/java/ru/dxunvrs/todo/entity/Task.java new file mode 100644 index 0000000..db50fb5 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/entity/Task.java @@ -0,0 +1,46 @@ +package ru.dxunvrs.todo.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "tasks") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Task { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String title; + + @Column(columnDefinition = "TEXT") + private String description; + + @Column(nullable = false) + private Boolean completed = false; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/ru/dxunvrs/todo/exception/GlobalExceptionHandler.java b/src/main/java/ru/dxunvrs/todo/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..90bfb09 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/exception/GlobalExceptionHandler.java @@ -0,0 +1,58 @@ +package ru.dxunvrs.todo.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(TaskNotFoundException.class) + public ResponseEntity handleTaskNotFound(TaskNotFoundException ex) { + ErrorResponse error = new ErrorResponse( + HttpStatus.NOT_FOUND.value(), + ex.getMessage(), + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach(error -> { + String fieldName = ((FieldError) error).getField(); + String message = error.getDefaultMessage(); + errors.put(fieldName, message); + }); + + ValidationErrorResponse response = new ValidationErrorResponse( + HttpStatus.BAD_REQUEST.value(), + "Validation failed", + LocalDateTime.now(), + errors + ); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGeneral(Exception ex) { + ErrorResponse error = new ErrorResponse( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + "Internal server error", + LocalDateTime.now() + ); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); + } + + record ErrorResponse(int status, String message, LocalDateTime timestamp) {} + + record ValidationErrorResponse(int status, String message, LocalDateTime timestamp, Map errors) {} +} diff --git a/src/main/java/ru/dxunvrs/todo/exception/TaskNotFoundException.java b/src/main/java/ru/dxunvrs/todo/exception/TaskNotFoundException.java new file mode 100644 index 0000000..4dbc403 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/exception/TaskNotFoundException.java @@ -0,0 +1,7 @@ +package ru.dxunvrs.todo.exception; + +public class TaskNotFoundException extends RuntimeException { + public TaskNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/dxunvrs/todo/mapper/TaskMapper.java b/src/main/java/ru/dxunvrs/todo/mapper/TaskMapper.java new file mode 100644 index 0000000..921c778 --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/mapper/TaskMapper.java @@ -0,0 +1,38 @@ +package ru.dxunvrs.todo.mapper; + +import org.springframework.stereotype.Component; +import ru.dxunvrs.todo.dto.TaskCreateRequest; +import ru.dxunvrs.todo.dto.TaskResponse; +import ru.dxunvrs.todo.dto.TaskUpdateRequest; +import ru.dxunvrs.todo.entity.Task; + +@Component +public class TaskMapper { + + public Task toEntity(TaskCreateRequest request) { + Task task = new Task(); + task.setTitle(request.getTitle()); + task.setDescription(request.getDescription()); + task.setCompleted(request.getCompleted() != null ? request.getCompleted() : false); + return task; + } + + public void updateEntity(Task task, TaskUpdateRequest request) { + task.setTitle(request.getTitle()); + task.setDescription(request.getDescription()); + if (request.getCompleted() != null) { + task.setCompleted(request.getCompleted()); + } + } + + public TaskResponse toResponse(Task task) { + return new TaskResponse( + task.getId(), + task.getTitle(), + task.getDescription(), + task.getCompleted(), + task.getCreatedAt(), + task.getUpdatedAt() + ); + } +} diff --git a/src/main/java/ru/dxunvrs/todo/repository/TaskRepository.java b/src/main/java/ru/dxunvrs/todo/repository/TaskRepository.java new file mode 100644 index 0000000..d6dcacd --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/repository/TaskRepository.java @@ -0,0 +1,9 @@ +package ru.dxunvrs.todo.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import ru.dxunvrs.todo.entity.Task; + +@Repository +public interface TaskRepository extends JpaRepository { +} diff --git a/src/main/java/ru/dxunvrs/todo/service/TaskService.java b/src/main/java/ru/dxunvrs/todo/service/TaskService.java new file mode 100644 index 0000000..2cf22dc --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/service/TaskService.java @@ -0,0 +1,16 @@ +package ru.dxunvrs.todo.service; + +import ru.dxunvrs.todo.dto.TaskCreateRequest; +import ru.dxunvrs.todo.dto.TaskResponse; +import ru.dxunvrs.todo.dto.TaskUpdateRequest; + +public interface TaskService { + + TaskResponse getById(Long id); + + TaskResponse create(TaskCreateRequest request); + + TaskResponse update(Long id, TaskUpdateRequest request); + + void delete(Long id); +} diff --git a/src/main/java/ru/dxunvrs/todo/service/TaskServiceImpl.java b/src/main/java/ru/dxunvrs/todo/service/TaskServiceImpl.java new file mode 100644 index 0000000..392cefc --- /dev/null +++ b/src/main/java/ru/dxunvrs/todo/service/TaskServiceImpl.java @@ -0,0 +1,55 @@ +package ru.dxunvrs.todo.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.dxunvrs.todo.dto.TaskCreateRequest; +import ru.dxunvrs.todo.dto.TaskResponse; +import ru.dxunvrs.todo.dto.TaskUpdateRequest; +import ru.dxunvrs.todo.entity.Task; +import ru.dxunvrs.todo.exception.TaskNotFoundException; +import ru.dxunvrs.todo.mapper.TaskMapper; +import ru.dxunvrs.todo.repository.TaskRepository; + +@Service +@RequiredArgsConstructor +public class TaskServiceImpl implements TaskService { + + private final TaskRepository taskRepository; + private final TaskMapper taskMapper; + + @Override + @Transactional(readOnly = true) + public TaskResponse getById(Long id) { + Task task = taskRepository.findById(id) + .orElseThrow(() -> new TaskNotFoundException("Task not found with id: " + id)); + return taskMapper.toResponse(task); + } + + @Override + @Transactional + public TaskResponse create(TaskCreateRequest request) { + Task task = taskMapper.toEntity(request); + Task saved = taskRepository.save(task); + return taskMapper.toResponse(saved); + } + + @Override + @Transactional + public TaskResponse update(Long id, TaskUpdateRequest request) { + Task task = taskRepository.findById(id) + .orElseThrow(() -> new TaskNotFoundException("Task not found with id: " + id)); + taskMapper.updateEntity(task, request); + Task updated = taskRepository.save(task); + return taskMapper.toResponse(updated); + } + + @Override + @Transactional + public void delete(Long id) { + if (!taskRepository.existsById(id)) { + throw new TaskNotFoundException("Task not found with id: " + id); + } + taskRepository.deleteById(id); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..162063a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,24 @@ +spring.application.name=todo + +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:tododb} +spring.datasource.username=${DB_USER:postgres} +spring.datasource.password=${DB_PASSWORD:postgres} +spring.datasource.driver-class-name=org.postgresql.Driver + +spring.datasource.hikari.maximum-pool-size=10 +spring.datasource.hikari.minimum-idle=5 +spring.datasource.hikari.connection-timeout=30000 +spring.datasource.hikari.idle-timeout=600000 +spring.datasource.hikari.max-lifetime=1800000 + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.properties.hibernate.format_sql=true + +management.endpoints.web.exposure.include=health,info,metrics,prometheus +management.endpoint.health.show-details=always +management.endpoint.prometheus.enabled=true +management.metrics.export.prometheus.enabled=true +management.metrics.tags.application=${spring.application.name} +management.metrics.distribution.percentiles-histogram.http.server.requests=true diff --git a/src/test/java/ru/dxunvrs/todo/TodoApplicationTests.java b/src/test/java/ru/dxunvrs/todo/TodoApplicationTests.java new file mode 100644 index 0000000..d9d4f17 --- /dev/null +++ b/src/test/java/ru/dxunvrs/todo/TodoApplicationTests.java @@ -0,0 +1,13 @@ +package ru.dxunvrs.todo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TodoApplicationTests { + + @Test + void contextLoads() { + } + +}