returned lab1
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
.github
|
||||||
|
.gitignore
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
@@ -17,4 +18,12 @@ backups
|
|||||||
__pycache__
|
__pycache__
|
||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
|
examples
|
||||||
|
scripts
|
||||||
|
tests
|
||||||
|
*.md
|
||||||
|
Dockerfile*
|
||||||
|
Makefile
|
||||||
|
requirements-dev.txt
|
||||||
|
lab.json
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
|
||||||
|
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY cmd ./cmd
|
||||||
|
COPY contracts ./contracts
|
||||||
|
COPY dto ./dto
|
||||||
|
COPY internal ./internal
|
||||||
|
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||||
|
-trimpath \
|
||||||
|
-ldflags="-s -w" \
|
||||||
|
-o /out/messenger ./cmd
|
||||||
|
|
||||||
|
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616
|
||||||
|
|
||||||
|
RUN addgroup -S messenger \
|
||||||
|
&& adduser -S -D -H -u 10001 -G messenger messenger
|
||||||
|
|
||||||
|
COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
|
||||||
|
|
||||||
|
ENV PORT=8080
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
USER messenger:messenger
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
|
||||||
|
CMD wget -q -O /dev/null "http://127.0.0.1:${PORT}/health/ready" || exit 1
|
||||||
|
|
||||||
|
STOPSIGNAL SIGTERM
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
|
||||||
|
GO ?= go
|
||||||
|
PORT ?= 8080
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
|
IMAGE ?= mtusi-messenger:lab1
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence
|
.PHONY: help run docker-build docker-run check validate test test-own test-all load test-persistence
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||||
@@ -18,6 +21,11 @@ validate:
|
|||||||
test:
|
test:
|
||||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
test-own:
|
||||||
|
$(GO) test -race ./...
|
||||||
|
|
||||||
|
test-all: check validate test-own
|
||||||
|
|
||||||
load:
|
load:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
|||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
||||||
|
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||||
|
)
|
||||||
|
|
||||||
|
const shutdownTimeout = 8 * time.Second
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
port := os.Getenv("PORT")
|
||||||
|
if port == "" {
|
||||||
|
port = "8080"
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := repository.NewMemory()
|
||||||
|
useCase := chatusecase.New(repo)
|
||||||
|
handler := chat.NewChat(useCase)
|
||||||
|
e := handler.Router()
|
||||||
|
e.Server.ReadHeaderTimeout = 5 * time.Second
|
||||||
|
e.Server.ReadTimeout = 10 * time.Second
|
||||||
|
e.Server.WriteTimeout = 15 * time.Second
|
||||||
|
e.Server.IdleTimeout = 60 * time.Second
|
||||||
|
|
||||||
|
serverErrors := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
log.Printf("HTTP server is listening on :%s", port)
|
||||||
|
serverErrors <- e.Start(":" + port)
|
||||||
|
}()
|
||||||
|
|
||||||
|
stop := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
select {
|
||||||
|
case sig := <-stop:
|
||||||
|
log.Printf("received %s, shutting down", sig)
|
||||||
|
case err := <-serverErrors:
|
||||||
|
if !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
log.Fatalf("HTTP server failed: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := e.Shutdown(ctx); err != nil {
|
||||||
|
log.Printf("graceful shutdown failed: %v", err)
|
||||||
|
if closeErr := e.Close(); closeErr != nil {
|
||||||
|
log.Printf("forced shutdown failed: %v", closeErr)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("shutdown complete")
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package contracts
|
||||||
|
|
||||||
|
import _ "embed"
|
||||||
|
|
||||||
|
// OpenAPI is embedded so Swagger UI works from a compiled binary and does not
|
||||||
|
// depend on the process working directory.
|
||||||
|
//
|
||||||
|
//go:embed openapi.json
|
||||||
|
var OpenAPI []byte
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type CreateChatRequest struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateChatResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type CreateMessageRequest struct {
|
||||||
|
ChatID string `json:"-"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateMessageResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
SenderID string `json:"sender_id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type CreateUserRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateUserResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type CurrentUserRequest struct{}
|
||||||
|
|
||||||
|
type CurrentUserResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
type ErrorResponse struct {
|
||||||
|
Error ErrorDetails `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ErrorDetails struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type GetChatRequest struct {
|
||||||
|
ChatID string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetChatResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type ListChatsRequest struct {
|
||||||
|
Limit int `json:"-"`
|
||||||
|
Cursor string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListChatsResponse struct {
|
||||||
|
Items []ListChatsItem `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListChatsItem struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type ListMessagesRequest struct {
|
||||||
|
ChatID string `json:"-"`
|
||||||
|
Limit int `json:"-"`
|
||||||
|
Cursor string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListMessagesResponse struct {
|
||||||
|
Items []ListMessagesItem `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListMessagesItem struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
SenderID string `json:"sender_id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
type LivenessRequest struct{}
|
||||||
|
|
||||||
|
type LivenessResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
type ReadinessRequest struct{}
|
||||||
|
|
||||||
|
type ReadinessResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
module gitflic.ru/akselbant/mtusi2026lab1-fork
|
||||||
|
|
||||||
|
go 1.26.4
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/labstack/echo/v4 v4.13.4
|
||||||
|
github.com/swaggest/swgui v1.8.9
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/labstack/gommon v0.4.2 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
|
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||||
|
github.com/vearutop/statigz v1.4.0 // indirect
|
||||||
|
golang.org/x/crypto v0.38.0 // indirect
|
||||||
|
golang.org/x/net v0.40.0 // indirect
|
||||||
|
golang.org/x/sys v0.33.0 // indirect
|
||||||
|
golang.org/x/text v0.25.0 // indirect
|
||||||
|
golang.org/x/time v0.11.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
|
||||||
|
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||||
|
github.com/bool64/dev v0.2.45 h1:3nLKhAS/6Oklk3Mt2lHYSN/Cb4tdAD77KLwzeP+6eYE=
|
||||||
|
github.com/bool64/dev v0.2.45/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
|
||||||
|
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/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/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
||||||
|
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
|
||||||
|
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||||
|
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||||
|
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||||
|
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
|
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/swaggest/swgui v1.8.9 h1:cxAgIwouPpZPlvX68jY5fpwarzLbkc8/IL6DMj+H460=
|
||||||
|
github.com/swaggest/swgui v1.8.9/go.mod h1:eTJfgwudbyw9xMwqO26vs82ei2u6//JnUAofx2vGB3M=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
|
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||||
|
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||||
|
github.com/vearutop/statigz v1.4.0 h1:RQL0KG3j/uyA/PFpHeZ/L6l2ta920/MxlOAIGEOuwmU=
|
||||||
|
github.com/vearutop/statigz v1.4.0/go.mod h1:LYTolBLiz9oJISwiVKnOQoIwhO1LWX1A7OECawGS8XE=
|
||||||
|
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
|
||||||
|
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
|
||||||
|
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||||
|
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||||
|
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
|
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
|
||||||
|
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
|
||||||
|
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||||
|
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) authorizedChat(c echo.Context, requestedChat domain.Chat) (domain.Chat, bool, error) {
|
||||||
|
chat, err := h.useCase.GetChat(c.Request().Context(), authenticatedUser(c).ID, requestedChat)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, false, h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
return chat, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) cursorPosition(raw string, present bool, scope, owner string) (*domain.Position, error) {
|
||||||
|
if !present {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if raw == "" {
|
||||||
|
return nil, errors.New("empty cursor")
|
||||||
|
}
|
||||||
|
createdAt, id, err := h.cursor.decode(raw, scope, owner)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &domain.Position{CreatedAt: createdAt, ID: id}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) createChat(c echo.Context) error {
|
||||||
|
var request dto.CreateChatRequest
|
||||||
|
if err := decodeJSON(c, &request); err != nil {
|
||||||
|
return h.jsonError(c, err)
|
||||||
|
}
|
||||||
|
callerID := authenticatedUser(c).ID
|
||||||
|
chat, err := h.useCase.CreateChat(c.Request().Context(), callerID, createChatRequestToDomain(request))
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusCreated, createChatResponseFromDomain(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
|
||||||
|
return domain.Chat{Title: request.Title, MemberIDs: request.MemberIDs}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
|
||||||
|
return dto.CreateChatResponse{
|
||||||
|
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) createMessage(c echo.Context) error {
|
||||||
|
request := dto.CreateMessageRequest{ChatID: c.Param("chat_id")}
|
||||||
|
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := decodeJSON(c, &request); err != nil {
|
||||||
|
return h.jsonError(c, err)
|
||||||
|
}
|
||||||
|
request.ChatID = chat.ID
|
||||||
|
|
||||||
|
message, err := h.useCase.CreateMessage(c.Request().Context(), authenticatedUser(c).ID, createMessageRequestToDomain(request))
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusCreated, createMessageResponseFromDomain(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
|
||||||
|
return domain.Message{ChatID: request.ChatID, Text: request.Text}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
|
||||||
|
return dto.CreateMessageResponse{
|
||||||
|
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||||
|
Text: message.Text, CreatedAt: message.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) createUser(c echo.Context) error {
|
||||||
|
var request dto.CreateUserRequest
|
||||||
|
if err := decodeJSON(c, &request); err != nil {
|
||||||
|
return h.jsonError(c, err)
|
||||||
|
}
|
||||||
|
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request))
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusCreated, createUserResponseFromDomain(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
|
||||||
|
return domain.User{Username: request.Username, DisplayName: request.DisplayName}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
|
||||||
|
return dto.CreateUserResponse{
|
||||||
|
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) currentUser(c echo.Context) error {
|
||||||
|
user := authenticatedUser(c)
|
||||||
|
return c.JSON(http.StatusOK, currentUserResponseFromDomain(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
|
||||||
|
return dto.CurrentUserResponse{
|
||||||
|
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type cursorPayload struct {
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type cursorCodec struct {
|
||||||
|
secret [32]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCursorCodec() cursorCodec {
|
||||||
|
var codec cursorCodec
|
||||||
|
if _, err := rand.Read(codec.secret[:]); err != nil {
|
||||||
|
panic("cannot initialize cursor signing key: " + err.Error())
|
||||||
|
}
|
||||||
|
return codec
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
|
||||||
|
payload, err := json.Marshal(cursorPayload{
|
||||||
|
Scope: scope,
|
||||||
|
Owner: owner,
|
||||||
|
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
|
||||||
|
ID: id,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
panic("cannot encode cursor: " + err.Error())
|
||||||
|
}
|
||||||
|
signature := c.sign(payload)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
|
||||||
|
parts := strings.Split(raw, ".")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return time.Time{}, "", errors.New("malformed cursor")
|
||||||
|
}
|
||||||
|
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, "", errors.New("malformed cursor")
|
||||||
|
}
|
||||||
|
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
|
||||||
|
return time.Time{}, "", errors.New("invalid cursor signature")
|
||||||
|
}
|
||||||
|
var value cursorPayload
|
||||||
|
if err := json.Unmarshal(payload, &value); err != nil {
|
||||||
|
return time.Time{}, "", errors.New("malformed cursor payload")
|
||||||
|
}
|
||||||
|
if value.Scope != scope || value.Owner != owner {
|
||||||
|
return time.Time{}, "", errors.New("cursor belongs to another resource")
|
||||||
|
}
|
||||||
|
parsedID, err := uuid.Parse(value.ID)
|
||||||
|
if err != nil || parsedID.String() != value.ID {
|
||||||
|
return time.Time{}, "", errors.New("malformed cursor id")
|
||||||
|
}
|
||||||
|
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, "", errors.New("malformed cursor timestamp")
|
||||||
|
}
|
||||||
|
return createdAt, value.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cursorCodec) sign(payload []byte) []byte {
|
||||||
|
mac := hmac.New(sha256.New, c.secret[:])
|
||||||
|
_, _ = mac.Write(payload)
|
||||||
|
return mac.Sum(nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) invalid(c echo.Context, message string) error {
|
||||||
|
return h.writeError(c, http.StatusBadRequest, "invalid_request", message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) jsonError(c echo.Context, err error) error {
|
||||||
|
if errors.Is(err, errUnsupportedMediaType) {
|
||||||
|
return h.writeError(c, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type должен быть application/json")
|
||||||
|
}
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
return h.writeError(c, http.StatusRequestEntityTooLarge, "payload_too_large", "Тело запроса слишком большое")
|
||||||
|
}
|
||||||
|
return h.invalid(c, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) useCaseError(c echo.Context, err error) error {
|
||||||
|
applicationError, ok := domain.AsApplicationError(err)
|
||||||
|
if !ok {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
status := http.StatusInternalServerError
|
||||||
|
switch applicationError.Code {
|
||||||
|
case domain.ErrorInvalid:
|
||||||
|
status = http.StatusBadRequest
|
||||||
|
case domain.ErrorUnauthorized:
|
||||||
|
status = http.StatusUnauthorized
|
||||||
|
case domain.ErrorNotFound:
|
||||||
|
status = http.StatusNotFound
|
||||||
|
case domain.ErrorConflict:
|
||||||
|
status = http.StatusConflict
|
||||||
|
}
|
||||||
|
return h.writeError(c, status, string(applicationError.Code), applicationError.Message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) writeError(c echo.Context, status int, code, message string) error {
|
||||||
|
return c.JSON(status, dto.ErrorResponse{Error: dto.ErrorDetails{
|
||||||
|
Code: code,
|
||||||
|
Message: message,
|
||||||
|
RequestID: requestID(c),
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) httpErrorHandler(err error, c echo.Context) {
|
||||||
|
if c.Response().Committed {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status := http.StatusInternalServerError
|
||||||
|
code := "internal_error"
|
||||||
|
message := "Внутренняя ошибка сервера"
|
||||||
|
var httpError *echo.HTTPError
|
||||||
|
if errors.As(err, &httpError) {
|
||||||
|
status = httpError.Code
|
||||||
|
switch status {
|
||||||
|
case http.StatusNotFound:
|
||||||
|
code, message = "not_found", "Объект не найден"
|
||||||
|
case http.StatusMethodNotAllowed, http.StatusBadRequest:
|
||||||
|
code, message = "invalid_request", "Некорректный запрос"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = h.writeError(c, status, code, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestID(c echo.Context) string {
|
||||||
|
value, _ := c.Get(requestIDKey).(string)
|
||||||
|
if value == "" {
|
||||||
|
value = uuid.NewString()
|
||||||
|
c.Set(requestIDKey, value)
|
||||||
|
c.Response().Header().Set("X-Request-Id", value)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) getChat(c echo.Context) error {
|
||||||
|
request := dto.GetChatRequest{ChatID: c.Param("chat_id")}
|
||||||
|
chat, ok, err := h.authorizedChat(c, getChatRequestToDomain(request))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusOK, getChatResponseFromDomain(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
|
||||||
|
return domain.Chat{ID: request.ChatID}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
|
||||||
|
return dto.GetChatResponse{
|
||||||
|
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) listChats(c echo.Context) error {
|
||||||
|
limit, err := parseLimit(c)
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, err.Error())
|
||||||
|
}
|
||||||
|
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, "cursor должен быть указан один раз")
|
||||||
|
}
|
||||||
|
request := dto.ListChatsRequest{Limit: limit, Cursor: rawCursor}
|
||||||
|
userID := authenticatedUser(c).ID
|
||||||
|
position, err := h.cursorPosition(request.Cursor, cursorPresent, "chats", userID)
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, "Некорректный cursor")
|
||||||
|
}
|
||||||
|
|
||||||
|
page, err := h.useCase.ListChats(c.Request().Context(), userID, listChatsRequestToDomain(request, position))
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
var next *string
|
||||||
|
if page.HasMore {
|
||||||
|
last := page.Items[len(page.Items)-1]
|
||||||
|
encoded := h.cursor.encode("chats", userID, last.CreatedAt, last.ID)
|
||||||
|
next = &encoded
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusOK, listChatsResponseFromDomain(page, next))
|
||||||
|
}
|
||||||
|
|
||||||
|
func listChatsRequestToDomain(request dto.ListChatsRequest, position *domain.Position) domain.Pagination {
|
||||||
|
return domain.Pagination{After: position, Limit: request.Limit}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.ListChatsResponse {
|
||||||
|
items := make([]dto.ListChatsItem, 0, len(page.Items))
|
||||||
|
for _, chat := range page.Items {
|
||||||
|
items = append(items, dto.ListChatsItem{
|
||||||
|
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) listMessages(c echo.Context) error {
|
||||||
|
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
|
||||||
|
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
limit, err := parseLimit(c)
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, err.Error())
|
||||||
|
}
|
||||||
|
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, "cursor должен быть указан один раз")
|
||||||
|
}
|
||||||
|
request.ChatID = chat.ID
|
||||||
|
request.Limit = limit
|
||||||
|
request.Cursor = rawCursor
|
||||||
|
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
|
||||||
|
if err != nil {
|
||||||
|
return h.invalid(c, "Некорректный cursor")
|
||||||
|
}
|
||||||
|
|
||||||
|
page, err := h.useCase.ListMessages(
|
||||||
|
c.Request().Context(), authenticatedUser(c).ID,
|
||||||
|
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
var next *string
|
||||||
|
if page.HasMore {
|
||||||
|
last := page.Items[len(page.Items)-1]
|
||||||
|
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
|
||||||
|
next = &encoded
|
||||||
|
}
|
||||||
|
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
|
||||||
|
}
|
||||||
|
|
||||||
|
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
|
||||||
|
return domain.Chat{ID: request.ChatID}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
|
||||||
|
return domain.Pagination{After: position, Limit: request.Limit}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
|
||||||
|
items := make([]dto.ListMessagesItem, 0, len(page.Items))
|
||||||
|
for _, message := range page.Items {
|
||||||
|
items = append(items, dto.ListMessagesItem{
|
||||||
|
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||||
|
Text: message.Text, CreatedAt: message.CreatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) liveness(c echo.Context) error {
|
||||||
|
return c.JSON(http.StatusOK, dto.LivenessResponse{Status: "ok"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
requestIDKey = "request_id"
|
||||||
|
userKey = "current_user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
|
return func(c echo.Context) error {
|
||||||
|
requestID := uuid.NewString()
|
||||||
|
c.Set(requestIDKey, requestID)
|
||||||
|
c.Response().Header().Set("X-Request-Id", requestID)
|
||||||
|
return next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
|
return func(c echo.Context) error {
|
||||||
|
user, err := h.useCase.Authenticate(c.Request().Context(), c.Request().Header.Get("X-User-Id"))
|
||||||
|
if err != nil {
|
||||||
|
return h.useCaseError(c, err)
|
||||||
|
}
|
||||||
|
c.Set(userKey, user)
|
||||||
|
return next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func authenticatedUser(c echo.Context) domain.User {
|
||||||
|
return c.Get(userKey).(domain.User)
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Chat) readiness(c echo.Context) error {
|
||||||
|
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultLimit = 50
|
||||||
|
maxLimit = 100
|
||||||
|
maxJSONBody = 1 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
var errUnsupportedMediaType = errors.New("unsupported media type")
|
||||||
|
|
||||||
|
func decodeJSON(c echo.Context, target any) error {
|
||||||
|
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get(echo.HeaderContentType))
|
||||||
|
if err != nil || mediaType != echo.MIMEApplicationJSON {
|
||||||
|
return errUnsupportedMediaType
|
||||||
|
}
|
||||||
|
reader := http.MaxBytesReader(c.Response(), c.Request().Body, maxJSONBody)
|
||||||
|
decoder := json.NewDecoder(reader)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(target); err != nil {
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return errors.New("Некорректное JSON-тело")
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
err = decoder.Decode(&extra)
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !errors.Is(err, io.EOF) {
|
||||||
|
return errors.New("JSON-тело должно содержать ровно один объект")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseLimit(c echo.Context) (int, error) {
|
||||||
|
raw, present, err := oneQueryValue(c, "limit")
|
||||||
|
if err != nil {
|
||||||
|
return 0, errors.New("limit должен быть указан один раз")
|
||||||
|
}
|
||||||
|
if !present {
|
||||||
|
return defaultLimit, nil
|
||||||
|
}
|
||||||
|
limit, err := strconv.Atoi(raw)
|
||||||
|
if err != nil || limit < 1 || limit > maxLimit {
|
||||||
|
return 0, fmt.Errorf("limit должен быть целым числом от 1 до %d", maxLimit)
|
||||||
|
}
|
||||||
|
return limit, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func oneQueryValue(c echo.Context, name string) (string, bool, error) {
|
||||||
|
values, present := c.QueryParams()[name]
|
||||||
|
if !present {
|
||||||
|
return "", false, nil
|
||||||
|
}
|
||||||
|
if len(values) != 1 {
|
||||||
|
return "", true, errors.New("query parameter must occur once")
|
||||||
|
}
|
||||||
|
return values[0], true, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
"github.com/labstack/echo/v4/middleware"
|
||||||
|
"github.com/swaggest/swgui/v5emb"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Chat is the HTTP handler and depends only on the application boundary.
|
||||||
|
type Chat struct {
|
||||||
|
useCase UseCase
|
||||||
|
cursor cursorCodec
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChat(useCase UseCase) *Chat {
|
||||||
|
return &Chat{useCase: useCase, cursor: newCursorCodec()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) Router() *echo.Echo {
|
||||||
|
e := echo.New()
|
||||||
|
e.HideBanner = true
|
||||||
|
e.HidePort = true
|
||||||
|
e.HTTPErrorHandler = h.httpErrorHandler
|
||||||
|
e.Use(h.requestIDMiddleware)
|
||||||
|
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||||
|
HandleError: true,
|
||||||
|
LogLatency: true,
|
||||||
|
LogMethod: true,
|
||||||
|
LogRoutePath: true,
|
||||||
|
LogURIPath: true,
|
||||||
|
LogRequestID: true,
|
||||||
|
LogStatus: true,
|
||||||
|
LogResponseSize: true,
|
||||||
|
LogValuesFunc: func(_ echo.Context, values middleware.RequestLoggerValues) error {
|
||||||
|
path := values.RoutePath
|
||||||
|
if path == "" {
|
||||||
|
path = values.URIPath
|
||||||
|
}
|
||||||
|
log.Printf(
|
||||||
|
"request_id=%s method=%s path=%s status=%d response_bytes=%d latency=%s",
|
||||||
|
values.RequestID, values.Method, path, values.Status, values.ResponseSize, values.Latency,
|
||||||
|
)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
e.Use(middleware.Recover())
|
||||||
|
|
||||||
|
e.GET("/health/live", h.liveness)
|
||||||
|
e.GET("/health/ready", h.readiness)
|
||||||
|
swaggerUI := echo.WrapHandler(v5emb.New(
|
||||||
|
"MTUSI Messenger",
|
||||||
|
"/swagger/openapi.json",
|
||||||
|
"/swagger/",
|
||||||
|
))
|
||||||
|
e.GET("/swagger", h.swagger)
|
||||||
|
e.GET("/swagger/", swaggerUI)
|
||||||
|
e.GET("/swagger/openapi.json", h.swaggerSpec)
|
||||||
|
e.GET("/swagger/*", swaggerUI)
|
||||||
|
e.POST("/api/v1/users", h.createUser)
|
||||||
|
|
||||||
|
api := e.Group("/api/v1", h.authenticate)
|
||||||
|
api.GET("/users/me", h.currentUser)
|
||||||
|
api.POST("/chats", h.createChat)
|
||||||
|
api.GET("/chats", h.listChats)
|
||||||
|
api.GET("/chats/:chat_id", h.getChat)
|
||||||
|
api.POST("/chats/:chat_id/messages", h.createMessage)
|
||||||
|
api.GET("/chats/:chat_id/messages", h.listMessages)
|
||||||
|
|
||||||
|
return e
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
package chat_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
||||||
|
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testAPI struct {
|
||||||
|
server *httptest.Server
|
||||||
|
}
|
||||||
|
|
||||||
|
type userResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type chatResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type messageResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type messagePageResponse struct {
|
||||||
|
Items []messageResponse `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type errorResponse struct {
|
||||||
|
Error struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
} `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestAPI(t *testing.T) *testAPI {
|
||||||
|
t.Helper()
|
||||||
|
useCase := chatusecase.New(repository.NewMemory())
|
||||||
|
server := httptest.NewServer(chathandler.NewChat(useCase).Router())
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return &testAPI{server: server}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actorID, body string, wantStatus int, target any) {
|
||||||
|
t.Helper()
|
||||||
|
request, err := http.NewRequest(method, a.server.URL+path, bytes.NewBufferString(body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create request: %v", err)
|
||||||
|
}
|
||||||
|
if body != "" {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if actorID != "" {
|
||||||
|
request.Header.Set("X-User-Id", actorID)
|
||||||
|
}
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s %s: %v", method, path, err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
responseBody, err := io.ReadAll(response.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read response: %v", err)
|
||||||
|
}
|
||||||
|
if response.StatusCode != wantStatus {
|
||||||
|
t.Fatalf("%s %s: status=%d, want=%d, body=%s", method, path, response.StatusCode, wantStatus, responseBody)
|
||||||
|
}
|
||||||
|
if response.Header.Get("X-Request-Id") == "" {
|
||||||
|
t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||||
|
}
|
||||||
|
if target != nil {
|
||||||
|
if err := json.Unmarshal(responseBody, target); err != nil {
|
||||||
|
t.Fatalf("decode response %q: %v", responseBody, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) createUser(t *testing.T, username string) userResponse {
|
||||||
|
t.Helper()
|
||||||
|
var user userResponse
|
||||||
|
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
|
||||||
|
fmt.Sprintf(`{"username":%q,"display_name":%q}`, username, username), http.StatusCreated, &user)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) requestError(t *testing.T, method, path, actorID, body string, wantStatus int, wantCode string) {
|
||||||
|
t.Helper()
|
||||||
|
var response errorResponse
|
||||||
|
a.request(t, http.DefaultClient, method, path, actorID, body, wantStatus, &response)
|
||||||
|
if response.Error.Code != wantCode {
|
||||||
|
t.Fatalf("%s %s: error code=%q, want=%q", method, path, response.Error.Code, wantCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) createChat(t *testing.T, ownerID string, memberIDs []string) chatResponse {
|
||||||
|
t.Helper()
|
||||||
|
body, err := json.Marshal(map[string]any{"title": "test chat", "member_ids": memberIDs})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("encode chat: %v", err)
|
||||||
|
}
|
||||||
|
var chat chatResponse
|
||||||
|
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/chats", ownerID, string(body), http.StatusCreated, &chat)
|
||||||
|
return chat
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) createMessage(t *testing.T, client *http.Client, actorID, chatID, text string) messageResponse {
|
||||||
|
t.Helper()
|
||||||
|
body, err := json.Marshal(map[string]string{"text": text})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("encode message: %v", err)
|
||||||
|
}
|
||||||
|
var message messageResponse
|
||||||
|
a.request(t, client, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, string(body), http.StatusCreated, &message)
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectsMalformedJSON(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||||
|
`{"username":`, http.StatusBadRequest, "invalid_request")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHidesForeignChat(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
owner := api.createUser(t, "owner_user")
|
||||||
|
outsider := api.createUser(t, "outsider_user")
|
||||||
|
chat := api.createChat(t, owner.ID, []string{owner.ID})
|
||||||
|
api.requestError(t, http.MethodGet, "/api/v1/chats/"+chat.ID, outsider.ID,
|
||||||
|
"", http.StatusNotFound, "not_found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectsEmptyMessage(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
user := api.createUser(t, "empty_message_user")
|
||||||
|
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||||
|
api.requestError(t, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", user.ID,
|
||||||
|
`{"text":" "}`, http.StatusBadRequest, "invalid_request")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectsDuplicateUsername(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.createUser(t, "duplicate_user")
|
||||||
|
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||||
|
`{"username":"duplicate_user","display_name":"Duplicate"}`, http.StatusConflict, "conflict")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
user := api.createUser(t, "pagination_user")
|
||||||
|
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||||
|
for index := 0; index < 7; index++ {
|
||||||
|
api.createMessage(t, http.DefaultClient, user.ID, chat.ID, fmt.Sprintf("message-%d", index))
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := make(map[string]struct{})
|
||||||
|
cursor := ""
|
||||||
|
pageSizes := make([]int, 0, 4)
|
||||||
|
for {
|
||||||
|
path := "/api/v1/chats/" + chat.ID + "/messages?limit=2"
|
||||||
|
if cursor != "" {
|
||||||
|
path += "&cursor=" + url.QueryEscape(cursor)
|
||||||
|
}
|
||||||
|
var page messagePageResponse
|
||||||
|
api.request(t, http.DefaultClient, http.MethodGet, path, user.ID, "", http.StatusOK, &page)
|
||||||
|
pageSizes = append(pageSizes, len(page.Items))
|
||||||
|
for _, message := range page.Items {
|
||||||
|
if _, duplicate := seen[message.ID]; duplicate {
|
||||||
|
t.Fatalf("message %s appeared on multiple pages", message.ID)
|
||||||
|
}
|
||||||
|
seen[message.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
if page.NextCursor == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
cursor = *page.NextCursor
|
||||||
|
}
|
||||||
|
if len(seen) != 7 {
|
||||||
|
t.Fatalf("received %d unique messages, want 7", len(seen))
|
||||||
|
}
|
||||||
|
wantPageSizes := []int{2, 2, 2, 1}
|
||||||
|
if fmt.Sprint(pageSizes) != fmt.Sprint(wantPageSizes) {
|
||||||
|
t.Fatalf("page sizes=%v, want=%v", pageSizes, wantPageSizes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConcurrentMessagesAreUnique(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
|
||||||
|
users := make([]userResponse, 10)
|
||||||
|
memberIDs := make([]string, 10)
|
||||||
|
for index := range users {
|
||||||
|
users[index] = api.createUser(t, fmt.Sprintf("parallel_user_%02d", index))
|
||||||
|
memberIDs[index] = users[index].ID
|
||||||
|
}
|
||||||
|
chat := api.createChat(t, users[0].ID, memberIDs)
|
||||||
|
|
||||||
|
start := make(chan struct{})
|
||||||
|
errors := make(chan error, 10)
|
||||||
|
var waitGroup sync.WaitGroup
|
||||||
|
|
||||||
|
for clientIndex := 0; clientIndex < 10; clientIndex++ {
|
||||||
|
waitGroup.Add(1)
|
||||||
|
go func(clientIndex int) {
|
||||||
|
defer waitGroup.Done()
|
||||||
|
client := &http.Client{Transport: &http.Transport{}, Timeout: 5 * time.Second}
|
||||||
|
defer client.CloseIdleConnections()
|
||||||
|
<-start
|
||||||
|
for messageIndex := 0; messageIndex < 10; messageIndex++ {
|
||||||
|
body, err := json.Marshal(map[string]string{
|
||||||
|
"text": fmt.Sprintf("client-%02d-message-%02d", clientIndex, messageIndex),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
errors <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
request, err := http.NewRequest(http.MethodPost,
|
||||||
|
api.server.URL+"/api/v1/chats/"+chat.ID+"/messages", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
errors <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.Header.Set("X-User-Id", users[clientIndex].ID)
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
errors <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, readErr := io.Copy(io.Discard, response.Body)
|
||||||
|
closeErr := response.Body.Close()
|
||||||
|
if readErr != nil {
|
||||||
|
errors <- readErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
errors <- closeErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if response.StatusCode != http.StatusCreated {
|
||||||
|
errors <- fmt.Errorf("client %d message %d: status=%d", clientIndex, messageIndex, response.StatusCode)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}(clientIndex)
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
waitGroup.Wait()
|
||||||
|
close(errors)
|
||||||
|
for err := range errors {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seenIDs := make(map[string]struct{}, 10*10)
|
||||||
|
seenTexts := make(map[string]struct{}, 10*10)
|
||||||
|
cursor := ""
|
||||||
|
for {
|
||||||
|
path := "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||||
|
if cursor != "" {
|
||||||
|
path += "&cursor=" + url.QueryEscape(cursor)
|
||||||
|
}
|
||||||
|
var page messagePageResponse
|
||||||
|
api.request(t, http.DefaultClient, http.MethodGet, path, users[0].ID, "", http.StatusOK, &page)
|
||||||
|
for _, message := range page.Items {
|
||||||
|
if _, duplicate := seenIDs[message.ID]; duplicate {
|
||||||
|
t.Fatalf("duplicate message ID %s", message.ID)
|
||||||
|
}
|
||||||
|
if _, duplicate := seenTexts[message.Text]; duplicate {
|
||||||
|
t.Fatalf("duplicate message text %q", message.Text)
|
||||||
|
}
|
||||||
|
seenIDs[message.ID] = struct{}{}
|
||||||
|
seenTexts[message.Text] = struct{}{}
|
||||||
|
}
|
||||||
|
if page.NextCursor == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
cursor = *page.NextCursor
|
||||||
|
}
|
||||||
|
if len(seenIDs) != 10*10 || len(seenTexts) != 10*10 {
|
||||||
|
t.Fatalf("received %d unique IDs and %d unique texts, want %d of each",
|
||||||
|
len(seenIDs), len(seenTexts), 10*10)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/contracts"
|
||||||
|
)
|
||||||
|
|
||||||
|
var swaggerOpenAPI = makeSwaggerOpenAPI()
|
||||||
|
|
||||||
|
func (h *Chat) swagger(c echo.Context) error {
|
||||||
|
return c.Redirect(http.StatusTemporaryRedirect, "/swagger/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Chat) swaggerSpec(c echo.Context) error {
|
||||||
|
return c.Blob(http.StatusOK, echo.MIMEApplicationJSON, swaggerOpenAPI)
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeSwaggerOpenAPI() []byte {
|
||||||
|
var document map[string]any
|
||||||
|
if err := json.Unmarshal(contracts.OpenAPI, &document); err != nil {
|
||||||
|
panic("cannot decode embedded OpenAPI contract: " + err.Error())
|
||||||
|
}
|
||||||
|
// A relative URL keeps Swagger requests on the same scheme, host and port
|
||||||
|
// as the UI. This also works behind a reverse proxy and on a custom PORT.
|
||||||
|
document["servers"] = []map[string]string{{
|
||||||
|
"url": "/",
|
||||||
|
"description": "Текущий адрес Swagger UI",
|
||||||
|
}}
|
||||||
|
encoded, err := json.Marshal(document)
|
||||||
|
if err != nil {
|
||||||
|
panic("cannot encode Swagger OpenAPI contract: " + err.Error())
|
||||||
|
}
|
||||||
|
return encoded
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UseCase is the application boundary required by the HTTP handler.
|
||||||
|
type UseCase interface {
|
||||||
|
Authenticate(ctx context.Context, rawUserID string) (domain.User, error)
|
||||||
|
CreateUser(ctx context.Context, user domain.User) (domain.User, error)
|
||||||
|
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||||
|
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||||
|
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
|
||||||
|
CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error)
|
||||||
|
ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Chat struct {
|
||||||
|
ID string
|
||||||
|
Title string
|
||||||
|
MemberIDs []string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
type ErrorCode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ErrorInvalid ErrorCode = "invalid_request"
|
||||||
|
ErrorUnauthorized ErrorCode = "unauthorized"
|
||||||
|
ErrorNotFound ErrorCode = "not_found"
|
||||||
|
ErrorConflict ErrorCode = "conflict"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ApplicationError struct {
|
||||||
|
Code ErrorCode
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ApplicationError) Error() string {
|
||||||
|
return e.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewApplicationError(code ErrorCode, message string) error {
|
||||||
|
return &ApplicationError{Code: code, Message: message}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AsApplicationError(err error) (*ApplicationError, bool) {
|
||||||
|
var applicationError *ApplicationError
|
||||||
|
ok := errors.As(err, &applicationError)
|
||||||
|
return applicationError, ok
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
ID string
|
||||||
|
ChatID string
|
||||||
|
SenderID string
|
||||||
|
Text string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Position struct {
|
||||||
|
CreatedAt time.Time
|
||||||
|
ID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pagination struct {
|
||||||
|
After *Position
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatPage struct {
|
||||||
|
Items []Chat
|
||||||
|
HasMore bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessagePage struct {
|
||||||
|
Items []Message
|
||||||
|
HasMore bool
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID string
|
||||||
|
Username string
|
||||||
|
DisplayName string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Memory is the lab1 in-memory Repository implementation.
|
||||||
|
type Memory struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
users map[string]domain.User
|
||||||
|
userByUsername map[string]string
|
||||||
|
chats map[string]domain.Chat
|
||||||
|
messages map[string][]domain.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ chatusecase.Repository = (*Memory)(nil)
|
||||||
|
|
||||||
|
func NewMemory() *Memory {
|
||||||
|
return &Memory{
|
||||||
|
users: make(map[string]domain.User),
|
||||||
|
userByUsername: make(map[string]string),
|
||||||
|
chats: make(map[string]domain.Chat),
|
||||||
|
messages: make(map[string][]domain.Message),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) CreateUser(_ context.Context, username, displayName string) (domain.User, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if _, exists := m.userByUsername[username]; exists {
|
||||||
|
return domain.User{}, chatusecase.ErrUsernameTaken
|
||||||
|
}
|
||||||
|
user := domain.User{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Username: username,
|
||||||
|
DisplayName: displayName,
|
||||||
|
CreatedAt: now(),
|
||||||
|
}
|
||||||
|
m.users[user.ID] = user
|
||||||
|
m.userByUsername[user.Username] = user.ID
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) User(_ context.Context, id string) (domain.User, bool, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
user, ok := m.users[id]
|
||||||
|
return user, ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) CreateChat(_ context.Context, title string, memberIDs []string) (domain.Chat, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
for _, memberID := range memberIDs {
|
||||||
|
if _, exists := m.users[memberID]; !exists {
|
||||||
|
return domain.Chat{}, chatusecase.ErrUserNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chat := domain.Chat{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Title: title,
|
||||||
|
MemberIDs: append([]string(nil), memberIDs...),
|
||||||
|
CreatedAt: now(),
|
||||||
|
}
|
||||||
|
m.chats[chat.ID] = chat
|
||||||
|
return cloneChat(chat), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) ChatForUser(_ context.Context, chatID, userID string) (domain.Chat, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
chat, exists := m.chats[chatID]
|
||||||
|
if !exists {
|
||||||
|
return domain.Chat{}, chatusecase.ErrChatNotFound
|
||||||
|
}
|
||||||
|
if !contains(chat.MemberIDs, userID) {
|
||||||
|
return domain.Chat{}, chatusecase.ErrNotMember
|
||||||
|
}
|
||||||
|
return cloneChat(chat), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) ListChats(_ context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
|
||||||
|
result := make([]domain.Chat, 0)
|
||||||
|
for _, chat := range m.chats {
|
||||||
|
if contains(chat.MemberIDs, userID) && isAfter(chat.CreatedAt, chat.ID, after) {
|
||||||
|
result = append(result, cloneChat(chat))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(result, func(i, j int) bool {
|
||||||
|
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
|
||||||
|
})
|
||||||
|
if len(result) > limit {
|
||||||
|
result = result[:limit]
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) CreateMessage(_ context.Context, chatID, senderID, text string) (domain.Message, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
chat, exists := m.chats[chatID]
|
||||||
|
if !exists {
|
||||||
|
return domain.Message{}, chatusecase.ErrChatNotFound
|
||||||
|
}
|
||||||
|
if !contains(chat.MemberIDs, senderID) {
|
||||||
|
return domain.Message{}, chatusecase.ErrNotMember
|
||||||
|
}
|
||||||
|
message := domain.Message{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
ChatID: chatID,
|
||||||
|
SenderID: senderID,
|
||||||
|
Text: text,
|
||||||
|
CreatedAt: now(),
|
||||||
|
}
|
||||||
|
m.messages[chatID] = append(m.messages[chatID], message)
|
||||||
|
return message, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) ListMessages(_ context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
|
||||||
|
values := m.messages[chatID]
|
||||||
|
result := make([]domain.Message, 0, min(len(values), limit))
|
||||||
|
for _, message := range values {
|
||||||
|
if isAfter(message.CreatedAt, message.ID, after) {
|
||||||
|
result = append(result, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(result, func(i, j int) bool {
|
||||||
|
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
|
||||||
|
})
|
||||||
|
if len(result) > limit {
|
||||||
|
result = result[:limit]
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneChat(chat domain.Chat) domain.Chat {
|
||||||
|
chat.MemberIDs = append([]string(nil), chat.MemberIDs...)
|
||||||
|
return chat
|
||||||
|
}
|
||||||
|
|
||||||
|
func now() time.Time {
|
||||||
|
return time.Now().UTC().Truncate(time.Second)
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(values []string, target string) bool {
|
||||||
|
for _, value := range values {
|
||||||
|
if value == target {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAfter(createdAt time.Time, id string, after *domain.Position) bool {
|
||||||
|
return after == nil || createdAt.After(after.CreatedAt) || createdAt.Equal(after.CreatedAt) && id > after.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func less(leftTime time.Time, leftID string, rightTime time.Time, rightID string) bool {
|
||||||
|
if leftTime.Equal(rightTime) {
|
||||||
|
return leftID < rightID
|
||||||
|
}
|
||||||
|
return leftTime.Before(rightTime)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUsernameTaken = errors.New("username is already taken")
|
||||||
|
ErrUserNotFound = errors.New("user not found")
|
||||||
|
ErrChatNotFound = errors.New("chat not found")
|
||||||
|
ErrNotMember = errors.New("user is not a chat member")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Repository is the persistence port required by the chat use case.
|
||||||
|
type Repository interface {
|
||||||
|
CreateUser(ctx context.Context, username, displayName string) (domain.User, error)
|
||||||
|
User(ctx context.Context, id string) (domain.User, bool, error)
|
||||||
|
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||||
|
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
|
||||||
|
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
|
||||||
|
CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error)
|
||||||
|
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UseCase struct {
|
||||||
|
repository Repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(repository Repository) *UseCase {
|
||||||
|
return &UseCase{repository: repository}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) Authenticate(ctx context.Context, rawUserID string) (domain.User, error) {
|
||||||
|
userID, valid := normalizeUUID(rawUserID)
|
||||||
|
if !valid {
|
||||||
|
return domain.User{}, unauthorized()
|
||||||
|
}
|
||||||
|
user, exists, err := u.repository.User(ctx, userID)
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return domain.User{}, unauthorized()
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) CreateUser(ctx context.Context, user domain.User) (domain.User, error) {
|
||||||
|
if !validUsername(user.Username) {
|
||||||
|
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
|
||||||
|
}
|
||||||
|
if !validRequiredText(user.DisplayName, 100) {
|
||||||
|
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
|
||||||
|
}
|
||||||
|
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName)
|
||||||
|
if errors.Is(err, ErrUsernameTaken) {
|
||||||
|
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
|
||||||
|
}
|
||||||
|
return created, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||||
|
if !validRequiredText(chat.Title, 100) {
|
||||||
|
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
|
||||||
|
}
|
||||||
|
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
|
||||||
|
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
|
||||||
|
}
|
||||||
|
|
||||||
|
normalizedIDs := make([]string, len(chat.MemberIDs))
|
||||||
|
seen := make(map[string]struct{}, len(chat.MemberIDs))
|
||||||
|
callerIncluded := false
|
||||||
|
for index, memberID := range chat.MemberIDs {
|
||||||
|
normalized, valid := normalizeUUID(memberID)
|
||||||
|
if !valid {
|
||||||
|
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
|
||||||
|
}
|
||||||
|
if _, duplicate := seen[normalized]; duplicate {
|
||||||
|
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
|
||||||
|
}
|
||||||
|
normalizedIDs[index] = normalized
|
||||||
|
seen[normalized] = struct{}{}
|
||||||
|
callerIncluded = callerIncluded || normalized == callerID
|
||||||
|
}
|
||||||
|
if !callerIncluded {
|
||||||
|
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
|
||||||
|
if errors.Is(err, ErrUserNotFound) {
|
||||||
|
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
|
||||||
|
}
|
||||||
|
return created, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||||
|
chatID, valid := normalizeUUID(chat.ID)
|
||||||
|
if !valid {
|
||||||
|
return domain.Chat{}, invalid("Некорректный chat_id")
|
||||||
|
}
|
||||||
|
return u.chatForUser(ctx, chatID, callerID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
|
||||||
|
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||||
|
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||||
|
}
|
||||||
|
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return domain.ChatPage{}, err
|
||||||
|
}
|
||||||
|
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||||
|
if page.HasMore {
|
||||||
|
page.Items = page.Items[:pagination.Limit]
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
|
||||||
|
chatID, valid := normalizeUUID(message.ChatID)
|
||||||
|
if !valid {
|
||||||
|
return domain.Message{}, invalid("Некорректный chat_id")
|
||||||
|
}
|
||||||
|
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||||
|
return domain.Message{}, err
|
||||||
|
}
|
||||||
|
if !validRequiredText(message.Text, 4000) {
|
||||||
|
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
|
||||||
|
}
|
||||||
|
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text)
|
||||||
|
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||||
|
return domain.Message{}, notFound()
|
||||||
|
}
|
||||||
|
return created, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
|
||||||
|
chatID, valid := normalizeUUID(chat.ID)
|
||||||
|
if !valid {
|
||||||
|
return domain.MessagePage{}, invalid("Некорректный chat_id")
|
||||||
|
}
|
||||||
|
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||||
|
return domain.MessagePage{}, err
|
||||||
|
}
|
||||||
|
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||||
|
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||||
|
}
|
||||||
|
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return domain.MessagePage{}, err
|
||||||
|
}
|
||||||
|
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||||
|
if page.HasMore {
|
||||||
|
page.Items = page.Items[:pagination.Limit]
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
|
||||||
|
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
|
||||||
|
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||||
|
return domain.Chat{}, notFound()
|
||||||
|
}
|
||||||
|
return chat, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func invalid(message string) error {
|
||||||
|
return domain.NewApplicationError(domain.ErrorInvalid, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func unauthorized() error {
|
||||||
|
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительный X-User-Id")
|
||||||
|
}
|
||||||
|
|
||||||
|
func notFound() error {
|
||||||
|
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func normalizeUUID(value string) (string, bool) {
|
||||||
|
parsed, err := uuid.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
normalized := parsed.String()
|
||||||
|
if !strings.EqualFold(value, normalized) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return normalized, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validUsername(value string) bool {
|
||||||
|
if len(value) < 3 || len(value) > 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validRequiredText(value string, maxRunes int) bool {
|
||||||
|
length := utf8.RuneCountInString(value)
|
||||||
|
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user