From 380d0ef71000d0e05edb27711fbf841b79e10a85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Wed, 30 Sep 2026 22:32:04 +0300 Subject: [PATCH] feat: port backend implementation from lab1 --- .dockerignore | 22 ++++ Dockerfile | 29 +++++ backend/cmd/server/main.go | 69 +++++++++++ backend/go.mod | 40 +++++++ backend/go.sum | 91 ++++++++++++++ backend/internal/domain/entity.go | 29 +++++ backend/internal/domain/errors.go | 82 +++++++++++++ backend/internal/domain/repository.go | 20 ++++ backend/internal/httpapi/dto/chat.go | 39 ++++++ backend/internal/httpapi/dto/error.go | 69 +++++++++++ backend/internal/httpapi/dto/health.go | 5 + backend/internal/httpapi/dto/message.go | 40 +++++++ backend/internal/httpapi/dto/user.go | 28 +++++ backend/internal/httpapi/handler/bind.go | 52 ++++++++ backend/internal/httpapi/handler/chat.go | 88 ++++++++++++++ backend/internal/httpapi/handler/health.go | 23 ++++ backend/internal/httpapi/handler/message.go | 68 +++++++++++ backend/internal/httpapi/handler/response.go | 35 ++++++ backend/internal/httpapi/handler/user.go | 43 +++++++ backend/internal/httpapi/middleware/auth.go | 49 ++++++++ .../internal/httpapi/middleware/requestid.go | 32 +++++ backend/internal/httpapi/router.go | 45 +++++++ backend/internal/service/chat.go | 95 +++++++++++++++ backend/internal/service/message.go | 72 +++++++++++ backend/internal/service/user.go | 76 ++++++++++++ backend/internal/storage/memory/chat.go | 102 ++++++++++++++++ backend/internal/storage/memory/cursor.go | 47 ++++++++ backend/internal/storage/memory/message.go | 93 +++++++++++++++ backend/internal/storage/memory/storage.go | 34 ++++++ backend/internal/storage/memory/user.go | 59 +++++++++ student-tests/README.md | 7 ++ student-tests/run_all.py | 20 ++++ student-tests/test_cases.py | 112 ++++++++++++++++++ student-tests/test_concurrency.py | 80 +++++++++++++ 34 files changed, 1795 insertions(+) create mode 100644 Dockerfile create mode 100644 backend/cmd/server/main.go create mode 100644 backend/go.mod create mode 100644 backend/go.sum create mode 100644 backend/internal/domain/entity.go create mode 100644 backend/internal/domain/errors.go create mode 100644 backend/internal/domain/repository.go create mode 100644 backend/internal/httpapi/dto/chat.go create mode 100644 backend/internal/httpapi/dto/error.go create mode 100644 backend/internal/httpapi/dto/health.go create mode 100644 backend/internal/httpapi/dto/message.go create mode 100644 backend/internal/httpapi/dto/user.go create mode 100644 backend/internal/httpapi/handler/bind.go create mode 100644 backend/internal/httpapi/handler/chat.go create mode 100644 backend/internal/httpapi/handler/health.go create mode 100644 backend/internal/httpapi/handler/message.go create mode 100644 backend/internal/httpapi/handler/response.go create mode 100644 backend/internal/httpapi/handler/user.go create mode 100644 backend/internal/httpapi/middleware/auth.go create mode 100644 backend/internal/httpapi/middleware/requestid.go create mode 100644 backend/internal/httpapi/router.go create mode 100644 backend/internal/service/chat.go create mode 100644 backend/internal/service/message.go create mode 100644 backend/internal/service/user.go create mode 100644 backend/internal/storage/memory/chat.go create mode 100644 backend/internal/storage/memory/cursor.go create mode 100644 backend/internal/storage/memory/message.go create mode 100644 backend/internal/storage/memory/storage.go create mode 100644 backend/internal/storage/memory/user.go create mode 100644 student-tests/README.md create mode 100644 student-tests/run_all.py create mode 100644 student-tests/test_cases.py create mode 100644 student-tests/test_concurrency.py diff --git a/.dockerignore b/.dockerignore index bc16e55..9caa949 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,7 @@ .git +.gitignore .github + .env .env.* !.env.example @@ -13,8 +15,28 @@ backups *.p12 *.pfx *.jks + .venv __pycache__ node_modules + evidence .DS_Store + +tests +my-tests +scripts +examples +contracts +README.md +COURSE.md +CONTRIBUTING.md +MAINTAINERS.md +REPORT.md + +Makefile +requirements-dev.txt +Dockerfile.example + +Dockerfile +.dockerignore \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1622925 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +FROM golang:1.26.1-alpine AS builder + +WORKDIR /src + +COPY backend/go.mod backend/go.sum ./ +RUN go mod download + +COPY backend/ . + +RUN CGO_ENABLED=0 GOOS=linux go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /out/server \ + ./cmd/server + +FROM alpine:3.20 + +RUN adduser -D -u 1000 app + +COPY --from=builder /out/server /server + +EXPOSE 8080 + +USER app + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O - http://127.0.0.1:8080/health/live >/dev/null || exit 1 + +ENTRYPOINT ["/server"] \ No newline at end of file diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go new file mode 100644 index 0000000..4ca897a --- /dev/null +++ b/backend/cmd/server/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "high-loud-apps-labs/internal/httpapi" + "high-loud-apps-labs/internal/httpapi/handler" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" + "high-loud-apps-labs/internal/storage/memory" +) + +func main() { + addr := getenv("APP_HOST", "0.0.0.0") + ":" + getenv("APP_PORT", "8080") + + store := memory.New() + + userSvc := service.NewUserService(store.Users()) + chatSvc := service.NewChatService(store.Chats(), store.Users()) + messageSvc := service.NewMessageService(store.Messages(), store.Chats()) + + router := httpapi.NewRouter( + httpapi.Handlers{ + Health: handler.NewHealthHandler(), + User: handler.NewUserHandler(userSvc), + Chat: handler.NewChatHandler(chatSvc), + Message: handler.NewMessageHandler(messageSvc), + }, + middleware.Auth(store.Users()), + ) + + srv := &http.Server{ + Addr: addr, + Handler: router, + } + + go func() { + log.Printf("Запускаем на %s", addr) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("Ошибка запуска: %v", err) + } + }() + + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + log.Println("Получен сигнал завершения, останавливаем сервер...") + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := srv.Shutdown(ctx); err != nil { + log.Fatalf("Ошибка при остановке: %v", err) + } + log.Println("Сервер остановлен") +} + +func getenv(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..c2e4b21 --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,40 @@ +module high-loud-apps-labs + +go 1.26.1 + +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/google/uuid v1.6.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..0b62b83 --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,91 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/backend/internal/domain/entity.go b/backend/internal/domain/entity.go new file mode 100644 index 0000000..ee00b9c --- /dev/null +++ b/backend/internal/domain/entity.go @@ -0,0 +1,29 @@ +package domain + +import "time" + +type Health struct { + Status string +} + +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} + +type Message struct { + ID string + ChatID string + SenderID string + Text string + CreatedAt time.Time +} diff --git a/backend/internal/domain/errors.go b/backend/internal/domain/errors.go new file mode 100644 index 0000000..79f8a79 --- /dev/null +++ b/backend/internal/domain/errors.go @@ -0,0 +1,82 @@ +package domain + +import ( + "errors" + "fmt" +) + +type ErrorCode string + +const ( + CodeInvalidRequest ErrorCode = "invalid_request" + CodeUnauthorized ErrorCode = "unauthorized" + CodeNotFound ErrorCode = "not_found" + CodeConflict ErrorCode = "conflict" + CodeUnsupportedMediaType ErrorCode = "unsupported_media_type" + CodeInternalError ErrorCode = "internal_error" +) + +var ( + ErrNotFound = errors.New("не найдено") + ErrAlreadyExists = errors.New("уже существует") + ErrInvalidInput = errors.New("некорректные данные") + ErrForbidden = errors.New("доступ запрещён") + ErrUnsupportedMediaType = errors.New("неподдерживаемый тип содержимого") +) + +type NotFoundError struct { + Entity string + ID string +} + +func (e *NotFoundError) Error() string { + return fmt.Sprintf("%s с id %q не найден", e.Entity, e.ID) +} +func (e *NotFoundError) Unwrap() error { return ErrNotFound } +func (e *NotFoundError) Code() ErrorCode { return CodeNotFound } + +type AlreadyExistsError struct { + Entity string + Field string + Value string +} + +func (e *AlreadyExistsError) Error() string { + return fmt.Sprintf("%s с %s %q уже существует", e.Entity, e.Field, e.Value) +} +func (e *AlreadyExistsError) Unwrap() error { return ErrAlreadyExists } +func (e *AlreadyExistsError) Code() ErrorCode { return CodeConflict } + +type ValidationError struct { + Field string + Message string +} + +func (e *ValidationError) Error() string { + return fmt.Sprintf("ошибка валидации поля %q: %s", e.Field, e.Message) +} +func (e *ValidationError) Unwrap() error { return ErrInvalidInput } +func (e *ValidationError) Code() ErrorCode { return CodeInvalidRequest } + +type ForbiddenError struct { + Reason string +} + +func (e *ForbiddenError) Error() string { + return fmt.Sprintf("доступ запрещён: %s", e.Reason) +} +func (e *ForbiddenError) Unwrap() error { return ErrForbidden } +func (e *ForbiddenError) Code() ErrorCode { return CodeUnauthorized } + +type UnsupportedMediaTypeError struct { + MediaType string +} + +func (e *UnsupportedMediaTypeError) Error() string { + if e.MediaType == "" { + return "требуется Content-Type: application/json" + } + return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется application/json", e.MediaType) +} +func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType } +func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType } diff --git a/backend/internal/domain/repository.go b/backend/internal/domain/repository.go new file mode 100644 index 0000000..02d344d --- /dev/null +++ b/backend/internal/domain/repository.go @@ -0,0 +1,20 @@ +package domain + +import "context" + +type UserRepository interface { + Create(ctx context.Context, user *User) error + GetByID(ctx context.Context, id string) (*User, error) + GetByUsername(ctx context.Context, username string) (*User, error) +} + +type ChatRepository interface { + Create(ctx context.Context, chat *Chat) error + GetByID(ctx context.Context, id string) (*Chat, error) + ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]Chat, *string, error) +} + +type MessageRepository interface { + Create(ctx context.Context, message *Message) error + ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]Message, *string, error) +} diff --git a/backend/internal/httpapi/dto/chat.go b/backend/internal/httpapi/dto/chat.go new file mode 100644 index 0000000..a9bf042 --- /dev/null +++ b/backend/internal/httpapi/dto/chat.go @@ -0,0 +1,39 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +type CreateChatRequest struct { + Title string `json:"title" binding:"required,min=1,max=100"` + MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func ChatFromDomain(c *domain.Chat) ChatResponse { + return ChatResponse{ + ID: c.ID, + Title: c.Title, + MemberIDs: append([]string(nil), c.MemberIDs...), + CreatedAt: c.CreatedAt.UTC().Format(timeFormat), + } +} + +func ChatsFromDomain(items []domain.Chat) []ChatResponse { + out := make([]ChatResponse, len(items)) + for i := range items { + out[i] = ChatFromDomain(&items[i]) + } + return out +} diff --git a/backend/internal/httpapi/dto/error.go b/backend/internal/httpapi/dto/error.go new file mode 100644 index 0000000..0fe6c00 --- /dev/null +++ b/backend/internal/httpapi/dto/error.go @@ -0,0 +1,69 @@ +package dto + +import ( + "errors" + + "high-loud-apps-labs/internal/domain" +) + +// делаем вложенный ответ через вкладку ErrorBody в обертку. + +type ErrorBody struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +type ErrorResponse struct { + Error ErrorBody `json:"error"` +} + +type coded interface { + Code() domain.ErrorCode +} + +func ErrorFromDomain(err error, requestID string) ErrorResponse { + var c coded + if errors.As(err, &c) { + return ErrorResponse{Error: ErrorBody{ + Code: string(c.Code()), + Message: err.Error(), + RequestID: requestID, + }} + } + code := domain.CodeInternalError + switch { + case errors.Is(err, domain.ErrNotFound): + code = domain.CodeNotFound + case errors.Is(err, domain.ErrAlreadyExists): + code = domain.CodeConflict + case errors.Is(err, domain.ErrInvalidInput): + code = domain.CodeInvalidRequest + case errors.Is(err, domain.ErrForbidden): + code = domain.CodeUnauthorized + case errors.Is(err, domain.ErrUnsupportedMediaType): + code = domain.CodeUnsupportedMediaType + } + return ErrorResponse{Error: ErrorBody{ + Code: string(code), + Message: err.Error(), + RequestID: requestID, + }} +} + +func StatusFromError(err error) int { + switch { + case errors.Is(err, domain.ErrNotFound): + return 404 + case errors.Is(err, domain.ErrAlreadyExists): + return 409 + case errors.Is(err, domain.ErrInvalidInput): + return 400 + case errors.Is(err, domain.ErrForbidden): + return 401 + case errors.Is(err, domain.ErrUnsupportedMediaType): + return 415 + default: + return 500 + } +} diff --git a/backend/internal/httpapi/dto/health.go b/backend/internal/httpapi/dto/health.go new file mode 100644 index 0000000..8bb3503 --- /dev/null +++ b/backend/internal/httpapi/dto/health.go @@ -0,0 +1,5 @@ +package dto + +type HealthResponse struct { + Status string `json:"status"` +} diff --git a/backend/internal/httpapi/dto/message.go b/backend/internal/httpapi/dto/message.go new file mode 100644 index 0000000..31f9471 --- /dev/null +++ b/backend/internal/httpapi/dto/message.go @@ -0,0 +1,40 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +type CreateMessageRequest struct { + Text string `json:"text" binding:"required,min=1,max=4000"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func MessageFromDomain(m *domain.Message) MessageResponse { + return MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + CreatedAt: m.CreatedAt.UTC().Format(timeFormat), + } +} + +func MessagesFromDomain(items []domain.Message) []MessageResponse { + out := make([]MessageResponse, len(items)) + for i := range items { + out[i] = MessageFromDomain(&items[i]) + } + return out +} diff --git a/backend/internal/httpapi/dto/user.go b/backend/internal/httpapi/dto/user.go new file mode 100644 index 0000000..07b9ebf --- /dev/null +++ b/backend/internal/httpapi/dto/user.go @@ -0,0 +1,28 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +const timeFormat = "2006-01-02T15:04:05.000000Z07:00" + +type CreateUserRequest struct { + Username string `json:"username" binding:"required,min=3,max=32"` + DisplayName string `json:"display_name" binding:"required,min=1,max=100"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} + +func UserFromDomain(u *domain.User) UserResponse { + return UserResponse{ + ID: u.ID, + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: u.CreatedAt.UTC().Format(timeFormat), + } +} diff --git a/backend/internal/httpapi/handler/bind.go b/backend/internal/httpapi/handler/bind.go new file mode 100644 index 0000000..cca7387 --- /dev/null +++ b/backend/internal/httpapi/handler/bind.go @@ -0,0 +1,52 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "mime" + "strings" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + + "high-loud-apps-labs/internal/domain" +) + +func bindStrictJSON(c *gin.Context, dst any) error { + ct := c.GetHeader("Content-Type") + mediaType, _, err := mime.ParseMediaType(ct) + if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") { + return &domain.UnsupportedMediaTypeError{MediaType: ct} + } + + body, err := io.ReadAll(c.Request.Body) + if err != nil { + return &badRequestError{msg: "не удалось прочитать тело запроса"} + } + _ = c.Request.Body.Close() + + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + + if err := dec.Decode(dst); err != nil { + if errors.Is(err, io.EOF) { + return &badRequestError{msg: "тело запроса обязательно"} + } + return &badRequestError{msg: err.Error()} + } + + // Отклоняем любой непустой остаток после первого JSON-значения. + var extra json.RawMessage + if err := dec.Decode(&extra); !errors.Is(err, io.EOF) { + return &badRequestError{msg: "тело запроса содержит данные после JSON"} + } + + if v := binding.Validator; v != nil { + if err := v.ValidateStruct(dst); err != nil { + return &badRequestError{msg: err.Error()} + } + } + return nil +} diff --git a/backend/internal/httpapi/handler/chat.go b/backend/internal/httpapi/handler/chat.go new file mode 100644 index 0000000..86fc2cd --- /dev/null +++ b/backend/internal/httpapi/handler/chat.go @@ -0,0 +1,88 @@ +package handler + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type ChatHandler struct { + chats *service.ChatService +} + +func NewChatHandler(chats *service.ChatService) *ChatHandler { + return &ChatHandler{chats: chats} +} + +func (h *ChatHandler) Create(c *gin.Context) { + var req dto.CreateChatRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + me := middleware.CurrentUser(c) + + chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusCreated, dto.ChatFromDomain(chat)) +} + +func (h *ChatHandler) Get(c *gin.Context) { + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.ChatFromDomain(chat)) +} + +func (h *ChatHandler) List(c *gin.Context) { + me := middleware.CurrentUser(c) + limit, cursor, err := parseListQuery(c) + if err != nil { + respondError(c, err) + return + } + + items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.ChatPageResponse{ + Items: dto.ChatsFromDomain(items), + NextCursor: next, + }) +} + +func parseListQuery(c *gin.Context) (int, *string, error) { + limit := 50 + if v := c.Query("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > 100 { + return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"} + } + limit = n + } + var cursor *string + if v := c.Query("cursor"); v != "" { + cursor = &v + } + return limit, cursor, nil +} diff --git a/backend/internal/httpapi/handler/health.go b/backend/internal/httpapi/handler/health.go new file mode 100644 index 0000000..fc4ee1e --- /dev/null +++ b/backend/internal/httpapi/handler/health.go @@ -0,0 +1,23 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" +) + +type HealthHandler struct{} + +func NewHealthHandler() *HealthHandler { + return &HealthHandler{} +} + +func (h *HealthHandler) Live(c *gin.Context) { + c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"}) +} + +func (h *HealthHandler) Ready(c *gin.Context) { + c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"}) +} diff --git a/backend/internal/httpapi/handler/message.go b/backend/internal/httpapi/handler/message.go new file mode 100644 index 0000000..354c7ed --- /dev/null +++ b/backend/internal/httpapi/handler/message.go @@ -0,0 +1,68 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type MessageHandler struct { + messages *service.MessageService +} + +func NewMessageHandler(messages *service.MessageService) *MessageHandler { + return &MessageHandler{messages: messages} +} + +func (h *MessageHandler) Create(c *gin.Context) { + var req dto.CreateMessageRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + m, err := h.messages.Create(c.Request.Context(), me.ID, chatID, req.Text) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusCreated, dto.MessageFromDomain(m)) +} + +func (h *MessageHandler) List(c *gin.Context) { + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + limit, cursor, err := parseListQuery(c) + if err != nil { + respondError(c, err) + return + } + + items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.MessagePageResponse{ + Items: dto.MessagesFromDomain(items), + NextCursor: next, + }) +} diff --git a/backend/internal/httpapi/handler/response.go b/backend/internal/httpapi/handler/response.go new file mode 100644 index 0000000..5f06609 --- /dev/null +++ b/backend/internal/httpapi/handler/response.go @@ -0,0 +1,35 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" +) + +type badRequestError struct{ msg string } + +func (e *badRequestError) Error() string { return e.msg } +func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput } +func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest } + +func parseUUIDPathParam(c *gin.Context, name string) (string, error) { + raw := c.Param(name) + if raw == "" { + return "", &badRequestError{msg: "параметр " + name + " обязателен"} + } + + id, err := uuid.Parse(raw) + if err != nil { + return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"} + } + + return id.String(), nil +} + +func respondError(c *gin.Context, err error) { + reqID := middleware.GetRequestID(c) + c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID)) +} diff --git a/backend/internal/httpapi/handler/user.go b/backend/internal/httpapi/handler/user.go new file mode 100644 index 0000000..35ad917 --- /dev/null +++ b/backend/internal/httpapi/handler/user.go @@ -0,0 +1,43 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type UserHandler struct { + users *service.UserService +} + +func NewUserHandler(users *service.UserService) *UserHandler { + return &UserHandler{users: users} +} + +func (h *UserHandler) Create(c *gin.Context) { + var req dto.CreateUserRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + + u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusCreated, dto.UserFromDomain(u)) +} + +func (h *UserHandler) Current(c *gin.Context) { + u := middleware.CurrentUser(c) + if u == nil { + respondError(c, &badRequestError{msg: "нет текущего пользователя"}) + return + } + c.JSON(http.StatusOK, dto.UserFromDomain(u)) +} diff --git a/backend/internal/httpapi/middleware/auth.go b/backend/internal/httpapi/middleware/auth.go new file mode 100644 index 0000000..589287f --- /dev/null +++ b/backend/internal/httpapi/middleware/auth.go @@ -0,0 +1,49 @@ +package middleware + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" +) + +const CurrentUserKey = "current_user" + +func Auth(users domain.UserRepository) gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader("X-User-Id") + if id == "" { + abortUnauthorized(c, "требуется X-User-Id") + return + } + + u, err := users.GetByID(c.Request.Context(), id) + if err != nil { + abortUnauthorized(c, "неизвестный пользователь") + return + } + + c.Set(CurrentUserKey, u) + c.Next() + } +} + +func CurrentUser(c *gin.Context) *domain.User { + if v, ok := c.Get(CurrentUserKey); ok { + if u, ok := v.(*domain.User); ok { + return u + } + } + return nil +} + +func abortUnauthorized(c *gin.Context, msg string) { + reqID := GetRequestID(c) + body := dto.ErrorFromDomain( + &domain.ForbiddenError{Reason: msg}, + reqID, + ) + c.AbortWithStatusJSON(http.StatusUnauthorized, body) +} diff --git a/backend/internal/httpapi/middleware/requestid.go b/backend/internal/httpapi/middleware/requestid.go new file mode 100644 index 0000000..43c9011 --- /dev/null +++ b/backend/internal/httpapi/middleware/requestid.go @@ -0,0 +1,32 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +const ( + RequestIDKey = "request_id" + RequestIDHeader = "X-Request-Id" +) + +func RequestID() gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader(RequestIDHeader) + if id == "" { + id = uuid.NewString() + } + c.Set(RequestIDKey, id) + c.Writer.Header().Set(RequestIDHeader, id) + c.Next() + } +} + +func GetRequestID(c *gin.Context) string { + if v, ok := c.Get(RequestIDKey); ok { + if s, ok := v.(string); ok { + return s + } + } + return "" +} diff --git a/backend/internal/httpapi/router.go b/backend/internal/httpapi/router.go new file mode 100644 index 0000000..48a78a7 --- /dev/null +++ b/backend/internal/httpapi/router.go @@ -0,0 +1,45 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/handler" + "high-loud-apps-labs/internal/httpapi/middleware" +) + +type Handlers struct { + Health *handler.HealthHandler + User *handler.UserHandler + Chat *handler.ChatHandler + Message *handler.MessageHandler +} + +func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine { + gin.EnableJsonDecoderDisallowUnknownFields() + + r := gin.New() + r.Use(gin.Logger()) + r.Use(gin.Recovery()) + r.Use(middleware.RequestID()) + + r.GET("/health/live", h.Health.Live) + r.GET("/health/ready", h.Health.Ready) + + api := r.Group("/api/v1") + { + api.POST("/users", h.User.Create) + } + + protected := api.Group("") + protected.Use(auth) + { + protected.GET("/users/me", h.User.Current) + protected.POST("/chats", h.Chat.Create) + protected.GET("/chats", h.Chat.List) + protected.GET("/chats/:chat_id", h.Chat.Get) + protected.POST("/chats/:chat_id/messages", h.Message.Create) + protected.GET("/chats/:chat_id/messages", h.Message.List) + } + + return r +} diff --git a/backend/internal/service/chat.go b/backend/internal/service/chat.go new file mode 100644 index 0000000..caa8dce --- /dev/null +++ b/backend/internal/service/chat.go @@ -0,0 +1,95 @@ +package service + +import ( + "context" + "errors" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" +) + +type ChatService struct { + chats domain.ChatRepository + users domain.UserRepository +} + +func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService { + return &ChatService{chats: chats, users: users} +} + +func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return nil, &domain.ValidationError{ + Field: "title", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(title) > 100 { + return nil, &domain.ValidationError{ + Field: "title", + Message: "не более 100 символов", + } + } + + seen := make(map[string]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "дубликаты запрещены", + } + } + seen[id] = struct{}{} + } + + if _, ok := seen[creatorID]; !ok { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "создатель должен входить в список участников", + } + } + + for _, id := range memberIDs { + if _, err := s.users.GetByID(ctx, id); err != nil { + if errors.Is(err, domain.ErrNotFound) { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "неизвестный участник " + id, + } + } + return nil, err + } + } + + c := &domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), + CreatedAt: time.Now().UTC(), + } + if err := s.chats.Create(ctx, c); err != nil { + return nil, err + } + return c, nil +} + +func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) { + c, err := s.chats.GetByID(ctx, chatID) + if err != nil { + return nil, err + } + for _, m := range c.MemberIDs { + if m == userID { + return c, nil + } + } + return nil, &domain.NotFoundError{Entity: "chat", ID: chatID} +} + +func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { + return s.chats.ListByMember(ctx, userID, limit, cursor) +} diff --git a/backend/internal/service/message.go b/backend/internal/service/message.go new file mode 100644 index 0000000..1814d96 --- /dev/null +++ b/backend/internal/service/message.go @@ -0,0 +1,72 @@ +package service + +import ( + "context" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" +) + +type MessageService struct { + messages domain.MessageRepository + chats domain.ChatRepository +} + +func NewMessageService(messages domain.MessageRepository, chats domain.ChatRepository) *MessageService { + return &MessageService{messages: messages, chats: chats} +} + +func (s *MessageService) Create(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) { + if strings.TrimSpace(text) == "" { + return nil, &domain.ValidationError{ + Field: "text", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(text) > 4000 { + return nil, &domain.ValidationError{ + Field: "text", + Message: "не более 4000 символов", + } + } + + if err := s.ensureMember(ctx, senderID, chatID); err != nil { + return nil, err + } + + m := &domain.Message{ + ID: uuid.NewString(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: time.Now().UTC(), + } + if err := s.messages.Create(ctx, m); err != nil { + return nil, err + } + return m, nil +} + +func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + if err := s.ensureMember(ctx, userID, chatID); err != nil { + return nil, nil, err + } + return s.messages.ListByChat(ctx, chatID, limit, cursor) +} + +func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error { + c, err := s.chats.GetByID(ctx, chatID) + if err != nil { + return err + } + for _, m := range c.MemberIDs { + if m == userID { + return nil + } + } + return &domain.NotFoundError{Entity: "chat", ID: chatID} +} diff --git a/backend/internal/service/user.go b/backend/internal/service/user.go new file mode 100644 index 0000000..2fa8a87 --- /dev/null +++ b/backend/internal/service/user.go @@ -0,0 +1,76 @@ +package service + +import ( + "context" + "errors" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type UserService struct { + users domain.UserRepository +} + +func NewUserService(users domain.UserRepository) *UserService { + return &UserService{users: users} +} + +func (s *UserService) Create(ctx context.Context, username, displayName string) (*domain.User, error) { + if !usernamePattern.MatchString(username) { + return nil, &domain.ValidationError{ + Field: "username", + Message: "должен соответствовать ^[a-z0-9_]{3,32}$", + } + } + if strings.TrimSpace(displayName) == "" { + return nil, &domain.ValidationError{ + Field: "display_name", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(displayName) > 100 { + return nil, &domain.ValidationError{ + Field: "display_name", + Message: "не более 100 символов", + } + } + + _, err := s.users.GetByUsername(ctx, username) + if err == nil { + return nil, &domain.AlreadyExistsError{ + Entity: "user", + Field: "username", + Value: username, + } + } + if !errors.Is(err, domain.ErrNotFound) { + return nil, err + } + + u := &domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + if err := s.users.Create(ctx, u); err != nil { + return nil, err + } + return u, nil +} + +func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) { + return s.users.GetByID(ctx, id) +} + +func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) { + return s.users.GetByUsername(ctx, username) +} diff --git a/backend/internal/storage/memory/chat.go b/backend/internal/storage/memory/chat.go new file mode 100644 index 0000000..a2e18d0 --- /dev/null +++ b/backend/internal/storage/memory/chat.go @@ -0,0 +1,102 @@ +package memory + +import ( + "context" + "slices" + + "high-loud-apps-labs/internal/domain" +) + +func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + stored := *chat + stored.MemberIDs = append([]string(nil), chat.MemberIDs...) + r.chats[chat.ID] = &stored + return nil +} + +func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + c, ok := r.chats[id] + if !ok { + return nil, &domain.NotFoundError{Entity: "chat", ID: id} + } + copy := *c + copy.MemberIDs = append([]string(nil), c.MemberIDs...) + return ©, nil +} + +func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + scope := "chats:" + userID + + all := make([]domain.Chat, 0) + for _, c := range r.chats { + for _, m := range c.MemberIDs { + if m == userID { + copy := *c + copy.MemberIDs = append([]string(nil), c.MemberIDs...) + all = append(all, copy) + break + } + } + } + + slices.SortFunc(all, func(a, b domain.Chat) int { + if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) { + return -1 + } + if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) { + return 1 + } + return 0 + }) + + start := 0 + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + start = len(all) + for i, c := range all { + if lessThan(t, id, c.CreatedAt, c.ID) { + start = i + break + } + } + } + + if start >= len(all) { + return []domain.Chat{}, nil, nil + } + end := start + limit + if end > len(all) { + end = len(all) + } + page := all[start:end] + + var next *string + if end < len(all) { + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + + return page, next, nil +} diff --git a/backend/internal/storage/memory/cursor.go b/backend/internal/storage/memory/cursor.go new file mode 100644 index 0000000..ef0ebac --- /dev/null +++ b/backend/internal/storage/memory/cursor.go @@ -0,0 +1,47 @@ +package memory + +import ( + "encoding/base64" + "strings" + "time" + + "high-loud-apps-labs/internal/domain" +) + +func encodeCursor(scope string, createdAt time.Time, id string) string { + raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(cursor, expectedScope string) (time.Time, string, error) { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return time.Time{}, "", badCursor() + } + parts := strings.SplitN(string(data), "|", 3) + if len(parts) != 3 { + return time.Time{}, "", badCursor() + } + if parts[0] != expectedScope { + return time.Time{}, "", badCursor() + } + t, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return time.Time{}, "", badCursor() + } + return t, parts[2], nil +} + +func badCursor() error { + return &domain.ValidationError{ + Field: "cursor", + Message: "некорректный формат", + } +} + +func lessThan(aTime time.Time, aID string, bTime time.Time, bID string) bool { + if aTime.Equal(bTime) { + return aID < bID + } + return aTime.Before(bTime) +} diff --git a/backend/internal/storage/memory/message.go b/backend/internal/storage/memory/message.go new file mode 100644 index 0000000..463b757 --- /dev/null +++ b/backend/internal/storage/memory/message.go @@ -0,0 +1,93 @@ +package memory + +import ( + "context" + "slices" + "time" + + "high-loud-apps-labs/internal/domain" +) + +func (r *MessageRepo) Create(ctx context.Context, message *domain.Message) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + stored := *message + r.messages[message.ChatID] = append(r.messages[message.ChatID], stored) + return nil +} + +func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + scope := "messages:" + chatID + + var ( + afterTime time.Time + afterID string + hasCursor bool + ) + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + afterTime = t + afterID = id + hasCursor = true + } + + src := r.messages[chatID] + if len(src) == 0 { + return []domain.Message{}, nil, nil + } + + all := make([]domain.Message, len(src)) + copy(all, src) + + slices.SortFunc(all, func(a, b domain.Message) int { + if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) { + return -1 + } + if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) { + return 1 + } + return 0 + }) + + start := 0 + if hasCursor { + start = len(all) + for i, m := range all { + if lessThan(afterTime, afterID, m.CreatedAt, m.ID) { + start = i + break + } + } + } + + if start >= len(all) { + return []domain.Message{}, nil, nil + } + end := start + limit + if end > len(all) { + end = len(all) + } + page := all[start:end] + + var next *string + if end < len(all) { + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + + return page, next, nil +} diff --git a/backend/internal/storage/memory/storage.go b/backend/internal/storage/memory/storage.go new file mode 100644 index 0000000..5b96773 --- /dev/null +++ b/backend/internal/storage/memory/storage.go @@ -0,0 +1,34 @@ +package memory + +import ( + "sync" + + "high-loud-apps-labs/internal/domain" +) + +type Storage struct { + mu sync.RWMutex + users map[string]*domain.User + chats map[string]*domain.Chat + messages map[string][]domain.Message +} + +func New() *Storage { + return &Storage{ + users: make(map[string]*domain.User), + chats: make(map[string]*domain.Chat), + messages: make(map[string][]domain.Message), + } +} + +func (s *Storage) Users() *UserRepo { return &UserRepo{s} } +func (s *Storage) Chats() *ChatRepo { return &ChatRepo{s} } +func (s *Storage) Messages() *MessageRepo { return &MessageRepo{s} } + +type UserRepo struct{ *Storage } +type ChatRepo struct{ *Storage } +type MessageRepo struct{ *Storage } + +var _ domain.UserRepository = (*UserRepo)(nil) +var _ domain.ChatRepository = (*ChatRepo)(nil) +var _ domain.MessageRepository = (*MessageRepo)(nil) diff --git a/backend/internal/storage/memory/user.go b/backend/internal/storage/memory/user.go new file mode 100644 index 0000000..713162b --- /dev/null +++ b/backend/internal/storage/memory/user.go @@ -0,0 +1,59 @@ +package memory + +import ( + "context" + + "high-loud-apps-labs/internal/domain" +) + +func (r *UserRepo) Create(ctx context.Context, user *domain.User) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + for _, u := range r.users { + if u.Username == user.Username { + return &domain.AlreadyExistsError{ + Entity: "user", + Field: "username", + Value: user.Username, + } + } + } + stored := *user + r.users[user.ID] = &stored + return nil +} + +func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + u, ok := r.users[id] + if !ok { + return nil, &domain.NotFoundError{Entity: "user", ID: id} + } + copy := *u + return ©, nil +} + +func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + for _, u := range r.users { + if u.Username == username { + copy := *u + return ©, nil + } + } + return nil, &domain.NotFoundError{Entity: "user", ID: username} +} diff --git a/student-tests/README.md b/student-tests/README.md new file mode 100644 index 0000000..0781b12 --- /dev/null +++ b/student-tests/README.md @@ -0,0 +1,7 @@ +# Собственные тесты + +Проверки негативных сценариев и конкурентной работы, отдельно от публичных `tests/`. + +Запуск (сервер уже должен быть поднят на `localhost:8080`): + + python students-tests/run_all.py --base-url http://localhost:8080 diff --git a/student-tests/run_all.py b/student-tests/run_all.py new file mode 100644 index 0000000..e089770 --- /dev/null +++ b/student-tests/run_all.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent + + +def main(): + args = sys.argv[1:] + for script in ('test_cases.py', 'test_concurrency.py'): + print(f'=== {script} ===') + result = subprocess.run([sys.executable, str(ROOT / script), *args]) + if result.returncode != 0: + sys.exit(result.returncode) + print('=== Все тесты прошли ===') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/student-tests/test_cases.py b/student-tests/test_cases.py new file mode 100644 index 0000000..e939d66 --- /dev/null +++ b/student-tests/test_cases.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты негативных сценариев') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- некорректный JSON --- + malformed = b'{"username":"alice","display_name":"A"' + c.call('POST', '/api/v1/users', 400, raw=malformed, + headers={'Content-Type': 'application/json'}) + + # --- лишнее поле --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], + 'display_name': 'X', 'extra': 'мусор'}) + + # --- неверный тип поля --- + c.call('POST', '/api/v1/users', 400, + body={'username': 123, 'display_name': 'X'}) + + # --- пустой display_name --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ''}) + + # --- display_name только из пробелов --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ' '}) + + # --- заглавные в username --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'UPPERCASE', 'display_name': 'X'}) + + # --- дубликат username --- + c.call('POST', '/api/v1/users', 409, body=alice['registration']) + + # --- пустое сообщение --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ''}) + + # --- сообщение только из пробелов --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '}) + + # --- чужой чат --- + c.call('GET', path, 404, actor=eve) + c.call('GET', path + '/messages', 404, actor=eve) + c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'чужое'}) + + # --- чат без создателя в member_ids --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Без меня', 'member_ids': [bob['id']]}) + + # --- чат с неизвестным участником --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'С фантомом', + 'member_ids': [alice['id'], '00000000-0000-4000-8000-000000000000']}) + + # --- чат с дубликатами --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Дубликаты', 'member_ids': [alice['id'], alice['id']]}) + + # --- обход нескольких страниц --- + for i in range(5): + c.message(alice, chat, 'page-test-%d' % i) + + seen = [] + cursor = None + for _ in range(20): + query = path + '/messages?limit=2' + if cursor: + from urllib.parse import quote + query += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', query, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + check(len(seen) == len(set(seen)), 'пагинация вернула дубликаты') + check(len(seen) >= 5, 'пагинация потеряла сообщения') + + # --- cursor от другого чата --- + other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, + body={'title': 'Другой чат', + 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + other_path = '/api/v1/chats/' + other_chat['id'] + c.message(alice, other_chat, 'other-1') + c.message(alice, other_chat, 'other-2') + + other_page = c.call('GET', other_path + '/messages?limit=1', actor=alice, + schema='MessagePage')['json'] + other_cursor = other_page['next_cursor'] + check(other_cursor is not None, 'ожидался cursor от другого чата, но получен null') + + from urllib.parse import quote + c.call('GET', path + '/messages?limit=2&cursor=' + quote(other_cursor, safe=''), + 400, actor=alice) + + print('PASS: негативные сценарии прошли') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_concurrency.py b/student-tests/test_concurrency.py new file mode 100644 index 0000000..9dee97a --- /dev/null +++ b/student-tests/test_concurrency.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +import threading +import uuid +from concurrent.futures import ThreadPoolExecutor + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты конкурентности') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- 100 сообщений от 10 потоков --- + workers = 10 + per_worker = 10 + expected_total = workers * per_worker + barrier = threading.Barrier(workers) + + def writer(worker_id): + local = Client(args.base_url, args.ca_file, timeout=10) + barrier.wait() + for i in range(per_worker): + local.message(alice, chat, 'c-%d-%d' % (worker_id, i)) + + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(writer, range(workers))) + + seen = [] + cursor = None + while True: + q = path + '/messages?limit=100' + if cursor: + from urllib.parse import quote + q += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', q, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + + check(len(seen) == len(set(seen)), 'после параллельной записи обнаружены дубликаты id сообщений') + check(len(seen) == expected_total, + 'ожидалось ровно %d сообщений, получено %d' % (expected_total, len(seen))) + + # --- гонка за username --- + username = 'race_' + uuid.uuid4().hex[:8] + barrier2 = threading.Barrier(workers) + + def register(_): + local = Client(args.base_url, args.ca_file, timeout=10) + barrier2.wait() + try: + local.call('POST', '/api/v1/users', 201, + body={'username': username, 'display_name': 'Race'}) + return 'ok' + except Failure: + return 'conflict' + + with ThreadPoolExecutor(max_workers=workers) as pool: + results = list(pool.map(register, range(workers))) + + ok_count = results.count('ok') + conflict_count = results.count('conflict') + check(ok_count == 1, 'ожидалась ровно одна успешная регистрация, получено %d' % ok_count) + check(conflict_count == workers - 1, + 'ожидалось %d конфликтов, получено %d' % (workers - 1, conflict_count)) + + print('PASS: конкурентность (100 сообщений, 1 победитель в гонке за username)') + + +if __name__ == '__main__': + run(main) \ No newline at end of file