forked from mtusi2026/mtusi2026lab4
feat:lab3-catchup
This commit is contained in:
+31
@@ -0,0 +1,31 @@
|
||||
# --- build stage ---
|
||||
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
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/messenger
|
||||
|
||||
# --- runtime stage ---
|
||||
FROM alpine:3.20
|
||||
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
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \
|
||||
CMD wget -qO- http://127.0.0.1:8080/health/ready >/dev/null || exit 1
|
||||
|
||||
ENTRYPOINT ["/app/messenger"]
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/src/api"
|
||||
"mtusi-messenger/src/config"
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
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, cfg.InstanceID)
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
go func() {
|
||||
log.Printf("messenger listening on %s (env=%s, session_ttl=%s)", srv.Addr, cfg.Env, cfg.SessionTTL)
|
||||
log.Printf("instance_id=%s", cfg.InstanceID)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
<-stop
|
||||
log.Println("shutting down...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(ctx)
|
||||
log.Println("stopped")
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
x-api: &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
|
||||
SESSION_STORE: "postgres"
|
||||
SESSION_TTL_SECONDS: "3600"
|
||||
# INSTANCE_ID сгенерируется в config.go
|
||||
secrets: [database_url, cache_url]
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
networks: [backend]
|
||||
|
||||
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]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${PG_CPUS:-1.0}", memory: "${PG_MEM:-512M}" }
|
||||
|
||||
redis:
|
||||
image: redis:7.2.5-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--save"]
|
||||
volumes: [redisdata:/data]
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks: [backend]
|
||||
api:
|
||||
<<: *api
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${API_CPU_PER_REPLICA:-0.5}"
|
||||
memory: "${API_MEM_PER_REPLICA:-128M}"
|
||||
|
||||
migrate:
|
||||
<<: *api
|
||||
entrypoint: ["/app/migrate.sh"]
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
deploy:
|
||||
replicas: 1
|
||||
restart_policy:
|
||||
condition: "no"
|
||||
|
||||
lb:
|
||||
image: nginx:1.27.0-alpine
|
||||
volumes:
|
||||
- ./infra/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on: [api]
|
||||
networks: [backend]
|
||||
|
||||
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 }
|
||||
@@ -0,0 +1,21 @@
|
||||
module mtusi-messenger
|
||||
|
||||
go 1.22
|
||||
|
||||
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/sys v0.20.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
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/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/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/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/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,28 @@
|
||||
worker_processes auto;
|
||||
events { worker_connections 4096; }
|
||||
|
||||
http {
|
||||
# Docker's embedded DNS. nginx будет обращаться сюда за IP реплик.
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
|
||||
location / {
|
||||
set $api_backend http://api:8080;
|
||||
|
||||
proxy_pass $api_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_send_timeout 15s;
|
||||
proxy_read_timeout 15s;
|
||||
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,5 @@
|
||||
-- Индекс B для «стоимости записи»:
|
||||
-- покрывающий индекс, включающий text — растёт быстрее, помогает только
|
||||
-- покрывающим запросам.
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_covering
|
||||
ON messages (chat_id, created_at, id) INCLUDE (sender_id, text);
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
status_code INTEGER NOT NULL,
|
||||
response JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||
ON idempotency_keys (created_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
|
||||
|
||||
# ./scripts/restart.sh # 2 реплики (по умолчанию)
|
||||
# ./scripts/restart.sh 4 # 4 реплики
|
||||
REPLICAS="${1:-2}"
|
||||
|
||||
# Останов с сохранением volumes.
|
||||
docker compose down --remove-orphans
|
||||
|
||||
# Пересоздание сети + контейнеров с нужным числом реплик.
|
||||
API_REPLICAS="$REPLICAS" \
|
||||
docker compose --env-file .env -f compose.yaml up -d --build
|
||||
|
||||
# Ждём готовности с хоста.
|
||||
i=0
|
||||
while [ "$i" -lt 90 ]; do
|
||||
if curl -sf http://localhost:8080/health/ready >/dev/null 2>&1; then
|
||||
echo "ready after ${i}s (replicas=$REPLICAS)"
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "stack did not become ready in 90s" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Все контейнеры сервиса api (включая Exited).
|
||||
# `docker compose ps -a -q api` возвращает их ID.
|
||||
STOPPED=""
|
||||
for id in $(docker compose ps -a -q api); do
|
||||
state=$(docker inspect --format '{{.State.Status}}' "$id")
|
||||
if [ "$state" = "exited" ] || [ "$state" = "created" ]; then
|
||||
STOPPED="$STOPPED $id"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$STOPPED" ]; then
|
||||
echo "all api containers already running"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for id in $STOPPED; do
|
||||
hn=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
docker start "$id" >/dev/null
|
||||
echo "started $id ($hn)"
|
||||
done
|
||||
|
||||
# Дождаться, пока LB увидит их снова (curl с хоста).
|
||||
i=0
|
||||
while [ "$i" -lt 30 ]; do
|
||||
if curl -sf http://localhost:8080/health/ready >/dev/null 2>&1; then
|
||||
echo "ready after ${i}s"
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "stack did not become ready in 30s" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
# Находим ID контейнера, чьё имя (HOSTNAME) совпадает с TARGET_INSTANCE_ID.
|
||||
CID=$(docker compose ps -q api | while read -r id; do
|
||||
name=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$name" = "$TARGET_INSTANCE_ID" ]; then
|
||||
echo "$id"
|
||||
break
|
||||
fi
|
||||
done)
|
||||
|
||||
if [ -z "$CID" ]; then
|
||||
echo "container with hostname $TARGET_INSTANCE_ID not found" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
docker stop "$CID"
|
||||
echo "stopped $CID ($TARGET_INSTANCE_ID)"
|
||||
@@ -0,0 +1,79 @@
|
||||
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)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid session")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
// writeError пишет ошибку в формате контракта.
|
||||
func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(domain.ErrorBody{
|
||||
Error: domain.ErrorDetail{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestIDFrom(r),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// writeJSON пишет успешный JSON-ответ.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"mtusi-messenger/src/domain"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type Handler struct {
|
||||
Store *domain.Store
|
||||
Sessions *domain.SessionStore
|
||||
}
|
||||
|
||||
// --- Health ---
|
||||
|
||||
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"})
|
||||
}
|
||||
|
||||
// --- Users ---
|
||||
|
||||
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 := decodeSingleJSON(r.Body, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
// Пароль: 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)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username taken")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.VerifyPassword(r.Context(), username, password)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
s, err := h.Sessions.Create(r.Context(), *u)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTimeout) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store timeout")
|
||||
return
|
||||
}
|
||||
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 {
|
||||
if errors.Is(err, domain.ErrTimeout) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store timeout")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
// --- Chats ---
|
||||
|
||||
type createChatReq struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
var req createChatReq
|
||||
if err := decodeSingleJSON(r.Body, &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)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid members")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
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) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
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")
|
||||
chats, next, err := h.Store.ListChats(r.Context(), me.ID, limit, cursor)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.ChatPage{Items: chats, NextCursor: next})
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chatID := r.PathValue("chat_id")
|
||||
c, err := h.Store.GetChat(r.Context(), chatID, me.ID)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat_id")
|
||||
return
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
|
||||
type createMessageReq struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
// Idempotency-Key обязателен.
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "Idempotency-Key required")
|
||||
return
|
||||
}
|
||||
if !idempotencyKeyRe.MatchString(key) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid Idempotency-Key")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.Store.GetChat(r.Context(), chatID, me.ID); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat_id")
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Читаем тело один раз и хешируем нормализованный JSON.
|
||||
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 64*1024))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "cannot read body")
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
if err := decodeSingleJSON(bytes.NewReader(rawBody), &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
|
||||
}
|
||||
bodyHash, err := domain.HashBody(rawBody)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
|
||||
msg, rec, replay, err := h.Store.AddMessageIdempotent(
|
||||
r.Context(), chatID, me.ID, req.Text, key, bodyHash)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if replay {
|
||||
// Возвращаем сохранённый 201 и то же Message.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(rec.StatusCode)
|
||||
_, _ = w.Write(rec.Response)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, msg)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat_id")
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
}
|
||||
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")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
items, next, err := h.Store.ListMessages(r.Context(), chatID, limit, cursor)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "query timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.MessagePage{Items: items, NextCursor: next})
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
func decodeSingleJSON(r io.Reader, v any) error {
|
||||
dec := json.NewDecoder(r)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
if dec.More() {
|
||||
return errors.New("trailing data after JSON value")
|
||||
}
|
||||
// Пробуем прочитать ещё один токен — если это не EOF, значит есть мусор.
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); err != io.EOF {
|
||||
return errors.New("trailing data after JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey string
|
||||
|
||||
const (
|
||||
requestIDKey ctxKey = "request_id"
|
||||
userKey ctxKey = "user"
|
||||
tokenKey ctxKey = "token"
|
||||
)
|
||||
|
||||
func requestIDFrom(r *http.Request) string {
|
||||
if v, ok := r.Context().Value(requestIDKey).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// withInstanceID ставит X-Instance-Id на КАЖДЫЙ ответ (включая ошибки и health).
|
||||
// ID генерируется один раз при старте процесса — стабилен в пределах жизни.
|
||||
func withInstanceID(instanceID string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package api
|
||||
|
||||
import "net/http"
|
||||
|
||||
func NewRouter(h *Handler, instanceID string) 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)
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.ListMessages)
|
||||
|
||||
// Порядок: instanceID снаружи, requestID внутри.
|
||||
return withInstanceID(instanceID)(withRequestID(mux))
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
SessionStore string // "postgres" | "redis"
|
||||
RedisRequired bool
|
||||
InstanceID string
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
port := 8080
|
||||
if v := os.Getenv("APP_PORT"); v != "" {
|
||||
if p, err := strconv.Atoi(v); err == nil {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
ttl := 3600
|
||||
if v := os.Getenv("SESSION_TTL_SECONDS"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
ttl = n
|
||||
}
|
||||
}
|
||||
|
||||
// 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"))
|
||||
}
|
||||
|
||||
instanceID := os.Getenv("INSTANCE_ID")
|
||||
if instanceID == "" {
|
||||
instanceID = os.Getenv("HOSTNAME")
|
||||
}
|
||||
if instanceID == "" {
|
||||
instanceID = "api-" + randomShortID()
|
||||
}
|
||||
|
||||
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",
|
||||
InstanceID: instanceID,
|
||||
}
|
||||
}
|
||||
|
||||
func randomShortID() string {
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
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
|
||||
}
|
||||
// Жёсткие короткие таймауты: Redis — кэш, а не критический путь.
|
||||
opt.DialTimeout = 1 * time.Second
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.MaxRetries = 0 // без автоматических ретраев: одна попытка — и уходим в БД
|
||||
opt.PoolTimeout = 1 * time.Second
|
||||
|
||||
rdb := redis.NewClient(opt)
|
||||
|
||||
// Проверка связи при старте — короткая.
|
||||
c, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
if err := rdb.Ping(c).Err(); err != nil {
|
||||
_ = rdb.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &SessionCache{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) userKey(userID string) string { return "user:" + userID }
|
||||
|
||||
// opCtx возвращает контекст с коротким таймаутом для каждой операции.
|
||||
// Не наследуем HTTP-контекст напрямую, чтобы не блокировать ответ клиенту.
|
||||
func (c *SessionCache) opCtx() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
}
|
||||
|
||||
// SetUser кладёт публичные данные пользователя в кэш с TTL до конца сессии.
|
||||
func (c *SessionCache) SetUser(ctx context.Context, userID string, u User, expires time.Time) {
|
||||
ttl := time.Until(expires)
|
||||
if ttl <= 0 {
|
||||
return
|
||||
}
|
||||
b, err := json.Marshal(u)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
_ = c.rdb.Set(opCtx, c.userKey(userID), b, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) GetUser(ctx context.Context, userID string) (User, bool) {
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
b, err := c.rdb.Get(opCtx, c.userKey(userID)).Bytes()
|
||||
if err != nil {
|
||||
return User{}, false
|
||||
}
|
||||
var u User
|
||||
if err := json.Unmarshal(b, &u); err != nil {
|
||||
return User{}, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
// DelUser — на случай удаления пользователя (в lab2 не вызывается).
|
||||
func (c *SessionCache) DelUser(ctx context.Context, userID string) error {
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
return c.rdb.Del(opCtx, c.userKey(userID)).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
c2, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
return c.rdb.Ping(c2).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error { return c.rdb.Close() }
|
||||
@@ -0,0 +1,75 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// IdempotencyRecord — сохранённый результат POST.
|
||||
type IdempotencyRecord struct {
|
||||
StatusCode int
|
||||
Response json.RawMessage
|
||||
}
|
||||
|
||||
// LookupIdempotency возвращает запись, если ключ уже использован.
|
||||
// Второй аргумент — совпадает ли хеш тела с сохранённым.
|
||||
func (s *Store) LookupIdempotency(ctx context.Context, userID, method, path, key, bodyHash string) (*IdempotencyRecord, bool, error) {
|
||||
var (
|
||||
storedHash string
|
||||
rec IdempotencyRecord
|
||||
)
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method=$2 AND path=$3 AND key=$4`,
|
||||
userID, method, path, key,
|
||||
).Scan(&storedHash, &rec.StatusCode, &rec.Response)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, classifyDBError(err)
|
||||
}
|
||||
if storedHash != bodyHash {
|
||||
return nil, true, ErrConflict
|
||||
}
|
||||
return &rec, true, nil
|
||||
}
|
||||
|
||||
// SaveIdempotency пишет результат. Конфликт PK означает, что параллельный
|
||||
// запрос успел раньше — вызывающий должен перечитать через LookupIdempotency.
|
||||
func (s *Store) SaveIdempotency(ctx context.Context, userID, method, path, key, bodyHash string, status int, resp json.RawMessage) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
||||
userID, method, path, key, bodyHash, status, resp)
|
||||
return classifyDBError(err)
|
||||
}
|
||||
|
||||
// HashBody — стабильный хеш JSON независимо от порядка ключей.
|
||||
func HashBody(raw []byte) (string, error) {
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return "", err
|
||||
}
|
||||
normalized, err := json.Marshal(v) // map keys сортируются
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(normalized)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
// CleanupIdempotency — можно звать из фонового тикера (опционально).
|
||||
func (s *Store) CleanupIdempotency(ctx context.Context, olderThan time.Duration) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM idempotency_keys WHERE created_at < now() - $1::interval`,
|
||||
olderThan.String())
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message 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"`
|
||||
}
|
||||
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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")
|
||||
ErrTimeout = errors.New("timeout")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
@@ -0,0 +1,572 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
|
||||
"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/argon2"
|
||||
)
|
||||
|
||||
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, classifyDBError(err)
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = time.Hour
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
_, err := conn.Exec(ctx, `
|
||||
SET statement_timeout = '5s';
|
||||
SET lock_timeout = '2s';
|
||||
SET idle_in_transaction_session_timeout = '5s';
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(ctxPing); err != nil {
|
||||
pool.Close()
|
||||
return nil, classifyDBError(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)
|
||||
}
|
||||
|
||||
// Argon2id параметры — OWASP baseline: m=19456 KiB (19 MiB), t=2, p=1.
|
||||
// Хеш кодируется в формате PHC: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
|
||||
const (
|
||||
argonMemory uint32 = 19456
|
||||
argonTime uint32 = 2
|
||||
argonThreads uint8 = 1
|
||||
argonKeyLen uint32 = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
b64Key := base64.RawStdEncoding.EncodeToString(key)
|
||||
// PHC string; параметры можно будет менять в будущем, старые хеши останутся валидными.
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
argonMemory, argonTime, argonThreads, b64Salt, b64Key), nil
|
||||
}
|
||||
|
||||
func verifyPassword(password, encoded string) bool {
|
||||
// Минимальный парсер PHC-строки.
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
var mem, time uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &time, &threads); err != nil {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
gotKey := argon2.IDKey([]byte(password), salt, time, mem, threads, uint32(len(wantKey)))
|
||||
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1
|
||||
}
|
||||
|
||||
// --- Users ---
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(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, classifyDBError(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, classifyDBError(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) {
|
||||
// Тратим сопоставимое время на проверку фиктивного хеша,
|
||||
// чтобы не различать "нет пользователя" и "неверный пароль" по таймингу.
|
||||
_ = verifyPassword(password, "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if !verifyPassword(password, hash) {
|
||||
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, classifyDBError(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, classifyDBError(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, classifyDBError(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, classifyDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, classifyDBError(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, classifyDBError(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, classifyDBError(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, classifyDBError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
return &c, rows.Err()
|
||||
}
|
||||
|
||||
// ListChats возвращает чаты пользователя с keyset-пагинацией по (created_at, id).
|
||||
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cursor string) ([]Chat, *string, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
|
||||
if cursor == "" {
|
||||
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
|
||||
LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
var cCreated time.Time
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT created_at FROM chats WHERE id=$1`, cursor,
|
||||
).Scan(&cCreated); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, ErrInvalid
|
||||
}
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
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
|
||||
AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, cCreated, cursor, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, classifyDBError(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, nil, classifyDBError(err)
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(chats) > limit {
|
||||
chats = chats[:limit]
|
||||
last := chats[len(chats)-1].ID
|
||||
next = &last
|
||||
}
|
||||
if chats == nil {
|
||||
chats = []Chat{}
|
||||
}
|
||||
|
||||
// Догружаем участников.
|
||||
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, nil, classifyDBError(err)
|
||||
}
|
||||
for mrows.Next() {
|
||||
var uid string
|
||||
if err := mrows.Scan(&uid); err != nil {
|
||||
mrows.Close()
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
chats[i].MemberIDs = append(chats[i].MemberIDs, uid)
|
||||
}
|
||||
mrows.Close()
|
||||
}
|
||||
return chats, next, 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, classifyDBError(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, classifyDBError(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, classifyDBError(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, classifyDBError(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, classifyDBError(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, classifyDBError(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, classifyDBError(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, classifyDBError(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
|
||||
}
|
||||
|
||||
func classifyDBError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "57014": // query_canceled (statement_timeout)
|
||||
return ErrTimeout
|
||||
case "55P03": // lock_not_available (lock_timeout)
|
||||
return ErrTimeout
|
||||
case "40001": // serialization_failure
|
||||
return ErrUnavailable
|
||||
case "53300": // too_many_connections
|
||||
return ErrUnavailable
|
||||
case "22P02", "22007", "22023": // invalid_text_representation / invalid_datetime_format / invalid_parameter_value
|
||||
return ErrInvalid
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return ErrTimeout
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AddMessageIdempotent — атомарно проверяет членство, вставляет сообщение
|
||||
// и сохраняет результат идемпотентности в одной транзакции.
|
||||
// Если ключ уже есть с тем же body — возвращает сохранённый ответ и replay=true.
|
||||
func (s *Store) AddMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID, text, key, bodyHash string,
|
||||
) (msg *Message, rec *IdempotencyRecord, replay bool, err error) {
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
|
||||
if err != nil {
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// 1) Членство.
|
||||
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, nil, false, ErrNotFound
|
||||
}
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 2) Уже был такой ключ?
|
||||
var storedHash string
|
||||
var storedStatus int
|
||||
var storedResp json.RawMessage
|
||||
err = tx.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
||||
senderID, path, key,
|
||||
).Scan(&storedHash, &storedStatus, &storedResp)
|
||||
switch {
|
||||
case err == nil:
|
||||
if storedHash != bodyHash {
|
||||
return nil, nil, false, ErrConflict
|
||||
}
|
||||
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 3) Вставка сообщения.
|
||||
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 {
|
||||
// Гонка на одном ключе в разных репликах: unique violation в idempotency_keys
|
||||
// маловероятен здесь, но serialization failure возможен.
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 4) Сохранение ответа.
|
||||
respJSON, _ := json.Marshal(m)
|
||||
_, err = tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
|
||||
VALUES ($1,'POST',$2,$3,$4,201,$5)`,
|
||||
senderID, path, key, bodyHash, respJSON)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
// Кто-то параллельно успел вставить: перечитываем в этой же tx.
|
||||
if err2 := tx.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
||||
senderID, path, key,
|
||||
).Scan(&storedHash, &storedStatus, &storedResp); err2 == nil {
|
||||
if storedHash != bodyHash {
|
||||
return nil, nil, false, ErrConflict
|
||||
}
|
||||
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
||||
}
|
||||
}
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
return &m, nil, false, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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 "", classifyDBError(err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Create — пишем сессию в БД (источник истины) и кэшируем публичные данные User.
|
||||
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
expires := time.Now().UTC().Add(s.ttl)
|
||||
if _, err := s.store.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
|
||||
token, user.ID, expires); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.SetUser(ctx, user.ID, user, expires)
|
||||
}
|
||||
return &Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expires,
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Lookup ВСЕГДА обращается к PostgreSQL за фактом существования сессии.
|
||||
// Кэш используется только для публичных данных User.
|
||||
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
|
||||
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, classifyDBError(err)
|
||||
}
|
||||
if time.Now().UTC().After(expiresAt) {
|
||||
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
if u, ok := s.cache.GetUser(ctx, userID); ok {
|
||||
return &u, nil
|
||||
}
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.SetUser(ctx, userID, *u, expiresAt)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
|
||||
var userID string
|
||||
err := s.store.pool.QueryRow(ctx,
|
||||
`DELETE FROM sessions WHERE token=$1 RETURNING user_id`, token,
|
||||
).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Сессии уже нет — с точки зрения клиента токен отозван.
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return classifyDBError(err)
|
||||
}
|
||||
if s.cache != nil {
|
||||
// Кэш User не критичен, но полезно сбросить.
|
||||
_ = s.cache.DelUser(ctx, userID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user