forked from mtusi2026/mtusi2026lab2
feat:level4
This commit is contained in:
+11
-13
@@ -2,32 +2,30 @@
|
||||
FROM golang:1.22-alpine AS build
|
||||
|
||||
WORKDIR /src
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
|
||||
RUN go mod download
|
||||
|
||||
COPY cmd/ ./cmd/
|
||||
COPY src/ ./src/
|
||||
|
||||
COPY cmd ./cmd
|
||||
COPY src ./src
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/messenger
|
||||
|
||||
# --- runtime stage ---
|
||||
FROM alpine:3.20
|
||||
|
||||
RUN adduser -D -H -u 10001 app
|
||||
|
||||
USER app
|
||||
|
||||
RUN apk add --no-cache ca-certificates postgresql-client && \
|
||||
addgroup -S app && adduser -S -G app app
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build /out/messenger /app/messenger
|
||||
COPY migrations /app/migrations
|
||||
COPY scripts/migrate.sh /app/migrate.sh
|
||||
RUN chmod +x /app/migrate.sh
|
||||
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=2s --retries=5 \
|
||||
CMD wget -qO- http://127.0.0.1:8080/health/live >/dev/null 2>&1 || exit 1
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \
|
||||
CMD wget -qO- http://127.0.0.1:8080/health/live >/dev/null || exit 1
|
||||
|
||||
ENTRYPOINT ["/app/messenger"]
|
||||
+37
-7
@@ -18,22 +18,54 @@ import (
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
store := domain.NewStore()
|
||||
handler := &api.Handler{Store: store}
|
||||
if cfg.DatabaseURL == "" {
|
||||
log.Fatal("DATABASE_URL is required (env DATABASE_URL or DATABASE_URL_FILE)")
|
||||
}
|
||||
|
||||
rootCtx, cancelRoot := context.WithCancel(context.Background())
|
||||
defer cancelRoot()
|
||||
|
||||
store, err := domain.NewStore(rootCtx, cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("postgres: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
// Кэш сессий в Redis/Valkey. Если CACHE_URL не задан — работаем без кэша.
|
||||
var cache *domain.SessionCache
|
||||
if cfg.CacheURL != "" {
|
||||
cache, err = domain.NewSessionCache(rootCtx, cfg.CacheURL)
|
||||
if err != nil {
|
||||
if cfg.RedisRequired {
|
||||
log.Fatalf("redis required but unavailable: %v", err)
|
||||
}
|
||||
log.Printf("redis unavailable, continuing without session cache: %v", err)
|
||||
cache = nil
|
||||
} else {
|
||||
defer cache.Close()
|
||||
}
|
||||
} else if cfg.RedisRequired {
|
||||
log.Fatal("SESSION_STORE=redis but CACHE_URL is not configured")
|
||||
}
|
||||
|
||||
sessions := domain.NewSessionStore(store, cache, cfg.SessionTTL)
|
||||
handler := &api.Handler{Store: store, Sessions: sessions}
|
||||
router := api.NewRouter(handler)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Graceful shutdown по SIGTERM/SIGINT в течение 10 секунд.
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
go func() {
|
||||
log.Printf("messenger listening on %s", srv.Addr)
|
||||
log.Printf("messenger listening on %s (env=%s, session_ttl=%s)", srv.Addr, cfg.Env, cfg.SessionTTL)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
@@ -43,8 +75,6 @@ func main() {
|
||||
log.Println("shutting down...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Printf("shutdown error: %v", err)
|
||||
}
|
||||
_ = srv.Shutdown(ctx)
|
||||
log.Println("stopped")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.3-alpine
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_DB: messenger
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks: [backend]
|
||||
|
||||
redis:
|
||||
image: redis:7.2.5-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--save", "60", "1"]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks: [backend]
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
APP_HOST: "0.0.0.0"
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: "lab"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8080:8080"
|
||||
networks: [backend]
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["/app/migrate.sh"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
secrets:
|
||||
- database_url
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks: [backend]
|
||||
restart: "no"
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
|
||||
networks:
|
||||
backend:
|
||||
driver: bridge
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password.txt
|
||||
database_url:
|
||||
file: ./secrets/database_url.txt
|
||||
cache_url:
|
||||
file: ./secrets/cache_url.txt
|
||||
@@ -2,4 +2,19 @@ module mtusi-messenger
|
||||
|
||||
go 1.22
|
||||
|
||||
require github.com/google/uuid v1.6.0
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.5.5
|
||||
github.com/redis/go-redis/v9 v9.5.1
|
||||
golang.org/x/crypto v0.23.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,2 +1,55 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
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/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8=
|
||||
github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
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=
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id),
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Индекс истории: ровно под ORDER BY (created_at, id) и keyset-курсор.
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created_id
|
||||
ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions (expires_at);
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Применяет миграции к БД, читая DATABASE_URL из файла секрета.
|
||||
# Устойчиво к повторному запуску (CREATE ... IF NOT EXISTS).
|
||||
URL_FILE="${DATABASE_URL_FILE:-/run/secrets/database_url}"
|
||||
DATABASE_URL="$(cat "$URL_FILE")"
|
||||
PSQL="psql $DATABASE_URL -v ON_ERROR_STOP=1 -q"
|
||||
|
||||
for f in migrations/*.sql; do
|
||||
echo "applying $f"
|
||||
$PSQL -f "$f"
|
||||
done
|
||||
echo "migrations done"
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Перезапускает API и все хранилища (postgres, redis), сохраняя volumes.
|
||||
# Никаких down -v / flush / reseed.
|
||||
|
||||
COMPOSE="docker compose --env-file .env"
|
||||
|
||||
$COMPOSE stop api
|
||||
$COMPOSE restart postgres
|
||||
$COMPOSE restart redis
|
||||
|
||||
# Ждём healthy у postgres и redis.
|
||||
for i in $(seq 1 60); do
|
||||
pg_ok=$($COMPOSE ps --format json postgres | grep -c '"Health":"healthy"' || true)
|
||||
rd_ok=$($COMPOSE ps --format json redis | grep -c '"Health":"healthy"' || true)
|
||||
if [ "$pg_ok" -ge 1 ] && [ "$rd_ok" -ge 1 ]; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
$COMPOSE up -d api
|
||||
|
||||
# Готовность API проверит сам тест; здесь возвращаем 0.
|
||||
exit 0
|
||||
@@ -0,0 +1,68 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
// bearerAuth извлекает токен, проверяет сессию и кладёт пользователя в контекст.
|
||||
// Basic на бизнес-эндпоинтах не принимается. X-User-Id игнорируется.
|
||||
func (h *Handler) bearerAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing bearer token")
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||
if token == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing bearer token")
|
||||
return
|
||||
}
|
||||
u, err := h.Sessions.Lookup(r.Context(), token)
|
||||
if err != nil {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid session")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userKey, *u)
|
||||
ctx = context.WithValue(ctx, tokenKey, token)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func userFrom(r *http.Request) (domain.User, bool) {
|
||||
u, ok := r.Context().Value(userKey).(domain.User)
|
||||
return u, ok
|
||||
}
|
||||
|
||||
func tokenFrom(r *http.Request) string {
|
||||
if v, ok := r.Context().Value(tokenKey).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseBasicCredentials разбирает Authorization: Basic base64(username:password).
|
||||
func parseBasicCredentials(header string) (string, string, error) {
|
||||
if !strings.HasPrefix(header, "Basic ") {
|
||||
return "", "", errors.New("not basic")
|
||||
}
|
||||
raw := strings.TrimSpace(strings.TrimPrefix(header, "Basic "))
|
||||
decoded, err := base64.StdEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return "", "", errors.New("invalid base64")
|
||||
}
|
||||
parts := strings.SplitN(string(decoded), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", "", errors.New("missing colon")
|
||||
}
|
||||
return parts[0], parts[1], nil
|
||||
}
|
||||
+163
-125
@@ -12,9 +12,9 @@ import (
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// Handler держит хранилище.
|
||||
type Handler struct {
|
||||
Store *domain.Store
|
||||
Store *domain.Store
|
||||
Sessions *domain.SessionStore
|
||||
}
|
||||
|
||||
// --- Health ---
|
||||
@@ -23,7 +23,13 @@ func (h *Handler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// Ready проверяет БД (обязательная зависимость). Redis — кэш, его недоступность
|
||||
// не должна ронять readiness: API может работать, обходя кэш.
|
||||
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.Store.Ping(r.Context()); err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
@@ -32,11 +38,14 @@ func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
type createUserReq struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
@@ -44,30 +53,70 @@ func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
if len([]rune(req.DisplayName)) < 1 || len([]rune(req.DisplayName)) > 100 {
|
||||
if n := len([]rune(req.DisplayName)); n < 1 || n > 100 || strings.TrimSpace(req.DisplayName) == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(req.Username, req.DisplayName)
|
||||
// Пароль: 12–128 code points, не состоит только из пробелов.
|
||||
if n := len([]rune(req.Password)); n < 12 || n > 128 || strings.TrimSpace(req.Password) == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid password")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err == domain.ErrConflict {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
if userID == "" {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing X-User-Id")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.GetUser(userID)
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
u, _ := userFrom(r)
|
||||
writeJSON(w, http.StatusOK, u)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
// --- Auth ---
|
||||
|
||||
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, err := parseBasicCredentials(r.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "unknown user")
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, u)
|
||||
u, err := h.Store.VerifyPassword(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == domain.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
s, err := h.Sessions.Create(r.Context(), *u)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, s)
|
||||
}
|
||||
|
||||
func (h *Handler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
token := tokenFrom(r)
|
||||
if err := h.Sessions.Revoke(r.Context(), token); err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
// --- Chats ---
|
||||
@@ -78,55 +127,58 @@ type createChatReq struct {
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req createChatReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Title) == "" || len([]rune(req.Title)) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
c, err := h.Store.CreateChat(req.Title, req.MemberIDs, userID)
|
||||
if err == domain.ErrInvalid {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid members")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, c)
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
var req createChatReq
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Title) == "" || len([]rune(req.Title)) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
c, err := h.Store.CreateChat(r.Context(), req.Title, req.MemberIDs, me.ID)
|
||||
if err == domain.ErrInvalid {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid members")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, c)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chats := h.Store.ListChats(userID)
|
||||
if chats == nil {
|
||||
chats = []domain.Chat{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.ChatPage{Items: chats, NextCursor: nil})
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chats, err := h.Store.ListChats(r.Context(), me.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.ChatPage{Items: chats, NextCursor: nil})
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
c, err := h.Store.GetChat(chatID, userID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
c, err := h.Store.GetChat(r.Context(), r.PathValue("chat_id"), me.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
@@ -136,78 +188,64 @@ type createMessageReq struct {
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(chatID, userID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(req.Text)
|
||||
if text == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "empty message")
|
||||
return
|
||||
}
|
||||
if len([]rune(req.Text)) > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "message too long")
|
||||
return
|
||||
}
|
||||
m, err := h.Store.AddMessage(chatID, userID, req.Text)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(r.Context(), chatID, me.ID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if len([]rune(req.Text)) > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "message too long")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Text) == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "empty message")
|
||||
return
|
||||
}
|
||||
m, err := h.Store.AddMessage(r.Context(), chatID, me.ID, req.Text)
|
||||
if err == domain.ErrNotFound {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(chatID, userID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid limit")
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := h.Store.GetChat(r.Context(), chatID, me.ID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
items, next, err := h.Store.ListMessages(chatID, limit, cursor)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []domain.Message{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.MessagePage{Items: items, NextCursor: next})
|
||||
}
|
||||
|
||||
// requireUser проверяет X-User-Id и возвращает ID.
|
||||
func (h *Handler) requireUser(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
if userID == "" {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing X-User-Id")
|
||||
return "", false
|
||||
}
|
||||
if _, err := h.Store.GetUser(userID); err != nil {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "unknown user")
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
limit := 50
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid limit")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
items, next, err := h.Store.ListMessages(r.Context(), chatID, limit, cursor)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.MessagePage{Items: items, NextCursor: next})
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
@@ -9,9 +9,12 @@ import (
|
||||
|
||||
type ctxKey string
|
||||
|
||||
const requestIDKey ctxKey = "request_id"
|
||||
const (
|
||||
requestIDKey ctxKey = "request_id"
|
||||
userKey ctxKey = "user"
|
||||
tokenKey ctxKey = "token"
|
||||
)
|
||||
|
||||
// requestIDFrom достаёт request_id из контекста.
|
||||
func requestIDFrom(r *http.Request) string {
|
||||
if v, ok := r.Context().Value(requestIDKey).(string); ok {
|
||||
return v
|
||||
@@ -19,7 +22,6 @@ func requestIDFrom(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// withRequestID добавляет X-Request-Id во все ответы.
|
||||
func withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
|
||||
+2
-1
@@ -2,13 +2,14 @@ package api
|
||||
|
||||
import "net/http"
|
||||
|
||||
// NewRouter собирает маршруты.
|
||||
func NewRouter(h *Handler) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", h.Live)
|
||||
mux.HandleFunc("GET /health/ready", h.Ready)
|
||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", h.CurrentUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", h.CreateSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", h.RevokeSession)
|
||||
mux.HandleFunc("POST /api/v1/chats", h.CreateChat)
|
||||
mux.HandleFunc("GET /api/v1/chats", h.ListChats)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", h.GetChat)
|
||||
|
||||
+53
-12
@@ -3,16 +3,38 @@ package config
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config — конфигурация, приходящая из окружения.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
SessionStore string // "postgres" | "redis"
|
||||
RedisRequired bool
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readSecretFromFile(path string) string {
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Load читает переменные окружения со значениями по умолчанию.
|
||||
func Load() Config {
|
||||
port := 8080
|
||||
if v := os.Getenv("APP_PORT"); v != "" {
|
||||
@@ -20,13 +42,32 @@ func Load() Config {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
host := os.Getenv("APP_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
ttl := 3600
|
||||
if v := os.Getenv("SESSION_TTL_SECONDS"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
ttl = n
|
||||
}
|
||||
}
|
||||
env := os.Getenv("APP_ENV")
|
||||
if env == "" {
|
||||
env = "lab"
|
||||
|
||||
// DATABASE_URL и CACHE_URL могут прийти либо напрямую, либо через *_FILE.
|
||||
dbURL := os.Getenv("DATABASE_URL")
|
||||
if dbURL == "" {
|
||||
dbURL = readSecretFromFile(os.Getenv("DATABASE_URL_FILE"))
|
||||
}
|
||||
cacheURL := os.Getenv("CACHE_URL")
|
||||
if cacheURL == "" {
|
||||
cacheURL = readSecretFromFile(os.Getenv("CACHE_URL_FILE"))
|
||||
}
|
||||
|
||||
store := getenv("SESSION_STORE", "postgres")
|
||||
return Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: port,
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
DatabaseURL: dbURL,
|
||||
CacheURL: cacheURL,
|
||||
SessionTTL: time.Duration(ttl) * time.Second,
|
||||
SessionStore: store,
|
||||
RedisRequired: store == "redis",
|
||||
}
|
||||
return Config{Host: host, Port: port, Env: env}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// SessionCache — необязательный кэш сессий поверх Redis.
|
||||
// Источник истины — PostgreSQL. Кэш ускоряет проверку токена.
|
||||
type SessionCache struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionCache(ctx context.Context, url string) (*SessionCache, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rdb := redis.NewClient(opt)
|
||||
c, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := rdb.Ping(c).Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &SessionCache{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) key(token string) string { return "session:" + token }
|
||||
|
||||
func (c *SessionCache) Set(ctx context.Context, token string, u User, expires time.Time) {
|
||||
ttl := time.Until(expires)
|
||||
if ttl <= 0 {
|
||||
return
|
||||
}
|
||||
b, err := json.Marshal(u)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.rdb.Set(ctx, c.key(token), b, ttl)
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(ctx context.Context, token string) (User, bool) {
|
||||
b, err := c.rdb.Get(ctx, c.key(token)).Bytes()
|
||||
if err != nil {
|
||||
return User{}, false
|
||||
}
|
||||
var u User
|
||||
if err := json.Unmarshal(b, &u); err != nil {
|
||||
return User{}, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (c *SessionCache) Del(ctx context.Context, token string) {
|
||||
c.rdb.Del(ctx, c.key(token))
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
c2, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
return c.rdb.Ping(c2).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error { return c.rdb.Close() }
|
||||
+18
-8
@@ -1,8 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User — пользователь системы.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
@@ -10,7 +12,6 @@ type User struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Chat — чат с участниками.
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
@@ -18,7 +19,6 @@ type Chat struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Message — сообщение в чате.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
@@ -27,26 +27,36 @@ type Message struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MessagePage — страница истории сообщений.
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// ChatPage — страница списка чатов.
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// ErrorBody — тело ошибки в формате контракта.
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type ErrorBody struct {
|
||||
Error ErrorDetail `json:"error"`
|
||||
}
|
||||
|
||||
// ErrorDetail — детали ошибки.
|
||||
type ErrorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalid = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(ctx context.Context, dsn string) (*Store, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = time.Hour
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(ctxPing); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
c, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
return s.pool.Ping(c)
|
||||
}
|
||||
|
||||
// --- Users ---
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := uuid.NewString()
|
||||
var u User
|
||||
err = s.pool.QueryRow(ctx,
|
||||
`INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1,$2,$3,$4)
|
||||
RETURNING id, username, display_name, created_at`,
|
||||
id, username, displayName, string(hash),
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
|
||||
var u User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at FROM users WHERE id=$1`, id,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// VerifyPassword возвращает пользователя, если пароль верный; иначе ErrUnauthorized.
|
||||
func (s *Store) VerifyPassword(ctx context.Context, username, password string) (*User, error) {
|
||||
var u User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username=$1`,
|
||||
username,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Всё равно тратим время на bcrypt, чтобы не различать "нет юзера"/"неверный пароль".
|
||||
_ = bcrypt.CompareHashAndPassword([]byte("$2a$10$0000000000000000000000000000000000000000000000000000"), []byte(password))
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// --- Chats ---
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, creatorID string) (*Chat, error) {
|
||||
// Проверка входных данных.
|
||||
seen := map[string]bool{}
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
if !seen[creatorID] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Проверяем, что все участники существуют.
|
||||
for id := range seen {
|
||||
var exists bool
|
||||
if err := tx.QueryRow(ctx, `SELECT true FROM users WHERE id=$1`, id).Scan(&exists); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
chatID := uuid.NewString()
|
||||
var c Chat
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO chats (id, title) VALUES ($1,$2) RETURNING id, title, created_at`,
|
||||
chatID, title,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2)`,
|
||||
c.ID, id,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Порядок member_ids — как в запросе.
|
||||
c.MemberIDs = append([]string(nil), memberIDs...)
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID string) (*Chat, error) {
|
||||
var exists bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
||||
chatID, userID,
|
||||
).Scan(&exists)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var c Chat
|
||||
err = s.pool.QueryRow(ctx,
|
||||
`SELECT id, title, created_at FROM chats WHERE id=$1`, chatID,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
return &c, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID string) ([]Chat, error) {
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var chats []Chat
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Догружаем участников (небольшие объёмы в учебном сценарии).
|
||||
for i := range chats {
|
||||
mrows, err := s.pool.Query(ctx,
|
||||
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for mrows.Next() {
|
||||
var uid string
|
||||
if err := mrows.Scan(&uid); err != nil {
|
||||
mrows.Close()
|
||||
return nil, err
|
||||
}
|
||||
chats[i].MemberIDs = append(chats[i].MemberIDs, uid)
|
||||
}
|
||||
mrows.Close()
|
||||
}
|
||||
if chats == nil {
|
||||
chats = []Chat{}
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
|
||||
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (*Message, error) {
|
||||
// Проверка членства + вставка в одной транзакции.
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var ok bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
||||
chatID, senderID,
|
||||
).Scan(&ok); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var m Message
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1,$2,$3,$4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`,
|
||||
uuid.NewString(), chatID, senderID, text,
|
||||
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// ListMessages — keyset-пагинация по (created_at, id).
|
||||
// Курсор — это id последнего элемента предыдущей страницы; сам id уникален,
|
||||
// поэтому используем его для поиска (created_at, id) в БД.
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, cursor string) ([]Message, *string, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
|
||||
if cursor == "" {
|
||||
rows, err = s.pool.Query(ctx,
|
||||
`SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id=$1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
// Определяем позицию курсора.
|
||||
var cCreated time.Time
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT created_at FROM messages WHERE id=$1 AND chat_id=$2`,
|
||||
cursor, chatID,
|
||||
).Scan(&cCreated); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, ErrInvalid
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
rows, err = s.pool.Query(ctx,
|
||||
`SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id=$1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`, chatID, cCreated, cursor, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[len(items)-1].ID
|
||||
next = &last
|
||||
}
|
||||
if items == nil {
|
||||
items = []Message{}
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type SessionStore struct {
|
||||
store *Store
|
||||
cache *SessionCache
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewSessionStore(store *Store, cache *SessionCache, ttl time.Duration) *SessionStore {
|
||||
return &SessionStore{store: store, cache: cache, ttl: ttl}
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
b := make([]byte, 32) // 256 бит
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Create создаёт сессию: сначала пишем в PostgreSQL (источник истины), затем кэш.
|
||||
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expires := time.Now().UTC().Add(s.ttl)
|
||||
_, err = s.store.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
|
||||
token, user.ID, expires)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, user, expires)
|
||||
}
|
||||
return &Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expires,
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Lookup проверяет токен. Сначала кэш; при miss — PostgreSQL.
|
||||
// Истёкшие сессии удаляются лениво.
|
||||
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
|
||||
if s.cache != nil {
|
||||
if u, ok := s.cache.Get(ctx, token); ok {
|
||||
return &u, nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
)
|
||||
err := s.store.pool.QueryRow(ctx,
|
||||
`SELECT user_id, expires_at FROM sessions WHERE token=$1`, token,
|
||||
).Scan(&userID, &expiresAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if time.Now().UTC().After(expiresAt) {
|
||||
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, *u, expiresAt)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет сессию из БД и кэша.
|
||||
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
|
||||
if _, err := s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalid = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
// Store — in-memory хранилище. Все данные исчезают при перезапуске процесса.
|
||||
type Store struct {
|
||||
mu sync.RWMutex // безопасность при параллельных запросах
|
||||
users map[string]*User
|
||||
byName map[string]*User
|
||||
chats map[string]*Chat
|
||||
messages map[string][]*Message // chat_id -> сообщения
|
||||
idIndex map[string]int // message_id -> позиция в messages[chat_id]
|
||||
}
|
||||
|
||||
// NewStore создаёт пустое хранилище.
|
||||
func NewStore() *Store {
|
||||
return &Store{
|
||||
users: make(map[string]*User),
|
||||
byName: make(map[string]*User),
|
||||
chats: make(map[string]*Chat),
|
||||
messages: make(map[string][]*Message),
|
||||
idIndex: make(map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser создаёт пользователя. Возвращает ErrConflict при дубликате username.
|
||||
func (s *Store) CreateUser(username, displayName string) (*User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, exists := s.byName[username]; exists {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
s.users[u.ID] = u
|
||||
s.byName[username] = u
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetUser возвращает пользователя по ID.
|
||||
func (s *Store) GetUser(id string) (*User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// CreateChat создаёт чат. Проверяет, что все участники существуют и вызывающий входит в список.
|
||||
func (s *Store) CreateChat(title string, memberIDs []string, creatorID string) (*Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
if !seen[creatorID] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
c := &Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
s.chats[c.ID] = c
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат, если пользователь — участник.
|
||||
func (s *Store) GetChat(chatID, userID string) (*Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
c, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == userID {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// ListChats возвращает чаты пользователя, отсортированные по (created_at, id).
|
||||
func (s *Store) ListChats(userID string) []Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
result := make([]Chat, 0)
|
||||
for _, c := range s.chats {
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == userID {
|
||||
result = append(result, *c)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].CreatedAt.Equal(result[j].CreatedAt) {
|
||||
return result[i].ID < result[j].ID
|
||||
}
|
||||
return result[i].CreatedAt.Before(result[j].CreatedAt)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// compareMessages возвращает true, если a < b по (created_at, id).
|
||||
func compareMessages(a, b *Message) bool {
|
||||
if a.CreatedAt.Equal(b.CreatedAt) {
|
||||
return a.ID < b.ID
|
||||
}
|
||||
return a.CreatedAt.Before(b.CreatedAt)
|
||||
}
|
||||
|
||||
// AddMessage добавляет сообщение, поддерживая сортировку вставкой.
|
||||
// Изменение относительно baseline: вместо append + sort при чтении
|
||||
// вставляем в нужную позицию сразу — чтение становится O(limit).
|
||||
func (s *Store) AddMessage(chatID, senderID, text string) (*Message, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.chats[chatID]; !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
m := &Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
msgs := s.messages[chatID]
|
||||
idx := sort.Search(len(msgs), func(i int) bool {
|
||||
return !compareMessages(msgs[i], m)
|
||||
})
|
||||
msgs = append(msgs, nil)
|
||||
copy(msgs[idx+1:], msgs[idx:])
|
||||
msgs[idx] = m
|
||||
s.messages[chatID] = msgs
|
||||
// Перестраиваем индексы от позиции вставки до конца.
|
||||
for i := idx; i < len(msgs); i++ {
|
||||
s.idIndex[msgs[i].ID] = i
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ListMessages возвращает страницу сообщений по курсору.
|
||||
// Изменение относительно baseline: без сортировки — срез уже отсортирован.
|
||||
func (s *Store) ListMessages(chatID string, limit int, cursor string) ([]Message, *string, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
msgs := s.messages[chatID]
|
||||
if len(msgs) == 0 {
|
||||
return []Message{}, nil, nil
|
||||
}
|
||||
start := 0
|
||||
if cursor != "" {
|
||||
pos, ok := s.idIndex[cursor]
|
||||
if !ok || pos >= len(msgs) || msgs[pos].ID != cursor || msgs[pos].ChatID != chatID {
|
||||
return nil, nil, ErrInvalid
|
||||
}
|
||||
start = pos + 1
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(msgs) {
|
||||
end = len(msgs)
|
||||
}
|
||||
items := make([]Message, 0, end-start)
|
||||
for _, m := range msgs[start:end] {
|
||||
items = append(items, *m)
|
||||
}
|
||||
var next *string
|
||||
if end < len(msgs) {
|
||||
last := msgs[end-1].ID
|
||||
next = &last
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
Reference in New Issue
Block a user