lab4: вложения в S3 (MinIO), reconciler PostgreSQL↔S3, тесты и CI
This commit is contained in:
@@ -18,3 +18,5 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
bin
|
||||
experiments
|
||||
|
||||
+7
-1
@@ -7,7 +7,7 @@ SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
SESSION_STORE=redis
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
@@ -18,3 +18,9 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
# Graceful shutdown: after SIGTERM readiness=503 for DRAIN_DELAY, then Shutdown up to SHUTDOWN_TIMEOUT.
|
||||
DRAIN_DELAY=3s
|
||||
SHUTDOWN_TIMEOUT=8s
|
||||
# Reconciler (PostgreSQL <-> S3): background pass interval and safe grace period.
|
||||
RECONCILE_INTERVAL=10m
|
||||
RECONCILE_GRACE=1h
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Реальный прогон Docker-стенда lab4 на GitHub-hosted runner.
|
||||
# Нужен потому, что на машине разработки нет аппаратной виртуализации для Docker Desktop.
|
||||
# Три независимых стенда параллельно; все результаты — настоящие прогоны.
|
||||
name: lab4 stand
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [lab4]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: lab4-stand-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
PYTHONUTF8: "1"
|
||||
|
||||
jobs:
|
||||
stand:
|
||||
name: Стенд — ${{ matrix.part }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
part: [base, files, track2]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Unit-тесты Go
|
||||
if: matrix.part == 'base'
|
||||
run: |
|
||||
mkdir -p evidence
|
||||
go test ./... 2>&1 | tee evidence/go_test.txt
|
||||
- name: Секреты и запуск стенда
|
||||
run: |
|
||||
chmod +x scripts/*.sh infra/s3/init.sh
|
||||
sh scripts/init-secrets.sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
docker compose logs --no-color s3-init
|
||||
- name: make check + доказательства (${{ matrix.part }})
|
||||
run: |
|
||||
make check PYTHON=python
|
||||
PYTHON=python sh scripts/collect-evidence.sh ${{ matrix.part }}
|
||||
- name: Окружение runner
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p evidence
|
||||
{ nproc; free -m; docker version --format '{{.Server.Version}}'; docker compose version; } > evidence/runner_${{ matrix.part }}.txt
|
||||
docker compose ps -a > evidence/docker_ps_final_${{ matrix.part }}.txt || true
|
||||
docker compose logs --no-color s3-init reconciler > evidence/s3init_reconciler_${{ matrix.part }}.log 2>&1 || true
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: evidence-${{ matrix.part }}
|
||||
path: evidence/
|
||||
|
||||
# api.github.com недоступен из сети разработчика, а github.com (git) — доступен,
|
||||
# поэтому артефакты публикуются в ветку lab4-results.
|
||||
publish:
|
||||
name: Публикация результатов в ветку lab4-results
|
||||
needs: [stand]
|
||||
if: always()
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: collected
|
||||
- name: Commit в lab4-results
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git checkout -q --orphan lab4-results
|
||||
git rm -rf -q .
|
||||
{ echo "source_commit=${{ github.sha }}"
|
||||
echo "run=${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
echo "stand=${{ needs.stand.result }}"; } > collected/RUN.txt
|
||||
cp -r collected/. .
|
||||
rm -rf collected
|
||||
git add -A
|
||||
git commit -q -m "results for ${{ github.sha }}"
|
||||
git push -f origin lab4-results
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# ============================================================
|
||||
# Stage 1: builder — компилируем статический бинарник
|
||||
# ============================================================
|
||||
FROM golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba AS builder
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
# Сначала манифесты зависимостей — кэшируем слой.
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Затем исходники.
|
||||
COPY . .
|
||||
|
||||
# Статический бинарник с оптимизациями:
|
||||
# CGO_ENABLED=0 — статическая линковка (не требует libc)
|
||||
# -ldflags="-s -w" — убираем отладочную информацию
|
||||
# -trimpath — убираем пути сборки из бинарника
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o /out/ \
|
||||
./cmd/api ./cmd/reconcile
|
||||
|
||||
# ============================================================
|
||||
# Stage 2: runtime — минимальный образ только с бинарником
|
||||
# ============================================================
|
||||
FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
|
||||
|
||||
# ca-certificates — для HTTPS в lab2+
|
||||
# tzdata — для корректной работы с временными зонами
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
|
||||
# Непривилегированный пользователь (UID/GID 1001).
|
||||
RUN addgroup -g 1001 -S appgroup && \
|
||||
adduser -u 1001 -S appuser -G appgroup
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Копируем бинарник и сразу выставляем владельца.
|
||||
COPY --from=builder --chown=appuser:appgroup /out/api /app/api
|
||||
# reconcile — сверка PostgreSQL и S3 (сервис reconciler и ручной запуск).
|
||||
COPY --from=builder --chown=appuser:appgroup /out/reconcile /app/reconcile
|
||||
|
||||
# Переключаемся на непривилегированного пользователя.
|
||||
USER 1001:1001
|
||||
|
||||
# Информативно: какой порт слушает приложение.
|
||||
EXPOSE 8080
|
||||
|
||||
# Healthcheck: readiness (БД + Redis + не в режиме drain).
|
||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \
|
||||
CMD wget --spider -q http://localhost:8080/health/ready || exit 1
|
||||
|
||||
# Exec-форма CMD — критично для доставки SIGTERM в приложение.
|
||||
CMD ["/app/api"]
|
||||
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover up down test-files test-reconcile reconcile-dry reconcile-apply evidence
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -28,3 +28,26 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# --- Студенческие цели (lab4) ---
|
||||
up:
|
||||
sh scripts/init-secrets.sh
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
|
||||
down:
|
||||
docker compose --env-file .env stop
|
||||
|
||||
test-files:
|
||||
$(PYTHON) student-tests/attachments_negative.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-reconcile:
|
||||
$(PYTHON) student-tests/reconcile_faults.py --base-url "$(BASE_URL)"
|
||||
|
||||
reconcile-dry:
|
||||
docker compose run --rm --no-deps --entrypoint /app/reconcile reconciler
|
||||
|
||||
reconcile-apply:
|
||||
docker compose run --rm --no-deps --entrypoint /app/reconcile reconciler --apply
|
||||
|
||||
evidence:
|
||||
sh scripts/collect-evidence.sh all
|
||||
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/config"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository/postgres"
|
||||
redisrepo "github.com/charawein/mtusi2026lab4/internal/repository/redis"
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/storage"
|
||||
transporthttp "github.com/charawein/mtusi2026lab4/internal/transport/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
if cfg.DatabaseURL == "" {
|
||||
slog.Error("DATABASE_URL_FILE is not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
if cfg.CacheURL == "" {
|
||||
slog.Error("CACHE_URL_FILE is not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, cfg.DBPoolMax)
|
||||
cancel()
|
||||
if err != nil {
|
||||
slog.Error("connect to postgres", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
redisClient, err := redisrepo.NewClient(rctx, cfg.CacheURL)
|
||||
rcancel()
|
||||
if err != nil {
|
||||
slog.Error("connect to redis", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer redisClient.Close()
|
||||
|
||||
if cfg.S3AccessKey == "" || cfg.S3SecretKey == "" {
|
||||
slog.Error("S3_ACCESS_KEY_ID_FILE / S3_SECRET_ACCESS_KEY_FILE are not set or empty")
|
||||
os.Exit(1)
|
||||
}
|
||||
store, err := storage.NewS3(cfg.S3Endpoint, cfg.S3Region, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey)
|
||||
if err != nil {
|
||||
slog.Error("s3 client", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userRepo := postgres.NewUserRepository(pool)
|
||||
chatRepo := postgres.NewChatRepository(pool)
|
||||
msgRepo := postgres.NewMessageRepository(pool)
|
||||
sessRepo := redisrepo.NewSessionRepository(redisClient)
|
||||
|
||||
userSvc := service.NewUserService(userRepo)
|
||||
chatSvc := service.NewChatService(chatRepo, userRepo)
|
||||
|
||||
var msgCache *redisrepo.MessageCache
|
||||
if cfg.CacheEnabled {
|
||||
msgCache = redisrepo.NewMessageCache(redisClient, cfg.CacheInvalidation)
|
||||
}
|
||||
msgSvc := service.NewMessageService(msgRepo, chatRepo, msgCache, cfg.IdempotencyTTL)
|
||||
|
||||
attSvc := service.NewAttachmentService(postgres.NewAttachmentRepository(pool), chatRepo, store,
|
||||
cfg.MaxUploadBytes, cfg.MaxImagePixels)
|
||||
authSvc := service.NewAuthService(userRepo, sessRepo, cfg.SessionTTL())
|
||||
|
||||
// draining выставляется по SIGTERM: /health/ready начинает отвечать 503,
|
||||
// LB исключает реплику, и только затем закрывается listener.
|
||||
var draining atomic.Bool
|
||||
router := transporthttp.NewRouter(userSvc, chatSvc, msgSvc, attSvc, authSvc, pool, redisClient, cfg.InstanceID, &draining)
|
||||
|
||||
// Очистка просроченных ключей идемпотентности. Запрос идемпотентен,
|
||||
// поэтому параллельный запуск на всех репликах безопасен.
|
||||
cleanupCtx, cleanupStop := context.WithCancel(context.Background())
|
||||
defer cleanupStop()
|
||||
go func() {
|
||||
t := time.NewTicker(time.Hour)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-cleanupCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
ctx, cancel := context.WithTimeout(cleanupCtx, 30*time.Second)
|
||||
if n, err := msgRepo.DeleteExpiredKeys(ctx, cfg.IdempotencyTTL); err != nil {
|
||||
slog.Warn("idempotency cleanup failed", "err", err)
|
||||
} else if n > 0 {
|
||||
slog.Info("idempotency keys expired", "deleted", n)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
// Загрузка до 10 MiB должна уложиться в ReadTimeout; медленный клиент
|
||||
// дольше не держит соединение и память.
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 35 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Внутренний endpoint метрик для экспериментов (трек 1). Порт не публикуется
|
||||
// и не проксируется LB: читается только через docker exec внутри контейнера.
|
||||
internalSrv := &http.Server{
|
||||
Addr: cfg.InternalAddr,
|
||||
Handler: transporthttp.NewInternalStatsHandler(pool, cfg),
|
||||
ReadHeaderTimeout: 2 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
if err := internalSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Warn("internal stats server failed", "err", err)
|
||||
}
|
||||
}()
|
||||
defer internalSrv.Close()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
slog.Info("server starting", "addr", cfg.Addr(), "instance_id", cfg.InstanceID)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
sigCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
slog.Error("server failed", "err", err)
|
||||
os.Exit(1)
|
||||
case <-sigCtx.Done():
|
||||
slog.Info("shutdown signal received, draining", "delay", cfg.DrainDelay)
|
||||
}
|
||||
|
||||
// Перестаём быть ready и даём LB время заметить это (inter*fall у HAProxy),
|
||||
// продолжая обслуживать уже направленные к нам запросы.
|
||||
draining.Store(true)
|
||||
time.Sleep(cfg.DrainDelay)
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
slog.Error("graceful shutdown failed", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("server stopped")
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Command reconcile сверяет PostgreSQL и S3 и безопасно убирает расхождения.
|
||||
//
|
||||
// reconcile # dry-run, grace 1h, отчёт JSON в stdout
|
||||
// reconcile --apply # исправить
|
||||
// reconcile --apply --interval 10m # фоновый режим (сервис reconciler в compose)
|
||||
//
|
||||
// Grace period должен быть больше максимальной длительности загрузки
|
||||
// (ReadTimeout 30 s + PUT) с запасом на расхождение часов; значения < 5m
|
||||
// разрешены только с --unsafe-short-grace (для тестов).
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/config"
|
||||
"github.com/charawein/mtusi2026lab4/internal/reconcile"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository/postgres"
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "apply fixes (default: dry-run, report only)")
|
||||
grace := flag.Duration("grace", time.Hour, "do not touch objects/intents/quarantine younger than this")
|
||||
unsafe := flag.Bool("unsafe-short-grace", false, "allow grace < 5m (tests only)")
|
||||
interval := flag.Duration("interval", 0, "repeat every interval (0 = run once)")
|
||||
flag.Parse()
|
||||
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil)))
|
||||
if *grace < 5*time.Minute && !*unsafe {
|
||||
fmt.Fprintln(os.Stderr, "grace < 5m is unsafe: in-flight uploads could be deleted; pass --unsafe-short-grace for tests")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
cfg := config.Load()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, 4)
|
||||
if err != nil {
|
||||
slog.Error("connect to postgres", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
store, err := storage.NewS3(cfg.S3Endpoint, cfg.S3Region, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey)
|
||||
if err != nil {
|
||||
slog.Error("s3 client", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
repo := postgres.NewAttachmentRepository(pool)
|
||||
|
||||
runOnce := func() int {
|
||||
unlock, ok, err := repo.TryLock(ctx)
|
||||
if err != nil {
|
||||
slog.Error("advisory lock", "err", err)
|
||||
return 1
|
||||
}
|
||||
if !ok {
|
||||
slog.Warn("another reconciler is running, skipping this pass")
|
||||
return 3
|
||||
}
|
||||
defer unlock()
|
||||
var now time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT now()`).Scan(&now); err != nil {
|
||||
slog.Error("db time", "err", err)
|
||||
return 1
|
||||
}
|
||||
rep, err := reconcile.Run(ctx, repo, store, reconcile.Options{
|
||||
Prefix: service.ObjectPrefix, Grace: *grace, Apply: *apply, Now: now,
|
||||
})
|
||||
out, _ := json.Marshal(rep)
|
||||
fmt.Println(string(out))
|
||||
if err != nil {
|
||||
slog.Error("reconcile pass failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
slog.Info("reconcile pass done", "dry_run", rep.DryRun, "found", rep.Found, "fixed", rep.Fixed,
|
||||
"rows", rep.RowsScanned, "objects", rep.ObjectsScanned, "ms", rep.DurationMS)
|
||||
if len(rep.Errors) > 0 {
|
||||
return 4
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
if *interval <= 0 {
|
||||
os.Exit(runOnce())
|
||||
}
|
||||
t := time.NewTicker(*interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
runOnce()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
# Lab4: клиент → HAProxy → API × N → PostgreSQL (данные и метаданные вложений), Redis (сессии, кэш)
|
||||
# и приватный S3 (MinIO) для байтов вложений.
|
||||
# Запуск: scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait
|
||||
name: mtusi2026lab4
|
||||
|
||||
x-api-env: &api-env
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: ${SESSION_STORE:-redis}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DRAIN_DELAY: ${DRAIN_DELAY:-3s}
|
||||
SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-8s}
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-20}
|
||||
CACHE_INVALIDATION: ${CACHE_INVALIDATION:-version}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.0.5-alpine
|
||||
ports:
|
||||
- "127.0.0.1:${LB_PORT:-8080}:8080"
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
|
||||
environment:
|
||||
LB_BALANCE: ${LB_BALANCE:-roundrobin}
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks: [front]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${LB_CPUS:-0.50}", memory: 128M }
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi2026lab4-api:local
|
||||
# Без container_name и без ports: реплики доступны только через lb.
|
||||
environment: *api-env
|
||||
secrets: [database_url, cache_url, s3_access_key_id, s3_secret_access_key]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/health/ready"]
|
||||
interval: 5s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
# DRAIN_DELAY + SHUTDOWN_TIMEOUT < stop_grace_period, иначе SIGKILL оборвёт запросы.
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
networks: [front, back]
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: { cpus: "${API_CPUS:-0.50}", memory: "${API_MEMORY:-256M}" }
|
||||
|
||||
# Однократные миграции до старта API: реплики не гоняются за схему.
|
||||
migrate:
|
||||
image: migrate/migrate:v4.17.0
|
||||
volumes:
|
||||
- ./migrations:/migrations:ro
|
||||
secrets: [database_url]
|
||||
entrypoint: ["/bin/sh", "-c", "exec migrate -path /migrations -database \"$$(cat /run/secrets/database_url)\" up"]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
networks: [back]
|
||||
|
||||
postgres:
|
||||
image: postgres:16.4-alpine
|
||||
command: ["postgres", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"]
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_DB: messenger
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pg_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${PG_CPUS:-1.00}", memory: "${PG_MEMORY:-512M}" }
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${REDIS_CPUS:-0.50}", memory: 256M }
|
||||
|
||||
# S3-совместимое хранилище байтов вложений. Порты не публикуются, консоль
|
||||
# выключена (MINIO_BROWSER=off): доступ только из сети back.
|
||||
s3:
|
||||
image: minio/minio:RELEASE.2025-04-22T22-12-26Z
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- export MINIO_ROOT_USER="$$(cat /run/secrets/s3_root_user)" MINIO_ROOT_PASSWORD="$$(cat /run/secrets/s3_root_password)"; exec minio server /data --address :9000
|
||||
environment:
|
||||
MINIO_BROWSER: "off"
|
||||
secrets: [s3_root_user, s3_root_password]
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "${S3_CPUS:-0.50}", memory: 512M }
|
||||
|
||||
# Идемпотентный bootstrap: приватный bucket, политика и отдельный пользователь
|
||||
# API с правами только на этот bucket. Root-учётка есть только у s3 и s3-init.
|
||||
s3-init:
|
||||
image: minio/mc:RELEASE.2025-04-16T18-13-26Z
|
||||
entrypoint: ["/bin/sh", "/init/init.sh"]
|
||||
environment:
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
secrets: [s3_root_user, s3_root_password, s3_access_key_id, s3_secret_access_key]
|
||||
volumes:
|
||||
- ./infra/s3:/init:ro
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
networks: [back]
|
||||
|
||||
# Сверка PostgreSQL и S3: брошенные загрузки, сироты, потерянные объекты.
|
||||
# Безопасный grace period 1h; одновременно работает один экземпляр (advisory lock).
|
||||
reconciler:
|
||||
image: mtusi2026lab4-api:local
|
||||
entrypoint: ["/app/reconcile", "--apply", "--interval", "${RECONCILE_INTERVAL:-10m}", "--grace", "${RECONCILE_GRACE:-1h}"]
|
||||
environment: *api-env
|
||||
secrets: [database_url, s3_access_key_id, s3_secret_access_key]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
networks: [back]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
|
||||
networks:
|
||||
# front: lb ↔ api; back: api ↔ хранилища. LB не видит БД и S3.
|
||||
front:
|
||||
back:
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
s3_root_user:
|
||||
file: ./secrets/s3_root_user
|
||||
s3_root_password:
|
||||
file: ./secrets/s3_root_password
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
|
||||
volumes:
|
||||
s3_data:
|
||||
pg_data:
|
||||
redis_data:
|
||||
@@ -0,0 +1,35 @@
|
||||
module github.com/charawein/mtusi2026lab4
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/minio-go/v7 v7.4.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.4 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
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.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
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-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
|
||||
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
|
||||
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
|
||||
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,59 @@
|
||||
# HAProxy — единственная публичная точка входа (lab3).
|
||||
# Backend-адреса берутся из встроенного DNS Docker (service name "api"),
|
||||
# поэтому масштабирование/пересоздание реплик не требует перезапуска LB.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 2048
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 15s
|
||||
timeout http-request 10s
|
||||
timeout queue 5s
|
||||
# Повтор только при ошибке установки соединения (запрос ещё не отправлен),
|
||||
# поэтому неидемпотентные POST /users, /chats не дублируются.
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
option redispatch 1
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
# Как долго держать последний ответ DNS при ошибке/пропаже записи.
|
||||
hold valid 5s
|
||||
hold other 5s
|
||||
hold refused 5s
|
||||
hold nx 2s
|
||||
hold timeout 5s
|
||||
hold obsolete 2s
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
# roundrobin по умолчанию; leastconn — вариант для эксперимента трека 1 (env LB_BALANCE).
|
||||
balance "${LB_BALANCE}"
|
||||
# Активная проверка готовности: 503 во время drain или без БД/Redis.
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
# Период проверки 1s, исключение после 2 неудач (~2s), возврат после 2 успехов.
|
||||
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
||||
# До 8 слотов под реплики сервиса api; лишние слоты остаются в MAINT.
|
||||
server-template api 8 api:8080
|
||||
|
||||
frontend stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентный bootstrap MinIO: повторный запуск ничего не ломает и не стирает данные.
|
||||
# 1. приватный bucket (anonymous access: none);
|
||||
# 2. политика messenger-api: только Get/Put/Delete объектов и List этого bucket;
|
||||
# 3. отдельный пользователь API с этой политикой (root-ключ API не получает).
|
||||
# Секреты читаются из /run/secrets и не печатаются.
|
||||
set -eu
|
||||
: "${S3_BUCKET:?}"
|
||||
ROOT_USER=$(cat /run/secrets/s3_root_user)
|
||||
ROOT_PASS=$(cat /run/secrets/s3_root_password)
|
||||
API_KEY=$(cat /run/secrets/s3_access_key_id)
|
||||
API_SECRET=$(cat /run/secrets/s3_secret_access_key)
|
||||
|
||||
mc alias set local http://s3:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null
|
||||
mc mb --ignore-existing "local/$S3_BUCKET"
|
||||
mc anonymous set none "local/$S3_BUCKET" >/dev/null
|
||||
|
||||
cat > /tmp/messenger-api.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::$S3_BUCKET"]},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::$S3_BUCKET/*"]}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
mc admin policy create local messenger-api /tmp/messenger-api.json >/dev/null
|
||||
# user add для существующего пользователя обновляет секрет — повтор безопасен.
|
||||
mc admin user add local "$API_KEY" "$API_SECRET" >/dev/null
|
||||
if ! mc admin policy entities local --user "$API_KEY" 2>/dev/null | grep -q messenger-api; then
|
||||
mc admin policy attach local messenger-api --user "$API_KEY" >/dev/null
|
||||
fi
|
||||
echo "s3 bootstrap ok: bucket=$S3_BUCKET private, api user with messenger-api policy"
|
||||
@@ -0,0 +1,127 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTLSeconds int
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionStore string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
CacheEnabled bool
|
||||
InstanceID string
|
||||
IdempotencyTTL time.Duration
|
||||
DrainDelay time.Duration
|
||||
DBPoolMax int32
|
||||
CacheInvalidation string
|
||||
InternalAddr string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
return Config{
|
||||
Host: getEnv("APP_HOST", "0.0.0.0"),
|
||||
Port: getEnv("APP_PORT", "8080"),
|
||||
Env: getEnv("APP_ENV", "lab"),
|
||||
SessionTTLSeconds: getInt("SESSION_TTL_SECONDS", 3600),
|
||||
DatabaseURL: readSecretFile("DATABASE_URL_FILE"),
|
||||
CacheURL: readSecretFile("CACHE_URL_FILE"),
|
||||
SessionStore: getEnv("SESSION_STORE", "postgres"),
|
||||
LogLevel: parseLevel(getEnv("LOG_LEVEL", "info")),
|
||||
ShutdownTimeout: parseDuration(getEnv("SHUTDOWN_TIMEOUT", "8s")),
|
||||
CacheEnabled: getEnv("CACHE_ENABLED", "true") == "true",
|
||||
InstanceID: instanceID(),
|
||||
IdempotencyTTL: time.Duration(getInt("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second,
|
||||
DrainDelay: parseDuration(getEnv("DRAIN_DELAY", "3s")),
|
||||
DBPoolMax: int32(max(1, getInt("DB_POOL_MAX", 20))),
|
||||
CacheInvalidation: getEnv("CACHE_INVALIDATION", "version"),
|
||||
InternalAddr: getEnv("INTERNAL_ADDR", ":9090"),
|
||||
S3Endpoint: getEnv("S3_ENDPOINT", "http://s3:9000"),
|
||||
S3Region: getEnv("S3_REGION", "us-east-1"),
|
||||
S3Bucket: getEnv("S3_BUCKET", "messenger-attachments"),
|
||||
S3AccessKey: readSecretFile("S3_ACCESS_KEY_ID_FILE"),
|
||||
S3SecretKey: readSecretFile("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
MaxUploadBytes: int64(getInt("MAX_UPLOAD_BYTES", 10*1024*1024)),
|
||||
MaxImagePixels: int64(getInt("MAX_IMAGE_PIXELS", 40_000_000)),
|
||||
}
|
||||
}
|
||||
|
||||
// instanceID — идентификатор реплики для X-Instance-Id. По умолчанию hostname,
|
||||
// который в Docker равен короткому ID контейнера: так stop-one.sh однозначно
|
||||
// находит контейнер. В lab7 его заменит непрозрачный alias.
|
||||
func instanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if h, err := os.Hostname(); err == nil && h != "" {
|
||||
return h
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func (c Config) SessionTTL() time.Duration {
|
||||
return time.Duration(c.SessionTTLSeconds) * time.Second
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return c.Host + ":" + c.Port }
|
||||
|
||||
func getEnv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getInt(key string, def int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readSecretFile(envKey string) string {
|
||||
path := os.Getenv(envKey)
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
slog.Warn("secret file not readable", "path", path, "err", err)
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func parseLevel(s string) slog.Level {
|
||||
var l slog.Level
|
||||
if err := l.UnmarshalText([]byte(s)); err != nil {
|
||||
return slog.LevelInfo
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func parseDuration(s string) time.Duration {
|
||||
d, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return 8 * time.Second
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AttachmentUploading = "uploading"
|
||||
AttachmentReady = "ready"
|
||||
AttachmentMissing = "missing"
|
||||
)
|
||||
|
||||
// Attachment — метаданные вложения. ObjectKey никогда не уходит клиенту.
|
||||
type Attachment struct {
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ObjectKey string
|
||||
Status string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// MarshalJSON — представление по контракту lab4: только ready, вариантов нет.
|
||||
func (a Attachment) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []string `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}{
|
||||
ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename,
|
||||
ContentType: a.ContentType, SizeBytes: a.SizeBytes, SHA256: a.SHA256,
|
||||
Status: a.Status, Variants: []string{}, ErrorCode: nil,
|
||||
CreatedAt: a.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
UpdatedAt: a.UpdatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
type Alias Chat
|
||||
members := c.MemberIDs
|
||||
if members == nil {
|
||||
members = []string{}
|
||||
}
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(c),
|
||||
MemberIDs: members,
|
||||
CreatedAt: c.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
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"`
|
||||
// AttachmentIDs — в порядке отправки; всегда массив (пустой, если вложений нет).
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
type Alias Message
|
||||
if m.AttachmentIDs == nil {
|
||||
m.AttachmentIDs = []string{}
|
||||
}
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(m),
|
||||
CreatedAt: m.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"-"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MarshalJSON форматирует CreatedAt в RFC3339 без микросекунд.
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
type Alias User
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(u),
|
||||
CreatedAt: u.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
// Package imagecheck потоково проверяет PNG/JPEG без декодирования пикселей.
|
||||
//
|
||||
// Проверка идёт по мере чтения (используется параллельно с PUT в S3), память
|
||||
// O(1) от размера изображения: размеры берутся из заголовка (IHDR/SOF) и
|
||||
// сравниваются с лимитом до чтения тела; PNG — CRC каждого chunk и длина
|
||||
// распакованного IDAT-потока (zlib → io.Discard), JPEG — структура сегментов
|
||||
// и маркер EOI. «Заведомо повреждённые» файлы (обрыв, битый CRC, мусор вместо
|
||||
// данных, чужой формат) дают ErrInvalid, слишком большие по пикселям — ErrTooLarge.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
)
|
||||
|
||||
const (
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid or unsupported image")
|
||||
ErrTooLarge = errors.New("image dimensions exceed limit")
|
||||
)
|
||||
|
||||
var pngSignature = []byte("\x89PNG\r\n\x1a\n")
|
||||
|
||||
// Sniff определяет формат по первым байтам (не по заголовку Content-Type клиента).
|
||||
func Sniff(head []byte) (string, bool) {
|
||||
switch {
|
||||
case bytes.HasPrefix(head, pngSignature):
|
||||
return PNG, true
|
||||
case len(head) >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF:
|
||||
return JPEG, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Result — что удалось узнать при проверке.
|
||||
type Result struct {
|
||||
Format string
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
// Validate читает r до конца и проверяет изображение формата format.
|
||||
// maxPixels ограничивает width*height. Хвост после конца изображения
|
||||
// дочитывается и игнорируется, чтобы не блокировать писателя.
|
||||
func Validate(r io.Reader, format string, maxPixels int64) (Result, error) {
|
||||
br := bufio.NewReaderSize(r, 32*1024)
|
||||
var res Result
|
||||
var err error
|
||||
switch format {
|
||||
case PNG:
|
||||
res, err = validatePNG(br, maxPixels)
|
||||
case JPEG:
|
||||
res, err = validateJPEG(br, maxPixels)
|
||||
default:
|
||||
return Result{}, ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, br)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func invalid(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// --- PNG ---
|
||||
|
||||
func channels(colorType byte) (int, bool) {
|
||||
switch colorType {
|
||||
case 0:
|
||||
return 1, true // grayscale
|
||||
case 2:
|
||||
return 3, true // RGB
|
||||
case 3:
|
||||
return 1, true // palette
|
||||
case 4:
|
||||
return 2, true // gray + alpha
|
||||
case 6:
|
||||
return 4, true // RGBA
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func validBitDepth(colorType, depth byte) bool {
|
||||
switch colorType {
|
||||
case 0:
|
||||
return depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16
|
||||
case 3:
|
||||
return depth == 1 || depth == 2 || depth == 4 || depth == 8
|
||||
case 2, 4, 6:
|
||||
return depth == 8 || depth == 16
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// expectedRaw — длина распакованного потока IDAT: строки с байтом фильтра.
|
||||
func expectedRaw(w, h int64, bitsPerPixel int64, interlaced bool) int64 {
|
||||
row := func(pw int64) int64 { return 1 + (pw*bitsPerPixel+7)/8 }
|
||||
if !interlaced {
|
||||
return h * row(w)
|
||||
}
|
||||
passes := [7][4]int64{{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}}
|
||||
var total int64
|
||||
for _, p := range passes {
|
||||
if w <= p[0] || h <= p[1] {
|
||||
continue
|
||||
}
|
||||
pw := (w - p[0] + p[2] - 1) / p[2]
|
||||
ph := (h - p[1] + p[3] - 1) / p[3]
|
||||
total += ph * row(pw)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
type pngChunk struct {
|
||||
length uint32
|
||||
typ [4]byte
|
||||
}
|
||||
|
||||
func readChunkHeader(br *bufio.Reader) (pngChunk, error) {
|
||||
var hdr [8]byte
|
||||
if _, err := io.ReadFull(br, hdr[:]); err != nil {
|
||||
return pngChunk{}, invalid("truncated chunk header")
|
||||
}
|
||||
c := pngChunk{length: binary.BigEndian.Uint32(hdr[:4])}
|
||||
copy(c.typ[:], hdr[4:])
|
||||
if c.length > 1<<31-1 {
|
||||
return c, invalid("chunk too long")
|
||||
}
|
||||
for _, b := range c.typ {
|
||||
if !((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z')) {
|
||||
return c, invalid("bad chunk type")
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// readChunkData читает тело chunk в dst (если не nil) и проверяет CRC.
|
||||
func readChunkData(br *bufio.Reader, c pngChunk, dst io.Writer) error {
|
||||
h := crc32.NewIEEE()
|
||||
h.Write(c.typ[:])
|
||||
w := io.Writer(h)
|
||||
if dst != nil {
|
||||
w = io.MultiWriter(h, dst)
|
||||
}
|
||||
if _, err := io.CopyN(w, br, int64(c.length)); err != nil {
|
||||
return invalid("truncated %s chunk", c.typ[:])
|
||||
}
|
||||
var crc [4]byte
|
||||
if _, err := io.ReadFull(br, crc[:]); err != nil {
|
||||
return invalid("truncated CRC")
|
||||
}
|
||||
if binary.BigEndian.Uint32(crc[:]) != h.Sum32() {
|
||||
return invalid("CRC mismatch in %s", c.typ[:])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// idatStream отдаёт данные подряд идущих IDAT-chunk как один поток.
|
||||
type idatStream struct {
|
||||
br *bufio.Reader
|
||||
remaining uint32
|
||||
crc uint32
|
||||
next *pngChunk // первый chunk после последнего IDAT
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *idatStream) Read(p []byte) (int, error) {
|
||||
for s.remaining == 0 {
|
||||
if s.err != nil || s.next != nil {
|
||||
if s.err != nil {
|
||||
return 0, s.err
|
||||
}
|
||||
return 0, io.EOF
|
||||
}
|
||||
if err := s.finishChunk(); err != nil {
|
||||
s.err = err
|
||||
return 0, err
|
||||
}
|
||||
c, err := readChunkHeader(s.br)
|
||||
if err != nil {
|
||||
s.err = err
|
||||
return 0, err
|
||||
}
|
||||
if string(c.typ[:]) != "IDAT" {
|
||||
s.next = &c
|
||||
return 0, io.EOF
|
||||
}
|
||||
s.startChunk(c)
|
||||
}
|
||||
if uint32(len(p)) > s.remaining {
|
||||
p = p[:s.remaining]
|
||||
}
|
||||
n, err := s.br.Read(p)
|
||||
s.crc = crc32.Update(s.crc, crc32.IEEETable, p[:n])
|
||||
s.remaining -= uint32(n)
|
||||
if err != nil && err != io.EOF {
|
||||
s.err = err
|
||||
return n, err
|
||||
}
|
||||
if n == 0 && err == io.EOF {
|
||||
s.err = invalid("truncated IDAT")
|
||||
return 0, s.err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *idatStream) startChunk(c pngChunk) {
|
||||
s.remaining = c.length
|
||||
s.crc = crc32.Update(0, crc32.IEEETable, c.typ[:])
|
||||
}
|
||||
|
||||
func (s *idatStream) finishChunk() error {
|
||||
var crc [4]byte
|
||||
if _, err := io.ReadFull(s.br, crc[:]); err != nil {
|
||||
return invalid("truncated CRC")
|
||||
}
|
||||
if binary.BigEndian.Uint32(crc[:]) != s.crc {
|
||||
return invalid("CRC mismatch in IDAT")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePNG(br *bufio.Reader, maxPixels int64) (Result, error) {
|
||||
res := Result{Format: PNG}
|
||||
sig := make([]byte, 8)
|
||||
if _, err := io.ReadFull(br, sig); err != nil || !bytes.Equal(sig, pngSignature) {
|
||||
return res, invalid("not a PNG")
|
||||
}
|
||||
c, err := readChunkHeader(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if string(c.typ[:]) != "IHDR" || c.length != 13 {
|
||||
return res, invalid("IHDR must be first")
|
||||
}
|
||||
var ihdr bytes.Buffer
|
||||
if err := readChunkData(br, c, &ihdr); err != nil {
|
||||
return res, err
|
||||
}
|
||||
b := ihdr.Bytes()
|
||||
w := int64(binary.BigEndian.Uint32(b[0:4]))
|
||||
h := int64(binary.BigEndian.Uint32(b[4:8]))
|
||||
depth, colorType, compression, filter, interlace := b[8], b[9], b[10], b[11], b[12]
|
||||
res.Width, res.Height = int(w), int(h)
|
||||
if w < 1 || h < 1 || w > 1<<31-1 || h > 1<<31-1 {
|
||||
return res, invalid("bad dimensions")
|
||||
}
|
||||
// Лимит пикселей — до чтения и распаковки данных изображения.
|
||||
if w*h > maxPixels {
|
||||
return res, ErrTooLarge
|
||||
}
|
||||
ch, ok := channels(colorType)
|
||||
if !ok || !validBitDepth(colorType, depth) || compression != 0 || filter != 0 || interlace > 1 {
|
||||
return res, invalid("unsupported IHDR")
|
||||
}
|
||||
want := expectedRaw(w, h, int64(ch)*int64(depth), interlace == 1)
|
||||
|
||||
sawIDAT := false
|
||||
for {
|
||||
c, err := readChunkHeader(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
switch string(c.typ[:]) {
|
||||
case "IDAT":
|
||||
if sawIDAT {
|
||||
return res, invalid("non-consecutive IDAT")
|
||||
}
|
||||
sawIDAT = true
|
||||
s := &idatStream{br: br}
|
||||
s.startChunk(c)
|
||||
zr, err := zlib.NewReader(s)
|
||||
if err != nil {
|
||||
return res, invalid("bad zlib header")
|
||||
}
|
||||
// Распаковка в никуда: проверяем длину без хранения пикселей.
|
||||
n, err := io.Copy(io.Discard, io.LimitReader(zr, want+1))
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrInvalid) {
|
||||
return res, err
|
||||
}
|
||||
return res, invalid("corrupt image data")
|
||||
}
|
||||
if n != want {
|
||||
return res, invalid("image data length %d, want %d", n, want)
|
||||
}
|
||||
// Остаток IDAT (например, пустые chunk) дочитываем с проверкой CRC.
|
||||
if _, err := io.Copy(io.Discard, s); err != nil {
|
||||
return res, err
|
||||
}
|
||||
if s.next == nil {
|
||||
return res, invalid("missing IEND")
|
||||
}
|
||||
c = *s.next
|
||||
if string(c.typ[:]) == "IEND" {
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
case "IEND":
|
||||
if !sawIDAT {
|
||||
return res, invalid("no image data")
|
||||
}
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
case "IHDR":
|
||||
return res, invalid("duplicate IHDR")
|
||||
default:
|
||||
if err := readChunkData(br, c, nil); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- JPEG ---
|
||||
|
||||
func isSOF(m byte) bool {
|
||||
switch m {
|
||||
case 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readMarker читает 0xFF (с заполнителями) и код маркера.
|
||||
func readMarker(br *bufio.Reader) (byte, error) {
|
||||
b, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return 0, invalid("truncated JPEG")
|
||||
}
|
||||
if b != 0xFF {
|
||||
return 0, invalid("expected JPEG marker")
|
||||
}
|
||||
for b == 0xFF {
|
||||
if b, err = br.ReadByte(); err != nil {
|
||||
return 0, invalid("truncated JPEG")
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func segmentLength(br *bufio.Reader) (int, error) {
|
||||
var l [2]byte
|
||||
if _, err := io.ReadFull(br, l[:]); err != nil {
|
||||
return 0, invalid("truncated JPEG segment")
|
||||
}
|
||||
n := int(binary.BigEndian.Uint16(l[:]))
|
||||
if n < 2 {
|
||||
return 0, invalid("bad JPEG segment length")
|
||||
}
|
||||
return n - 2, nil
|
||||
}
|
||||
|
||||
// skipEntropy пропускает сжатые данные скана и возвращает следующий маркер.
|
||||
func skipEntropy(br *bufio.Reader) (byte, error) {
|
||||
for {
|
||||
b, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return 0, invalid("truncated JPEG scan")
|
||||
}
|
||||
if b != 0xFF {
|
||||
continue
|
||||
}
|
||||
for b == 0xFF {
|
||||
if b, err = br.ReadByte(); err != nil {
|
||||
return 0, invalid("truncated JPEG scan")
|
||||
}
|
||||
}
|
||||
if b == 0x00 || (b >= 0xD0 && b <= 0xD7) {
|
||||
continue // байт-заполнитель или RSTn внутри скана
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
}
|
||||
|
||||
func validateJPEG(br *bufio.Reader, maxPixels int64) (Result, error) {
|
||||
res := Result{Format: JPEG}
|
||||
var soi [2]byte
|
||||
if _, err := io.ReadFull(br, soi[:]); err != nil || soi != [2]byte{0xFF, 0xD8} {
|
||||
return res, invalid("not a JPEG")
|
||||
}
|
||||
sawSOF, sawSOS := false, false
|
||||
marker, err := readMarker(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
for {
|
||||
switch {
|
||||
case marker == 0xD9: // EOI
|
||||
if !sawSOF || !sawSOS {
|
||||
return res, invalid("JPEG without frame or scan")
|
||||
}
|
||||
return res, nil
|
||||
case marker == 0xD8:
|
||||
return res, invalid("unexpected SOI")
|
||||
case marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7):
|
||||
// маркеры без длины
|
||||
case isSOF(marker):
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if n < 6 {
|
||||
return res, invalid("short SOF")
|
||||
}
|
||||
hdr := make([]byte, 5)
|
||||
if _, err := io.ReadFull(br, hdr); err != nil {
|
||||
return res, invalid("truncated SOF")
|
||||
}
|
||||
h := int64(binary.BigEndian.Uint16(hdr[1:3]))
|
||||
w := int64(binary.BigEndian.Uint16(hdr[3:5]))
|
||||
res.Width, res.Height = int(w), int(h)
|
||||
if w < 1 || h < 1 {
|
||||
return res, invalid("bad JPEG dimensions")
|
||||
}
|
||||
if w*h > maxPixels {
|
||||
return res, ErrTooLarge
|
||||
}
|
||||
if sawSOF {
|
||||
return res, invalid("multiple frames")
|
||||
}
|
||||
sawSOF = true
|
||||
if _, err := br.Discard(n - 5); err != nil {
|
||||
return res, invalid("truncated SOF")
|
||||
}
|
||||
case marker == 0xDA: // SOS
|
||||
if !sawSOF {
|
||||
return res, invalid("scan before frame")
|
||||
}
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if _, err := br.Discard(n); err != nil {
|
||||
return res, invalid("truncated SOS")
|
||||
}
|
||||
sawSOS = true
|
||||
if marker, err = skipEntropy(br); err != nil {
|
||||
return res, err
|
||||
}
|
||||
continue
|
||||
default:
|
||||
n, err := segmentLength(br)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if _, err := br.Discard(n); err != nil {
|
||||
return res, invalid("truncated JPEG segment")
|
||||
}
|
||||
}
|
||||
if marker, err = readMarker(br); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const limit = 40_000_000
|
||||
|
||||
func testImage(w, h int) *image.RGBA {
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x * 7), uint8(y * 3), uint8(x ^ y), 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func encodePNG(t *testing.T, w, h int) []byte {
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, testImage(w, h)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func encodeJPEG(t *testing.T, w, h int, progressive bool) []byte {
|
||||
var b bytes.Buffer
|
||||
if err := jpeg.Encode(&b, testImage(w, h), &jpeg.Options{Quality: 80}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func chunk(typ string, data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
binary.Write(&b, binary.BigEndian, uint32(len(data)))
|
||||
b.WriteString(typ)
|
||||
b.Write(data)
|
||||
crc := crc32.NewIEEE()
|
||||
crc.Write([]byte(typ))
|
||||
crc.Write(data)
|
||||
binary.Write(&b, binary.BigEndian, crc.Sum32())
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// craftPNG собирает PNG вручную: так можно задать любые IHDR и поток данных.
|
||||
func craftPNG(w, h uint32, colorType, depth, interlace byte, raw []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
b.Write(pngSignature)
|
||||
ihdr := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(ihdr[0:], w)
|
||||
binary.BigEndian.PutUint32(ihdr[4:], h)
|
||||
ihdr[8], ihdr[9], ihdr[12] = depth, colorType, interlace
|
||||
b.Write(chunk("IHDR", ihdr))
|
||||
var z bytes.Buffer
|
||||
zw := zlib.NewWriter(&z)
|
||||
zw.Write(raw)
|
||||
zw.Close()
|
||||
b.Write(chunk("IDAT", z.Bytes()))
|
||||
b.Write(chunk("IEND", nil))
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func check(t *testing.T, name string, data []byte, format string, want error) {
|
||||
t.Helper()
|
||||
_, err := Validate(bytes.NewReader(data), format, limit)
|
||||
if want == nil && err != nil {
|
||||
t.Errorf("%s: unexpected error %v", name, err)
|
||||
}
|
||||
if want != nil && !errors.Is(err, want) {
|
||||
t.Errorf("%s: got %v, want %v", name, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPNGAndJPEG(t *testing.T) {
|
||||
p := encodePNG(t, 320, 200)
|
||||
res, err := Validate(bytes.NewReader(p), PNG, limit)
|
||||
if err != nil || res.Width != 320 || res.Height != 200 {
|
||||
t.Fatalf("png: %+v %v", res, err)
|
||||
}
|
||||
j := encodeJPEG(t, 321, 199, false)
|
||||
res, err = Validate(bytes.NewReader(j), JPEG, limit)
|
||||
if err != nil || res.Width != 321 || res.Height != 199 {
|
||||
t.Fatalf("jpeg: %+v %v", res, err)
|
||||
}
|
||||
check(t, "png with trailing bytes", append(p, []byte("trailer")...), PNG, nil)
|
||||
}
|
||||
|
||||
func TestCourseFixture(t *testing.T) {
|
||||
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
||||
if err != nil {
|
||||
t.Skip("fixture not found")
|
||||
}
|
||||
res, err := Validate(bytes.NewReader(data), PNG, limit)
|
||||
if err != nil || res.Width != 320 || res.Height != 200 {
|
||||
t.Fatalf("fixture: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterlacedPNG(t *testing.T) {
|
||||
// 10×7 RGB, Adam7: длина сырых данных по семи проходам.
|
||||
w, h := int64(10), int64(7)
|
||||
raw := make([]byte, expectedRaw(w, h, 24, true))
|
||||
check(t, "interlaced", craftPNG(uint32(w), uint32(h), 2, 8, 1, raw), PNG, nil)
|
||||
check(t, "interlaced short data", craftPNG(uint32(w), uint32(h), 2, 8, 1, raw[:len(raw)-1]), PNG, ErrInvalid)
|
||||
}
|
||||
|
||||
func TestBrokenImages(t *testing.T) {
|
||||
p := encodePNG(t, 64, 64)
|
||||
j := encodeJPEG(t, 64, 64, false)
|
||||
|
||||
check(t, "png truncated", p[:len(p)/2], PNG, ErrInvalid)
|
||||
check(t, "png without IEND", p[:len(p)-12], PNG, ErrInvalid)
|
||||
bad := bytes.Clone(p)
|
||||
bad[len(bad)/2] ^= 0xFF
|
||||
check(t, "png corrupted byte", bad, PNG, ErrInvalid)
|
||||
check(t, "jpeg truncated", j[:len(j)/2], JPEG, ErrInvalid)
|
||||
check(t, "jpeg without EOI", j[:len(j)-2], JPEG, ErrInvalid)
|
||||
check(t, "png declared as jpeg", p, JPEG, ErrInvalid)
|
||||
check(t, "text as png", []byte("hello, not an image at all"), PNG, ErrInvalid)
|
||||
check(t, "empty", nil, PNG, ErrInvalid)
|
||||
check(t, "png short raw data", craftPNG(8, 8, 2, 8, 0, make([]byte, 8*(1+24)-1)), PNG, ErrInvalid)
|
||||
check(t, "png bad bit depth", craftPNG(8, 8, 2, 4, 0, make([]byte, 8*(1+12))), PNG, ErrInvalid)
|
||||
}
|
||||
|
||||
func TestPixelLimitBeforeData(t *testing.T) {
|
||||
// «Бомба»: IHDR на 100000×100000, данных почти нет. Должно быть ErrTooLarge,
|
||||
// а не попытка распаковать 30 ГБ.
|
||||
bomb := craftPNG(100000, 100000, 2, 8, 0, []byte{0})
|
||||
check(t, "png bomb", bomb, PNG, ErrTooLarge)
|
||||
// Ровно на границе лимита — допустимо по пикселям (данных не хватает → invalid).
|
||||
check(t, "png at limit", craftPNG(8000, 5000, 0, 1, 0, nil), PNG, ErrInvalid)
|
||||
check(t, "png over limit", craftPNG(8000, 5001, 0, 1, 0, nil), PNG, ErrTooLarge)
|
||||
|
||||
// JPEG: подменяем размеры в SOF0 на 60000×60000.
|
||||
j := encodeJPEG(t, 16, 16, false)
|
||||
i := bytes.Index(j, []byte{0xFF, 0xC0})
|
||||
if i < 0 {
|
||||
t.Fatal("no SOF0")
|
||||
}
|
||||
big := bytes.Clone(j)
|
||||
binary.BigEndian.PutUint16(big[i+5:], 60000)
|
||||
binary.BigEndian.PutUint16(big[i+7:], 60000)
|
||||
check(t, "jpeg bomb", big, JPEG, ErrTooLarge)
|
||||
}
|
||||
|
||||
func TestSniff(t *testing.T) {
|
||||
if f, ok := Sniff(encodePNG(t, 2, 2)); !ok || f != PNG {
|
||||
t.Error("png sniff")
|
||||
}
|
||||
if f, ok := Sniff(encodeJPEG(t, 2, 2, false)); !ok || f != JPEG {
|
||||
t.Error("jpeg sniff")
|
||||
}
|
||||
if _, ok := Sniff([]byte("GIF89a")); ok {
|
||||
t.Error("gif must not be accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// Package reconcile сверяет метаданные вложений (PostgreSQL) и объекты (S3).
|
||||
//
|
||||
// Обход — один merge-проход по двум потокам, отсортированным одинаково
|
||||
// (object_key COLLATE "C" и лексикографический листинг S3), поэтому память
|
||||
// O(1) от числа вложений, а стоимость — O(N) строк + ceil(N/1000) LIST-запросов.
|
||||
//
|
||||
// Расхождения и безопасные действия:
|
||||
//
|
||||
// stale_intent строка uploading старше grace (брошенная загрузка) → удалить объект, затем строку
|
||||
// orphan_object объект без строки, старше grace → удалить объект (после перепроверки строки)
|
||||
// missing_object строка ready без объекта → карантин: status=missing (после перепроверки Stat)
|
||||
// size_mismatch строка ready, размер объекта другой → карантин: status=missing
|
||||
// restored строка missing, объект снова есть и размер совпадает → status=ready
|
||||
// purge_missing строка missing старше grace, ни одно сообщение не ссылается → удалить строку
|
||||
//
|
||||
// Свежие объекты и намерения (моложе grace) и вложения, на которые ссылаются
|
||||
// сообщения, не удаляются никогда. Режим по умолчанию — dry-run (только отчёт).
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/storage"
|
||||
)
|
||||
|
||||
// Repo — нужные reconciler операции над метаданными.
|
||||
type Repo interface {
|
||||
StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error
|
||||
HasKey(ctx context.Context, key string) (bool, error)
|
||||
DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||||
SetStatus(ctx context.Context, id, from, to string) (bool, error)
|
||||
DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error)
|
||||
IsReferenced(ctx context.Context, id string) (bool, error)
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Prefix string
|
||||
Grace time.Duration
|
||||
Apply bool
|
||||
Now time.Time // общий «сейчас» для строк и объектов (время БД)
|
||||
// MaxItems ограничивает список примеров в отчёте на каждый вид расхождения.
|
||||
MaxItems int
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
Kind string `json:"kind"`
|
||||
Key string `json:"key"`
|
||||
AttachmentID string `json:"attachment_id,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GraceSeconds float64 `json:"grace_seconds"`
|
||||
Cutoff time.Time `json:"cutoff"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
RowsScanned int `json:"rows_scanned"`
|
||||
ObjectsScanned int `json:"objects_scanned"`
|
||||
Consistent int `json:"consistent"`
|
||||
Found map[string]int `json:"found"`
|
||||
Fixed map[string]int `json:"fixed"`
|
||||
Skipped map[string]int `json:"skipped"`
|
||||
Calls map[string]int `json:"calls"`
|
||||
HeapAllocMB float64 `json:"heap_alloc_mb"`
|
||||
Errors []string `json:"errors"`
|
||||
Items []Item `json:"items"`
|
||||
}
|
||||
|
||||
type reconciler struct {
|
||||
repo Repo
|
||||
store storage.Store
|
||||
opt Options
|
||||
rep *Report
|
||||
items map[string]int
|
||||
}
|
||||
|
||||
func (r *reconciler) note(kind string, it Item) {
|
||||
r.rep.Found[kind]++
|
||||
if r.items[kind] < r.opt.MaxItems {
|
||||
r.items[kind]++
|
||||
r.rep.Items = append(r.rep.Items, it)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) fail(format string, args ...any) {
|
||||
if len(r.rep.Errors) < 100 {
|
||||
r.rep.Errors = append(r.rep.Errors, fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
// Run выполняет один проход. Ошибки отдельных действий попадают в отчёт и не
|
||||
// прерывают обход; ошибка листинга/запроса прерывает проход целиком.
|
||||
func Run(ctx context.Context, repo Repo, store storage.Store, opt Options) (*Report, error) {
|
||||
start := time.Now()
|
||||
if opt.MaxItems == 0 {
|
||||
opt.MaxItems = 50
|
||||
}
|
||||
cutoff := opt.Now.Add(-opt.Grace)
|
||||
rep := &Report{
|
||||
DryRun: !opt.Apply, GraceSeconds: opt.Grace.Seconds(), Cutoff: cutoff,
|
||||
Found: map[string]int{}, Fixed: map[string]int{}, Skipped: map[string]int{}, Calls: map[string]int{},
|
||||
Errors: []string{}, Items: []Item{},
|
||||
}
|
||||
rc := &reconciler{repo: repo, store: store, opt: opt, rep: rep, items: map[string]int{}}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
objs := make(chan storage.Object, 512)
|
||||
objErr := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(objs)
|
||||
objErr <- store.List(ctx, opt.Prefix, func(o storage.Object) error {
|
||||
select {
|
||||
case objs <- o:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
}()
|
||||
rows := make(chan *domain.Attachment, 512)
|
||||
rowErr := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(rows)
|
||||
rowErr <- repo.StreamByKey(ctx, opt.Prefix, func(a *domain.Attachment) error {
|
||||
select {
|
||||
case rows <- a:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
}()
|
||||
|
||||
o, okO := <-objs
|
||||
a, okA := <-rows
|
||||
for okO || okA {
|
||||
switch {
|
||||
case okA && (!okO || a.ObjectKey < o.Key):
|
||||
rep.RowsScanned++
|
||||
rc.rowWithoutObject(ctx, a, cutoff)
|
||||
a, okA = <-rows
|
||||
case okO && (!okA || o.Key < a.ObjectKey):
|
||||
rep.ObjectsScanned++
|
||||
rc.objectWithoutRow(ctx, o, cutoff)
|
||||
o, okO = <-objs
|
||||
default:
|
||||
rep.RowsScanned++
|
||||
rep.ObjectsScanned++
|
||||
rc.both(ctx, a, o, cutoff)
|
||||
a, okA = <-rows
|
||||
o, okO = <-objs
|
||||
}
|
||||
}
|
||||
if err := <-objErr; err != nil {
|
||||
return rep, fmt.Errorf("list objects: %w", err)
|
||||
}
|
||||
if err := <-rowErr; err != nil {
|
||||
return rep, fmt.Errorf("stream rows: %w", err)
|
||||
}
|
||||
rep.Calls["s3_list_pages"] = (rep.ObjectsScanned + 999) / 1000
|
||||
var ms runtime.MemStats
|
||||
runtime.ReadMemStats(&ms)
|
||||
rep.HeapAllocMB = float64(ms.HeapAlloc) / (1 << 20)
|
||||
rep.DurationMS = time.Since(start).Milliseconds()
|
||||
return rep, nil
|
||||
}
|
||||
|
||||
func (r *reconciler) rowWithoutObject(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||||
switch a.Status {
|
||||
case domain.AttachmentUploading:
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_intent"]++ // загрузка может быть в процессе
|
||||
return
|
||||
}
|
||||
r.staleIntent(ctx, a, false)
|
||||
case domain.AttachmentReady:
|
||||
// Листинг мог начаться раньше, чем объект записан: перепроверяем точечно.
|
||||
if r.objectExists(ctx, a.ObjectKey) {
|
||||
r.rep.Skipped["recheck_object_present"]++
|
||||
return
|
||||
}
|
||||
r.quarantine(ctx, a, "missing_object", "")
|
||||
case domain.AttachmentMissing:
|
||||
r.purgeMissing(ctx, a, cutoff)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) objectWithoutRow(ctx context.Context, o storage.Object, cutoff time.Time) {
|
||||
if !o.LastModified.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_object"]++
|
||||
return
|
||||
}
|
||||
// Строка могла появиться после начала обхода — перепроверяем перед удалением.
|
||||
r.rep.Calls["db_haskey"]++
|
||||
has, err := r.repo.HasKey(ctx, o.Key)
|
||||
if err != nil {
|
||||
r.fail("haskey %s: %v", o.Key, err)
|
||||
return
|
||||
}
|
||||
if has {
|
||||
r.rep.Skipped["recheck_row_present"]++
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "orphan_object", Key: o.Key, Action: "delete_object",
|
||||
Detail: fmt.Sprintf("size=%d modified=%s", o.Size, o.LastModified.UTC().Format(time.RFC3339))}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_delete_object"
|
||||
r.note("orphan_object", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["s3_delete"]++
|
||||
if err := r.store.Delete(ctx, o.Key); err != nil {
|
||||
r.fail("delete orphan %s: %v", o.Key, err)
|
||||
return
|
||||
}
|
||||
r.note("orphan_object", it)
|
||||
r.rep.Fixed["orphan_object"]++
|
||||
}
|
||||
|
||||
func (r *reconciler) both(ctx context.Context, a *domain.Attachment, o storage.Object, cutoff time.Time) {
|
||||
switch a.Status {
|
||||
case domain.AttachmentUploading:
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_intent"]++
|
||||
return
|
||||
}
|
||||
r.staleIntent(ctx, a, true)
|
||||
case domain.AttachmentReady:
|
||||
if o.Size != a.SizeBytes {
|
||||
r.quarantine(ctx, a, "size_mismatch", fmt.Sprintf("db=%d s3=%d", a.SizeBytes, o.Size))
|
||||
return
|
||||
}
|
||||
r.rep.Consistent++
|
||||
case domain.AttachmentMissing:
|
||||
if o.Size != a.SizeBytes {
|
||||
r.purgeMissing(ctx, a, cutoff)
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "restored", Key: a.ObjectKey, AttachmentID: a.ID, Action: "set_ready"}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_set_ready"
|
||||
r.note("restored", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_update"]++
|
||||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentMissing, domain.AttachmentReady)
|
||||
if err != nil {
|
||||
r.fail("restore %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("restored", it)
|
||||
if ok {
|
||||
r.rep.Fixed["restored"]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) objectExists(ctx context.Context, key string) bool {
|
||||
r.rep.Calls["s3_stat"]++
|
||||
_, err := r.store.Stat(ctx, key)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
if !errors.Is(err, storage.ErrNotFound) {
|
||||
r.fail("stat %s: %v", key, err)
|
||||
return true // при ошибке хранилища ничего не трогаем
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *reconciler) staleIntent(ctx context.Context, a *domain.Attachment, hasObject bool) {
|
||||
it := Item{Kind: "stale_intent", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_intent",
|
||||
Detail: "updated_at=" + a.UpdatedAt.UTC().Format(time.RFC3339)}
|
||||
if hasObject {
|
||||
it.Action = "delete_object_and_intent"
|
||||
}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_" + it.Action
|
||||
r.note("stale_intent", it)
|
||||
return
|
||||
}
|
||||
// Сначала объект: если упадём между шагами, останется намерение без объекта,
|
||||
// и следующий проход его доберёт (обратный порядок оставил бы сироту без учёта).
|
||||
if hasObject {
|
||||
r.rep.Calls["s3_delete"]++
|
||||
if err := r.store.Delete(ctx, a.ObjectKey); err != nil {
|
||||
r.fail("delete intent object %s: %v", a.ObjectKey, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.rep.Calls["db_delete"]++
|
||||
ok, err := r.repo.DeleteStaleIntent(ctx, a.ID, r.opt.Now.Add(-r.opt.Grace))
|
||||
if err != nil {
|
||||
r.fail("delete intent %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("stale_intent", it)
|
||||
if ok {
|
||||
r.rep.Fixed["stale_intent"]++
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reconciler) quarantine(ctx context.Context, a *domain.Attachment, kind, detail string) {
|
||||
it := Item{Kind: kind, Key: a.ObjectKey, AttachmentID: a.ID, Action: "quarantine", Detail: detail}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_quarantine"
|
||||
r.note(kind, it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_update"]++
|
||||
ok, err := r.repo.SetStatus(ctx, a.ID, domain.AttachmentReady, domain.AttachmentMissing)
|
||||
if err != nil {
|
||||
r.fail("quarantine %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note(kind, it)
|
||||
if ok {
|
||||
r.rep.Fixed[kind]++
|
||||
}
|
||||
}
|
||||
|
||||
// purgeMissing удаляет запись карантина, только если она старше grace и на неё
|
||||
// не ссылается ни одно сообщение. Используемые вложения остаются (их история цела).
|
||||
func (r *reconciler) purgeMissing(ctx context.Context, a *domain.Attachment, cutoff time.Time) {
|
||||
if !a.UpdatedAt.Before(cutoff) {
|
||||
r.rep.Skipped["fresh_missing"]++
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_referenced"]++
|
||||
ref, err := r.repo.IsReferenced(ctx, a.ID)
|
||||
if err != nil {
|
||||
r.fail("referenced %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
if ref {
|
||||
r.rep.Skipped["referenced_missing_kept"]++
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "purge_missing", Key: a.ObjectKey, AttachmentID: a.ID, Action: "delete_row"}
|
||||
if !r.opt.Apply {
|
||||
it.Action = "would_delete_row"
|
||||
r.note("purge_missing", it)
|
||||
return
|
||||
}
|
||||
r.rep.Calls["db_delete"]++
|
||||
ok, err := r.repo.DeleteUnreferencedMissing(ctx, a.ID, cutoff)
|
||||
if err != nil {
|
||||
r.fail("purge %s: %v", a.ID, err)
|
||||
return
|
||||
}
|
||||
r.note("purge_missing", it)
|
||||
if ok {
|
||||
r.rep.Fixed["purge_missing"]++
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/storage"
|
||||
)
|
||||
|
||||
type fakeStore struct{ objs map[string]storage.Object }
|
||||
|
||||
func (f *fakeStore) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error {
|
||||
f.objs[key] = storage.Object{Key: key, Size: size, LastModified: time.Now()}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeStore) Get(context.Context, string) (io.ReadCloser, int64, error) {
|
||||
return io.NopCloser(bytes.NewReader(nil)), 0, nil
|
||||
}
|
||||
func (f *fakeStore) Stat(_ context.Context, key string) (storage.Object, error) {
|
||||
o, ok := f.objs[key]
|
||||
if !ok {
|
||||
return o, storage.ErrNotFound
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
func (f *fakeStore) Delete(_ context.Context, key string) error { delete(f.objs, key); return nil }
|
||||
func (f *fakeStore) List(_ context.Context, prefix string, fn func(storage.Object) error) error {
|
||||
keys := make([]string, 0, len(f.objs))
|
||||
for k := range f.objs {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if err := fn(f.objs[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeRepo struct {
|
||||
rows map[string]*domain.Attachment // by id
|
||||
refs map[string]bool
|
||||
}
|
||||
|
||||
func (f *fakeRepo) StreamByKey(_ context.Context, _ string, fn func(*domain.Attachment) error) error {
|
||||
list := make([]*domain.Attachment, 0, len(f.rows))
|
||||
for _, a := range f.rows {
|
||||
c := *a
|
||||
list = append(list, &c)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].ObjectKey < list[j].ObjectKey })
|
||||
for _, a := range list {
|
||||
if err := fn(a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) HasKey(_ context.Context, key string) (bool, error) {
|
||||
for _, a := range f.rows {
|
||||
if a.ObjectKey == key {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
func (f *fakeRepo) DeleteStaleIntent(_ context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != domain.AttachmentUploading || !a.UpdatedAt.Before(cutoff) {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, id)
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) SetStatus(_ context.Context, id, from, to string) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != from {
|
||||
return false, nil
|
||||
}
|
||||
a.Status = to
|
||||
a.UpdatedAt = now
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) DeleteUnreferencedMissing(_ context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
a, ok := f.rows[id]
|
||||
if !ok || a.Status != domain.AttachmentMissing || !a.UpdatedAt.Before(cutoff) || f.refs[id] {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, id)
|
||||
return true, nil
|
||||
}
|
||||
func (f *fakeRepo) IsReferenced(_ context.Context, id string) (bool, error) { return f.refs[id], nil }
|
||||
|
||||
var now = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
const grace = time.Hour
|
||||
|
||||
func old() time.Time { return now.Add(-2 * grace) }
|
||||
func fresh() time.Time { return now.Add(-time.Minute) }
|
||||
|
||||
func setup() (*fakeRepo, *fakeStore) {
|
||||
r := &fakeRepo{rows: map[string]*domain.Attachment{}, refs: map[string]bool{}}
|
||||
s := &fakeStore{objs: map[string]storage.Object{}}
|
||||
row := func(id, status string, size int64, at time.Time) {
|
||||
r.rows[id] = &domain.Attachment{ID: id, ObjectKey: "a/c/" + id, Status: status, SizeBytes: size, UpdatedAt: at}
|
||||
}
|
||||
obj := func(id string, size int64, at time.Time) {
|
||||
s.objs["a/c/"+id] = storage.Object{Key: "a/c/" + id, Size: size, LastModified: at}
|
||||
}
|
||||
// согласованное
|
||||
row("ok", domain.AttachmentReady, 10, old())
|
||||
obj("ok", 10, old())
|
||||
// брошенная загрузка с объектом и без
|
||||
row("stale1", domain.AttachmentUploading, 0, old())
|
||||
obj("stale1", 7, old())
|
||||
row("stale2", domain.AttachmentUploading, 0, old())
|
||||
// загрузка в процессе — не трогать
|
||||
row("inflight", domain.AttachmentUploading, 0, fresh())
|
||||
obj("inflight", 5, fresh())
|
||||
// сирота старая и свежая
|
||||
obj("orphan", 3, old())
|
||||
obj("orphan-fresh", 3, fresh())
|
||||
// ready без объекта: используемое и нет
|
||||
row("lost-used", domain.AttachmentReady, 9, old())
|
||||
r.refs["lost-used"] = true
|
||||
row("lost-free", domain.AttachmentReady, 9, old())
|
||||
// подменённый размер
|
||||
row("resized", domain.AttachmentReady, 10, old())
|
||||
obj("resized", 11, old())
|
||||
return r, s
|
||||
}
|
||||
|
||||
func run(t *testing.T, r *fakeRepo, s *fakeStore, apply bool, at time.Time) *Report {
|
||||
t.Helper()
|
||||
rep, err := Run(context.Background(), r, s, Options{Prefix: "a/", Grace: grace, Apply: apply, Now: at})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rep.Errors) > 0 {
|
||||
t.Fatalf("errors: %v", rep.Errors)
|
||||
}
|
||||
return rep
|
||||
}
|
||||
|
||||
func TestDryRunChangesNothing(t *testing.T) {
|
||||
r, s := setup()
|
||||
nRows, nObjs := len(r.rows), len(s.objs)
|
||||
rep := run(t, r, s, false, now)
|
||||
if len(r.rows) != nRows || len(s.objs) != nObjs || r.rows["lost-free"].Status != domain.AttachmentReady {
|
||||
t.Fatal("dry-run mutated state")
|
||||
}
|
||||
want := map[string]int{"stale_intent": 2, "orphan_object": 1, "missing_object": 2, "size_mismatch": 1}
|
||||
for k, v := range want {
|
||||
if rep.Found[k] != v {
|
||||
t.Errorf("found[%s]=%d want %d (%v)", k, rep.Found[k], v, rep.Found)
|
||||
}
|
||||
}
|
||||
if len(rep.Fixed) != 0 {
|
||||
t.Errorf("dry-run fixed %v", rep.Fixed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyFixesAndIsIdempotent(t *testing.T) {
|
||||
r, s := setup()
|
||||
run(t, r, s, true, now)
|
||||
|
||||
for _, id := range []string{"stale1", "stale2"} {
|
||||
if _, ok := r.rows[id]; ok {
|
||||
t.Errorf("stale intent %s not removed", id)
|
||||
}
|
||||
}
|
||||
if _, ok := s.objs["a/c/stale1"]; ok {
|
||||
t.Error("stale intent object not removed")
|
||||
}
|
||||
if _, ok := s.objs["a/c/orphan"]; ok {
|
||||
t.Error("old orphan not removed")
|
||||
}
|
||||
// Свежие — никогда.
|
||||
if _, ok := s.objs["a/c/orphan-fresh"]; !ok {
|
||||
t.Error("fresh orphan deleted")
|
||||
}
|
||||
if _, ok := r.rows["inflight"]; !ok {
|
||||
t.Error("in-flight intent deleted")
|
||||
}
|
||||
if _, ok := s.objs["a/c/inflight"]; !ok {
|
||||
t.Error("in-flight object deleted")
|
||||
}
|
||||
for _, id := range []string{"lost-used", "lost-free", "resized"} {
|
||||
if r.rows[id].Status != domain.AttachmentMissing {
|
||||
t.Errorf("%s not quarantined", id)
|
||||
}
|
||||
}
|
||||
if r.rows["ok"].Status != domain.AttachmentReady {
|
||||
t.Error("consistent row touched")
|
||||
}
|
||||
|
||||
// Повтор сразу: исправлять нечего, карантин ещё моложе grace.
|
||||
rep := run(t, r, s, true, now)
|
||||
if len(rep.Fixed) != 0 {
|
||||
t.Errorf("second pass fixed %v", rep.Fixed)
|
||||
}
|
||||
|
||||
// Через grace: неиспользуемая запись карантина удаляется, используемая остаётся.
|
||||
later := now.Add(2 * grace)
|
||||
run(t, r, s, true, later)
|
||||
if _, ok := r.rows["lost-free"]; ok {
|
||||
t.Error("unreferenced missing row not purged")
|
||||
}
|
||||
if _, ok := r.rows["lost-used"]; !ok {
|
||||
t.Error("referenced missing row deleted")
|
||||
}
|
||||
if _, ok := s.objs["a/c/orphan-fresh"]; ok {
|
||||
t.Error("orphan not removed after grace")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoredObjectLeavesQuarantine(t *testing.T) {
|
||||
r, s := setup()
|
||||
run(t, r, s, true, now)
|
||||
// Объект вернули (например, из бэкапа) с правильным размером.
|
||||
s.objs["a/c/lost-used"] = storage.Object{Key: "a/c/lost-used", Size: 9, LastModified: now}
|
||||
rep := run(t, r, s, true, now)
|
||||
if rep.Fixed["restored"] != 1 || r.rows["lost-used"].Status != domain.AttachmentReady {
|
||||
t.Errorf("restore failed: %v %s", rep.Fixed, r.rows["lost-used"].Status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type AttachmentRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentRepository(pool *pgxpool.Pool) *AttachmentRepository {
|
||||
return &AttachmentRepository{pool: pool}
|
||||
}
|
||||
|
||||
const attachmentColumns = `id, chat_id, owner_id, filename, object_key, status,
|
||||
COALESCE(content_type, ''), COALESCE(size_bytes, 0), COALESCE(sha256, ''), created_at, updated_at`
|
||||
|
||||
func scanAttachment(row pgx.Row) (*domain.Attachment, error) {
|
||||
var a domain.Attachment
|
||||
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.Status,
|
||||
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// CreateIntent записывает намерение загрузки (status=uploading) ДО записи в S3.
|
||||
func (r *AttachmentRepository) CreateIntent(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, 'uploading', $6, $6)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkReady переводит намерение в ready после успешного и проверенного PUT.
|
||||
// Если строки uploading уже нет (её убрал reconciler) — ErrNotFound.
|
||||
func (r *AttachmentRepository) MarkReady(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', content_type = $2, size_bytes = $3, sha256 = $4, updated_at = $5
|
||||
WHERE id = $1::uuid AND status = 'uploading'
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, a.ID, a.ContentType, a.SizeBytes, a.SHA256, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return repository.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteIntent убирает намерение, если загрузка не удалась (компенсация).
|
||||
func (r *AttachmentRepository) DeleteIntent(ctx context.Context, id string) error {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading'`
|
||||
if _, err := r.pool.Exec(ctx, q, id); err != nil {
|
||||
return fmt.Errorf("delete attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetForMember возвращает вложение, если пользователь — участник его чата.
|
||||
// Чужое и несуществующее вложение неразличимы (ErrNotFound).
|
||||
func (r *AttachmentRepository) GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error) {
|
||||
q := `SELECT ` + attachmentColumns + `
|
||||
FROM attachments a
|
||||
WHERE a.id = $1::uuid
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2::uuid)`
|
||||
a, err := scanAttachment(r.pool.QueryRow(ctx, q, id, userID))
|
||||
if err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, fmt.Errorf("select attachment: %w", err)
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// --- для reconciler ---
|
||||
|
||||
// StreamByKey отдаёт все строки в байтовом порядке object_key (как ListObjectsV2).
|
||||
func (r *AttachmentRepository) StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error {
|
||||
q := `SELECT ` + attachmentColumns + `
|
||||
FROM attachments
|
||||
WHERE starts_with(object_key, $1)
|
||||
ORDER BY object_key COLLATE "C"`
|
||||
rows, err := r.pool.Query(ctx, q, prefix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stream attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
a, err := scanAttachment(rows)
|
||||
if err != nil {
|
||||
return fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
if err := fn(a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
// HasKey — есть ли строка с этим object_key (повторная проверка перед удалением объекта).
|
||||
func (r *AttachmentRepository) HasKey(ctx context.Context, key string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// DeleteStaleIntent удаляет намерение, только если оно всё ещё uploading и старше cutoff.
|
||||
func (r *AttachmentRepository) DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading' AND updated_at < $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, cutoff)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// SetStatus меняет статус ready↔missing (карантин и восстановление).
|
||||
func (r *AttachmentRepository) SetStatus(ctx context.Context, id, from, to string) (bool, error) {
|
||||
const q = `UPDATE attachments SET status = $3, updated_at = now() WHERE id = $1::uuid AND status = $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, from, to)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// DeleteUnreferencedMissing удаляет запись карантина старше cutoff, если на неё
|
||||
// не ссылается ни одно сообщение. Блокировка строки (FOR UPDATE) конфликтует с
|
||||
// FOR SHARE при создании сообщения, поэтому гонки «удалили, пока прикрепляли» нет.
|
||||
func (r *AttachmentRepository) DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT id FROM attachments WHERE id = $1::uuid AND status = 'missing' AND updated_at < $2 FOR UPDATE`, id, cutoff).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&referenced); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// IsReferenced — используется ли вложение каким-либо сообщением.
|
||||
func (r *AttachmentRepository) IsReferenced(ctx context.Context, id string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// TryLock — advisory lock, чтобы одновременно работал один reconciler.
|
||||
func (r *AttachmentRepository) TryLock(ctx context.Context) (func(), bool, error) {
|
||||
conn, err := r.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var ok bool
|
||||
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock(4242004)`).Scan(&ok); err != nil || !ok {
|
||||
conn.Release()
|
||||
return nil, false, err
|
||||
}
|
||||
return func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(4242004)`)
|
||||
conn.Release()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
const insertMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, insertMember, chat.ID, uid); err != nil {
|
||||
return fmt.Errorf("insert member %s: %w", uid, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
var c domain.Chat
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select chat: %w", err)
|
||||
}
|
||||
|
||||
const qMembers = `SELECT user_id FROM chat_members WHERE chat_id = $1::uuid ORDER BY user_id`
|
||||
rows, err := r.pool.Query(ctx, qMembers, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
c.MemberIDs = []string{}
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const q = `SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid`
|
||||
var one int
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&one)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
const qChat = `SELECT 1 FROM chats WHERE id = $1::uuid`
|
||||
err = r.pool.QueryRow(ctx, qChat, chatID).Scan(&one)
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, repository.ErrNotFound
|
||||
}
|
||||
return false, fmt.Errorf("check chat exists: %w", err)
|
||||
}
|
||||
|
||||
// MemberVersion одним запросом возвращает версию истории чата и признак членства.
|
||||
// Несуществующий чат — ErrNotFound.
|
||||
func (r *ChatRepository) MemberVersion(ctx context.Context, chatID, userID string) (int64, bool, error) {
|
||||
const q = `
|
||||
SELECT c.version,
|
||||
EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = $2::uuid)
|
||||
FROM chats c
|
||||
WHERE c.id = $1::uuid
|
||||
`
|
||||
var version int64
|
||||
var member bool
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&version, &member)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, false, repository.ErrNotFound
|
||||
}
|
||||
return 0, false, fmt.Errorf("select chat version: %w", err)
|
||||
}
|
||||
return version, member, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error) {
|
||||
const qChats = `
|
||||
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::uuid
|
||||
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, qChats, userID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := []*domain.Chat{}
|
||||
var chatIDs []string
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
c.MemberIDs = []string{}
|
||||
chats = append(chats, &c)
|
||||
chatIDs = append(chatIDs, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
if len(chats) == 0 {
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
const qMembers = `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[]) ORDER BY chat_id, user_id`
|
||||
memberRows, err := r.pool.Query(ctx, qMembers, chatIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list members: %w", err)
|
||||
}
|
||||
defer memberRows.Close()
|
||||
|
||||
byChat := make(map[string][]string)
|
||||
for memberRows.Next() {
|
||||
var chatID, uid string
|
||||
if err := memberRows.Scan(&chatID, &uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
byChat[chatID] = append(byChat[chatID], uid)
|
||||
}
|
||||
if err := memberRows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := byChat[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateIdempotent вставляет сообщение и ключ в одной транзакции.
|
||||
// Конкурентные запросы с одним ключом сериализуются уникальным индексом
|
||||
// idempotency_keys: второй INSERT ждёт завершения первой транзакции, после
|
||||
// COMMIT получает конфликт (DO NOTHING), откатывает своё сообщение и читает
|
||||
// уже сохранённое. Если первая транзакция откатилась (транзиентная ошибка),
|
||||
// вторая просто продолжает — неуспешный результат не фиксируется.
|
||||
func (r *MessageRepository) CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (*domain.Message, bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Ключ старше TTL больше не защищает от повтора — освобождаем его.
|
||||
const deleteExpired = `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND chat_id = $2::uuid AND key = $3
|
||||
AND created_at < now() - make_interval(secs => $4)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, deleteExpired, msg.SenderID, msg.ChatID, key, ttl.Seconds()); err != nil {
|
||||
return nil, false, fmt.Errorf("delete expired key: %w", err)
|
||||
}
|
||||
|
||||
const insertMsg = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, insertMsg, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, false, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(msg.AttachmentIDs) > 0 {
|
||||
if err := attachToMessage(ctx, tx, msg); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
|
||||
const insertKey = `
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5::uuid)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
`
|
||||
tag, err := tx.Exec(ctx, insertKey, msg.SenderID, msg.ChatID, key, requestHash, msg.ID)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("insert idempotency key: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
// Версия истории растёт атомарно с сообщением: после COMMIT любое чтение
|
||||
// увидит новую версию и не попадёт в кэш, записанный до этого сообщения.
|
||||
const bumpVersion = `UPDATE chats SET version = version + 1 WHERE id = $1::uuid`
|
||||
if _, err := tx.Exec(ctx, bumpVersion, msg.ChatID); err != nil {
|
||||
return nil, false, fmt.Errorf("bump chat version: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, false, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return msg, true, nil
|
||||
}
|
||||
|
||||
// Ключ уже занят подтверждённой записью: наше сообщение не сохраняем.
|
||||
_ = tx.Rollback(ctx)
|
||||
|
||||
const selectStored = `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
` + attachmentIDsExpr + `
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1::uuid AND k.chat_id = $2::uuid AND k.key = $3
|
||||
`
|
||||
var storedHash string
|
||||
var m domain.Message
|
||||
err = r.pool.QueryRow(ctx, selectStored, msg.SenderID, msg.ChatID, key).
|
||||
Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("select stored message: %w", err)
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return nil, false, repository.ErrConflict
|
||||
}
|
||||
return &m, false, nil
|
||||
}
|
||||
|
||||
// DeleteExpiredKeys удаляет ключи старше TTL. Безопасно выполнять с любой реплики.
|
||||
func (r *MessageRepository) DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
const q = `DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`
|
||||
tag, err := r.pool.Exec(ctx, q, ttl.Seconds())
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete expired keys: %w", err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
|
||||
q := `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ` + attachmentIDsExpr + `
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1::uuid
|
||||
AND (m.created_at, m.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
msgs := []*domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
|
||||
return nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msgs = append(msgs, &m)
|
||||
}
|
||||
return msgs, rows.Err()
|
||||
}
|
||||
|
||||
// attachmentIDsExpr — id вложений сообщения m в порядке отправки (всегда массив).
|
||||
const attachmentIDsExpr = `ARRAY(SELECT ma.attachment_id::text FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id ORDER BY ma.position)`
|
||||
|
||||
// attachToMessage проверяет и привязывает вложения в транзакции сообщения.
|
||||
// FOR SHARE блокирует строки вложений до COMMIT: reconciler (FOR UPDATE) не
|
||||
// удалит вложение, которое сейчас прикрепляют. Вложение должно быть из того же
|
||||
// чата и в статусе ready; чужое, неизвестное и незавершённое — ErrNotFound.
|
||||
func attachToMessage(ctx context.Context, tx pgx.Tx, msg *domain.Message) error {
|
||||
const q = `
|
||||
SELECT id::text, status FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2::uuid
|
||||
FOR SHARE
|
||||
`
|
||||
rows, err := tx.Query(ctx, q, msg.AttachmentIDs, msg.ChatID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
status := map[string]string{}
|
||||
for rows.Next() {
|
||||
var id, st string
|
||||
if err := rows.Scan(&id, &st); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
status[id] = st
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
for _, id := range msg.AttachmentIDs {
|
||||
switch status[id] {
|
||||
case domain.AttachmentReady:
|
||||
case domain.AttachmentMissing:
|
||||
return repository.ErrConflict
|
||||
default:
|
||||
return repository.ErrNotFound
|
||||
}
|
||||
}
|
||||
batch := &pgx.Batch{}
|
||||
for i, id := range msg.AttachmentIDs {
|
||||
batch.Queue(`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
msg.ID, id, i)
|
||||
}
|
||||
if err := tx.SendBatch(ctx, batch).Close(); err != nil {
|
||||
return fmt.Errorf("insert message attachments: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool создаёт пул соединений с PostgreSQL.
|
||||
// Параметры ограничены, чтобы не перегрузить БД.
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = min(2, maxConns)
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
// Проверяем, что соединение работает.
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
|
||||
return &UserRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
return fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE id = $1::uuid`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE username = $1`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by username: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
|
||||
const q = `SELECT password_hash FROM users WHERE id = $1::uuid`
|
||||
var hash string
|
||||
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", fmt.Errorf("select password hash: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
// Ключ кэша истории всегда содержит версию чата из PostgreSQL (chats.version),
|
||||
// которая растёт в одной транзакции с сообщением. Поэтому после подтверждённой
|
||||
// записи следующее чтение идёт по новому ключу, даже если Redis отказал в
|
||||
// любой команде: устаревшие ключи просто истекают по TTL.
|
||||
//
|
||||
// CACHE_INVALIDATION влияет только на стоимость записи (эксперимент трека 1):
|
||||
// - "version": запись не обращается к Redis;
|
||||
// - "scan": дополнительно удаляет ключи чата через SCAN, как в lab2 —
|
||||
// O(размер keyspace/100) запросов к Redis на запись. На корректность не влияет.
|
||||
const (
|
||||
InvalidationScan = "scan"
|
||||
InvalidationVersion = "version"
|
||||
)
|
||||
|
||||
type MessageCache struct {
|
||||
client *redis.Client
|
||||
scanOnSet bool
|
||||
}
|
||||
|
||||
func NewMessageCache(client *redis.Client, mode string) *MessageCache {
|
||||
return &MessageCache{client: client, scanOnSet: mode == InvalidationScan}
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
Items []*domain.Message `json:"items"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func cacheKey(chatID string, version int64, cursor string, limit int) string {
|
||||
return fmt.Sprintf("messages:%s:v%d:%s:%d", chatID, version, cursor, limit)
|
||||
}
|
||||
|
||||
func (c *MessageCache) Get(ctx context.Context, chatID string, version int64, cursor string, limit int) ([]*domain.Message, string, bool) {
|
||||
raw, err := c.client.Get(ctx, cacheKey(chatID, version, cursor, limit)).Bytes()
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
var e cacheEntry
|
||||
if err := json.Unmarshal(raw, &e); err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return e.Items, e.NextCursor, true
|
||||
}
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID string, version int64, cursor string, limit int, items []*domain.Message, next string) {
|
||||
e := cacheEntry{Items: items, NextCursor: next}
|
||||
raw, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
slog.Warn("marshal cache entry failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := c.client.Set(ctx, cacheKey(chatID, version, cursor, limit), raw, 30*time.Second).Err(); err != nil {
|
||||
// Redis недоступен — не падаем, работаем без кэша.
|
||||
slog.Warn("redis set failed", "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// OnWrite вызывается после успешной записи сообщения. Свежесть чтения уже
|
||||
// обеспечена ростом chats.version в транзакции записи; в режиме scan здесь
|
||||
// только воспроизводится стоимость удаления старых ключей (lab2), и ошибка
|
||||
// Redis не может сделать историю устаревшей.
|
||||
func (c *MessageCache) OnWrite(ctx context.Context, chatID string) {
|
||||
if !c.scanOnSet {
|
||||
return
|
||||
}
|
||||
if err := c.Invalidate(ctx, chatID); err != nil {
|
||||
slog.Warn("redis scan invalidation failed", "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate удаляет все ключи messages:{chatID}:* через SCAN.
|
||||
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
|
||||
pattern := fmt.Sprintf("messages:%s:*", chatID)
|
||||
iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
|
||||
for iter.Next(ctx) {
|
||||
_ = c.client.Del(ctx, iter.Val()).Err()
|
||||
}
|
||||
return iter.Err()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
||||
return &SessionRepository{client: client}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
||||
key := "session:" + s.Token
|
||||
ttl := time.Until(s.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("session already expired")
|
||||
}
|
||||
if err := r.client.Set(ctx, key, s.UserID, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("set session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
||||
key := "session:" + token
|
||||
userID, err := r.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
ttl, err := r.client.TTL(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ttl: %w", err)
|
||||
}
|
||||
return &domain.Session{
|
||||
Token: token,
|
||||
UserID: userID,
|
||||
ExpiresAt: time.Now().UTC().Add(ttl),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
||||
return r.client.Del(ctx, "session:"+token).Err()
|
||||
}
|
||||
|
||||
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
client := redis.NewClient(opts)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
var ErrNotFound = errNotFound{}
|
||||
|
||||
type errNotFound struct{}
|
||||
|
||||
func (errNotFound) Error() string { return "not found" }
|
||||
|
||||
var ErrConflict = errConflict{}
|
||||
|
||||
type errConflict struct{}
|
||||
|
||||
func (errConflict) Error() string { return "conflict" }
|
||||
|
||||
// UserRepository
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, user *domain.User, passwordHash string) error
|
||||
GetByID(ctx context.Context, id string) (*domain.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*domain.User, error)
|
||||
GetPasswordHash(ctx context.Context, userID string) (string, error)
|
||||
}
|
||||
|
||||
// ChatRepository
|
||||
type ChatRepository interface {
|
||||
Create(ctx context.Context, chat *domain.Chat) error
|
||||
GetByID(ctx context.Context, id string) (*domain.Chat, error)
|
||||
IsMember(ctx context.Context, chatID, userID string) (bool, error)
|
||||
// MemberVersion — версия истории чата (растёт с каждым сообщением) и членство.
|
||||
MemberVersion(ctx context.Context, chatID, userID string) (version int64, member bool, err error)
|
||||
ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error)
|
||||
}
|
||||
|
||||
// MessageRepository
|
||||
type MessageRepository interface {
|
||||
Create(ctx context.Context, msg *domain.Message) error
|
||||
// CreateIdempotent атомарно создаёт сообщение и запись ключа идемпотентности.
|
||||
// Если ключ уже есть с тем же requestHash — возвращает ранее созданное сообщение
|
||||
// и created=false; с другим requestHash — ErrConflict.
|
||||
CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (stored *domain.Message, created bool, err error)
|
||||
DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error)
|
||||
ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error)
|
||||
}
|
||||
|
||||
// SessionRepository
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, s *domain.Session) error
|
||||
GetByToken(ctx context.Context, token string) (*domain.Session, error)
|
||||
Delete(ctx context.Context, token string) error
|
||||
DeleteExpired(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg" // DecodeConfig для раннего отказа по размерам
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/imagecheck"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
"github.com/charawein/mtusi2026lab4/internal/storage"
|
||||
)
|
||||
|
||||
// ObjectPrefix — все объекты вложений лежат под этим префиксом bucket.
|
||||
const ObjectPrefix = "a/"
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateIntent(ctx context.Context, a *domain.Attachment) error
|
||||
MarkReady(ctx context.Context, a *domain.Attachment) error
|
||||
DeleteIntent(ctx context.Context, id string) error
|
||||
GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
repo AttachmentRepository
|
||||
chats repository.ChatRepository
|
||||
store storage.Store
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
}
|
||||
|
||||
func NewAttachmentService(repo AttachmentRepository, chats repository.ChatRepository, store storage.Store, maxBytes, maxPixels int64) *AttachmentService {
|
||||
return &AttachmentService{repo: repo, chats: chats, store: store, maxBytes: maxBytes, maxPixels: maxPixels}
|
||||
}
|
||||
|
||||
// validateFilename: 1–255 code points, не только пробелы, без / \ NUL и управляющих.
|
||||
func validateFilename(s string) bool {
|
||||
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
if n := utf8.RuneCountInString(s); n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// declaredType нормализует Content-Type запроса; допустимы только PNG/JPEG.
|
||||
func declaredType(h string) (string, bool) {
|
||||
mt, _, err := mime.ParseMediaType(h)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
mt = strings.ToLower(mt)
|
||||
return mt, mt == imagecheck.PNG || mt == imagecheck.JPEG
|
||||
}
|
||||
|
||||
// Upload принимает сырые байты одного изображения и возвращает ready-вложение.
|
||||
//
|
||||
// Порядок: намерение в PostgreSQL (uploading) → потоковый PUT в S3, параллельно
|
||||
// SHA-256 и структурная проверка изображения → status=ready. 201 возвращается
|
||||
// только после того, как и объект, и метаданные сохранены. Любая ошибка после
|
||||
// записи намерения компенсируется (удаление объекта и намерения); если компенсация
|
||||
// не удалась (упали БД/S3/процесс), остаток убирает reconciler после grace period.
|
||||
func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filename, contentType string, body io.Reader, contentLength int64) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
ok, err := s.chats.IsMember(ctx, chatID, ownerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if !validateFilename(filename) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
declared, ok := declaredType(contentType)
|
||||
if !ok {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Лимит размера — до чтения тела.
|
||||
if contentLength > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
size := contentLength
|
||||
if size < 0 {
|
||||
// Без Content-Length (chunked): буфер не больше лимита + 1 байт.
|
||||
buf, err := io.ReadAll(io.LimitReader(body, s.maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if int64(len(buf)) > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
body, size = bytes.NewReader(buf), int64(len(buf))
|
||||
}
|
||||
if size == 0 {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
// Формат — по содержимому; подмена Content-Type → 415.
|
||||
br := bufio.NewReaderSize(body, 64*1024)
|
||||
head, _ := br.Peek(int(min(size, 64*1024)))
|
||||
format, ok := imagecheck.Sniff(head)
|
||||
if !ok || format != declared {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Ранний отказ по пикселям, если заголовок уместился в первые 64 KiB.
|
||||
if cfg, _, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
id := newID()
|
||||
a := &domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, Filename: filename,
|
||||
ObjectKey: ObjectPrefix + chatID + "/" + id,
|
||||
Status: domain.AttachmentUploading, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.repo.CreateIntent(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sum, putErr := s.putValidated(ctx, a.ObjectKey, br, size, format)
|
||||
if putErr != nil {
|
||||
s.compensate(ctx, a, putErr)
|
||||
return nil, putErr
|
||||
}
|
||||
|
||||
a.Status = domain.AttachmentReady
|
||||
a.ContentType = format
|
||||
a.SizeBytes = size
|
||||
a.SHA256 = sum
|
||||
a.UpdatedAt = nowUTC()
|
||||
if err := s.repo.MarkReady(ctx, a); err != nil {
|
||||
// S3 записан, а БД — нет: объект удаляем, намерение — по возможности.
|
||||
s.compensate(ctx, a, err)
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var errClientBody = errors.New("request body read failed")
|
||||
|
||||
type bodyReader struct{ r io.Reader }
|
||||
|
||||
func (b bodyReader) Read(p []byte) (int, error) {
|
||||
n, err := b.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, errors.Join(errClientBody, err)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// putValidated пишет объект в S3 и одновременно проверяет изображение и считает
|
||||
// SHA-256. Байты проходят потоком (pipe), в памяти — только буферы чтения.
|
||||
func (s *AttachmentService) putValidated(ctx context.Context, key string, body io.Reader, size int64, format string) (string, error) {
|
||||
pr, pw := io.Pipe()
|
||||
valErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := imagecheck.Validate(pr, format, s.maxPixels)
|
||||
if err != nil {
|
||||
pr.CloseWithError(err) // прерывает PUT: дальше писать некуда
|
||||
}
|
||||
valErr <- err
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
src := io.TeeReader(io.TeeReader(bodyReader{body}, h), pw)
|
||||
putErr := s.store.Put(ctx, key, src, size, format)
|
||||
if putErr != nil {
|
||||
pw.CloseWithError(putErr)
|
||||
} else {
|
||||
pw.Close()
|
||||
}
|
||||
vErr := <-valErr
|
||||
|
||||
switch {
|
||||
case errors.Is(vErr, imagecheck.ErrTooLarge):
|
||||
return "", ErrPayloadTooLarge
|
||||
case errors.Is(vErr, imagecheck.ErrInvalid):
|
||||
return "", ErrUnsupportedMedia
|
||||
case errors.Is(putErr, errClientBody):
|
||||
return "", ErrInvalidInput
|
||||
case putErr != nil:
|
||||
slog.Warn("attachment upload to s3 failed", "err", putErr)
|
||||
return "", ErrUnavailable
|
||||
case vErr != nil:
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// compensate убирает следы неудачной загрузки. Работает и после обрыва клиента
|
||||
// (контекст запроса отменён), поэтому использует отдельный контекст.
|
||||
func (s *AttachmentService) compensate(ctx context.Context, a *domain.Attachment, cause error) {
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.store.Delete(cctx, a.ObjectKey); err != nil {
|
||||
slog.Warn("compensation: delete object failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||||
slog.Warn("compensation: delete intent failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
slog.Info("attachment upload compensated", "attachment_id", a.ID, "cause", cause.Error())
|
||||
}
|
||||
|
||||
// Get возвращает метаданные ready-вложения участнику его чата.
|
||||
func (s *AttachmentService) Get(ctx context.Context, userID, id string) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
a, err := s.repo.GetForMember(ctx, parsed.String(), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
switch a.Status {
|
||||
case domain.AttachmentReady:
|
||||
return a, nil
|
||||
case domain.AttachmentMissing:
|
||||
// Метаданные есть, байтов нет (обнаружил reconciler): ошибка сервера, не клиента.
|
||||
return nil, ErrUnavailable
|
||||
default:
|
||||
return nil, ErrNotFound // загрузка не завершена — объекта для клиента ещё нет
|
||||
}
|
||||
}
|
||||
|
||||
// Open открывает оригинал на чтение. Вызывающий закрывает ReadCloser.
|
||||
func (s *AttachmentService) Open(ctx context.Context, userID, id string) (*domain.Attachment, io.ReadCloser, error) {
|
||||
a, err := s.Get(ctx, userID, id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
rc, size, err := s.store.Get(ctx, a.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
slog.Error("attachment object missing in s3", "attachment_id", a.ID)
|
||||
} else {
|
||||
slog.Warn("s3 get failed", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
if size != a.SizeBytes {
|
||||
rc.Close()
|
||||
slog.Error("attachment size mismatch", "attachment_id", a.ID, "s3", size, "db", a.SizeBytes)
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
return a, rc, nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
users repository.UserRepository
|
||||
sessions repository.SessionRepository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users repository.UserRepository, sessions repository.SessionRepository, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (*domain.Session, *domain.User, error) {
|
||||
u, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
_, _ = hashPassword("dummy-password-for-timing")
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := s.users.GetPasswordHash(ctx, u.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := verifyPassword(password, hash); err != nil {
|
||||
if errors.Is(err, ErrPasswordMismatch) {
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
sess := &domain.Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, sess); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sess, u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (*domain.User, error) {
|
||||
sess, err := s.sessions.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
// Redis недоступен — возвращаем 401, чтобы клиент перелогинился,
|
||||
// либо 503, если хотим явно показать проблему зависимости.
|
||||
return nil, ErrUnauthorized // ← было: return nil, err
|
||||
}
|
||||
if nowUTC().After(sess.ExpiresAt) {
|
||||
_ = s.sessions.Delete(ctx, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
u, err := s.users.GetByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, token)
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats repository.ChatRepository
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats repository.ChatRepository, users repository.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, callerID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if !validateTitle(title) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
// Нормализация UUID: убираем разницу регистра.
|
||||
normalized := make([]string, 0, len(memberIDs))
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerFound := false
|
||||
callerParsed, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
callerID = callerParsed.String()
|
||||
|
||||
for _, id := range memberIDs {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
id = parsed.String()
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
normalized = append(normalized, id)
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
if !callerFound {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: normalized,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit int) ([]*domain.Chat, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, callerID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.chats.ListByMember(ctx, callerID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Chat{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(callerID, last.CreatedAt, last.ID)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[0]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrPasswordMismatch = errors.New("password mismatch")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// nowUTC возвращает время UTC с точностью до секунд.
|
||||
// PostgreSQL и Python-клиент тестов ожидают формат без наносекунд.
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
redisrepo "github.com/charawein/mtusi2026lab4/internal/repository/redis"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages repository.MessageRepository
|
||||
chats repository.ChatRepository
|
||||
cache *redisrepo.MessageCache
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache, idempotencyTTL time.Duration) *MessageService {
|
||||
return &MessageService{messages: messages, chats: chats, cache: cache, idempotencyTTL: idempotencyTTL}
|
||||
}
|
||||
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
// requestHash — отпечаток семантики тела запроса. Хешируем уже разобранные поля,
|
||||
// а не сырые байты: порядок ключей JSON не важен, отсутствующий attachment_ids
|
||||
// равен [], порядок самих вложений значим.
|
||||
func requestHash(text string, attachmentIDs []string) string {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
raw, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{Text: text, AttachmentIDs: attachmentIDs})
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Send создаёт сообщение с обязательным Idempotency-Key. Повтор с тем же ключом
|
||||
// и телом возвращает исходное сообщение, с другим телом — ErrConflict.
|
||||
// Доступ к чату проверяется при каждом повторе.
|
||||
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string, attachmentIDs []string, idempotencyKey string) (*domain.Message, error) {
|
||||
if !idempotencyKeyRe.MatchString(idempotencyKey) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ids, ok := normalizeAttachmentIDs(attachmentIDs)
|
||||
if !ok {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
// С вложениями допустим пустой text; иначе — обычные правила текста.
|
||||
if !(len(ids) > 0 && text == "") && !validateText(text) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ok, err = s.chats.IsMember(ctx, chatID, senderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
m := &domain.Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
|
||||
AttachmentIDs: ids,
|
||||
}
|
||||
stored, created, err := s.messages.CreateIdempotent(ctx, m, idempotencyKey, requestHash(text, ids), s.idempotencyTTL)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrConflict):
|
||||
return nil, ErrConflict
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
return nil, ErrNotFound // чужое/неизвестное/незавершённое вложение
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !created {
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
// Версия чата уже увеличена в транзакции записи; здесь только режим scan.
|
||||
if s.cache != nil {
|
||||
s.cache.OnWrite(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
// Членство и версия истории — одним запросом к PostgreSQL. Версия читается
|
||||
// до истории, поэтому под ключом версии v лежат данные не старее v.
|
||||
version, ok, err := s.chats.MemberVersion(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
if items, next, hit := s.cache.Get(ctx, chatID, version, cursor, limit); hit {
|
||||
return items, next, nil
|
||||
}
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, chatID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Message{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, chatID, version, cursor, limit, items, next)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
// normalizeAttachmentIDs: 0–10 уникальных UUID; приводит к каноническому виду.
|
||||
func normalizeAttachmentIDs(in []string) ([]string, bool) {
|
||||
if len(in) > 10 {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]string, 0, len(in))
|
||||
seen := make(map[string]bool, len(in))
|
||||
for _, raw := range in {
|
||||
u, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
id := u.String()
|
||||
if seen[id] {
|
||||
return nil, false
|
||||
}
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
func verifyPassword(password, encoded string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return fmt.Errorf("invalid hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("incompatible version: %d", version)
|
||||
}
|
||||
var mem uint32
|
||||
var iters uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
|
||||
return fmt.Errorf("parse params: %w", err)
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode hash: %w", err)
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return ErrPasswordMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(users repository.UserRepository) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
// Register создаёт нового пользователя. Возвращает ErrInvalidInput при невалидных
|
||||
// данных и ErrConflict, если username занят.
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !validateUsername(username) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validateDisplayName(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validatePassword(password) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetByID возвращает пользователя. Возвращает ErrNotFound, если такого нет.
|
||||
// Используется middleware аутентификации для проверки X-User-Id.
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
u, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// validatePassword: 12–128 code points и не только пробельные символы
|
||||
// (обязательная строка по контракту не может состоять из одних пробелов).
|
||||
func validatePassword(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
// validateUsername проверяет формат username по README: строго [a-z0-9_]{3,32}.
|
||||
func validateUsername(s string) bool {
|
||||
return usernameRe.MatchString(s)
|
||||
}
|
||||
|
||||
// validateDisplayName проверяет display_name: 1–100 Unicode code points,
|
||||
// не состоит только из пробельных символов.
|
||||
func validateDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateTitle проверяет title чата: 1–100 code points, не только пробелы.
|
||||
func validateTitle(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateText проверяет text сообщения: 1–4000 code points, не только пробелы.
|
||||
// В lab4 появится возможность отправить пустой text, если есть attachment_ids.
|
||||
func validateText(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 4000
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidatePassword(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{"обычный", "correct-horse-12", true},
|
||||
{"ровно 12", strings.Repeat("a", 12), true},
|
||||
{"128 code points", strings.Repeat("я", 128), true},
|
||||
{"двоеточие допустимо", "pass:word:1234", true},
|
||||
{"пробелы внутри допустимы", " pass word ", true},
|
||||
{"короче 12", strings.Repeat("a", 11), false},
|
||||
{"длиннее 128", strings.Repeat("a", 129), false},
|
||||
{"12 пробелов", strings.Repeat(" ", 12), false},
|
||||
{"пробельные символы разных видов", strings.Repeat(" \t\n ", 4), false},
|
||||
{"пусто", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := validatePassword(c.in); got != c.want {
|
||||
t.Errorf("%s: validatePassword(%q) = %v, want %v", c.name, c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateText(t *testing.T) {
|
||||
if validateText(strings.Repeat(" ", 5)) {
|
||||
t.Error("whitespace-only text must be rejected")
|
||||
}
|
||||
if !validateText("привет") {
|
||||
t.Error("normal text must be accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Package storage — приватное S3-хранилище байтов вложений (MinIO).
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// ErrNotFound — объекта нет в bucket.
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
|
||||
// Object — элемент листинга.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Store — то, что нужно приложению и reconciler от объектного хранилища.
|
||||
type Store interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, int64, error)
|
||||
Stat(ctx context.Context, key string) (Object, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
// List отдаёт объекты с префиксом в лексикографическом (байтовом) порядке ключей.
|
||||
List(ctx context.Context, prefix string, fn func(Object) error) error
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewS3(endpoint, region, bucket, accessKey, secretKey string) (*S3, error) {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Host == "" {
|
||||
return nil, fmt.Errorf("bad S3 endpoint %q", endpoint)
|
||||
}
|
||||
c, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: region,
|
||||
// По умолчанию minio-go повторяет до 10 раз; при недоступном S3 клиент
|
||||
// должен быстро получить 503, а не ждать таймаута LB.
|
||||
MaxRetries: 2,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 client: %w", err)
|
||||
}
|
||||
return &S3{client: c, bucket: bucket}, nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
return code == "NoSuchKey" || code == "NotFound"
|
||||
}
|
||||
|
||||
// Put пишет объект одним PUT, читая r потоково (size известен заранее).
|
||||
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
DisableMultipart: true,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("s3 put: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("s3 get: %w", err)
|
||||
}
|
||||
// GetObject ленивый: ошибки (нет объекта, S3 недоступен) видны на Stat.
|
||||
st, err := obj.Stat()
|
||||
if err != nil {
|
||||
obj.Close()
|
||||
if isNotFound(err) {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
return nil, 0, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return obj, st.Size, nil
|
||||
}
|
||||
|
||||
func (s *S3) Stat(ctx context.Context, key string) (Object, error) {
|
||||
st, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return Object{}, ErrNotFound
|
||||
}
|
||||
return Object{}, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return Object{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete идемпотентен: удаление отсутствующего объекта не ошибка.
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil && !isNotFound(err) {
|
||||
return fmt.Errorf("s3 delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string, fn func(Object) error) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
for o := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return fmt.Errorf("s3 list: %w", o.Err)
|
||||
}
|
||||
if strings.HasSuffix(o.Key, "/") {
|
||||
continue
|
||||
}
|
||||
if err := fn(Object{Key: o.Key, Size: o.Size, LastModified: o.LastModified}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
attachments *service.AttachmentService
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(attachments *service.AttachmentService) *AttachmentHandler {
|
||||
return &AttachmentHandler{attachments: attachments}
|
||||
}
|
||||
|
||||
// Upload: POST /api/v1/chats/{chat_id}/attachments?filename=... с сырыми байтами PNG/JPEG.
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if len(q["filename"]) != 1 {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
// MaxBytesReader — второй рубеж: не дать прочитать больше лимита + 1 байт,
|
||||
// даже если Content-Length солгал.
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024+1)
|
||||
a, err := h.attachments.Upload(r.Context(), uid, r.PathValue("chat_id"), q.Get("filename"),
|
||||
r.Header.Get("Content-Type"), r.Body, r.ContentLength)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, a)
|
||||
}
|
||||
|
||||
// Get: GET /api/v1/attachments/{attachment_id} — метаданные.
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
a, err := h.attachments.Get(r.Context(), uid, r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, a)
|
||||
}
|
||||
|
||||
// Content: GET /api/v1/attachments/{attachment_id}/content[?variant=original] — байты
|
||||
// через авторизованный API, без redirect на S3.
|
||||
func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
variant := r.URL.Query().Get("variant")
|
||||
switch variant {
|
||||
case "", "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
// Варианты появятся в lab5; у ready-объекта lab4 их нет — после проверки доступа 404.
|
||||
if _, err := h.attachments.Get(r.Context(), uid, r.PathValue("attachment_id")); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteError(w, r, service.ErrNotFound)
|
||||
return
|
||||
default:
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
a, rc, err := h.attachments.Open(r.Context(), uid, r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
w.Header().Set("Content-Type", a.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if n, err := io.Copy(w, rc); err != nil {
|
||||
// Заголовок уже отправлен: клиент увидит обрыв по Content-Length.
|
||||
slog.Warn("attachment download interrupted", "attachment_id", a.ID, "sent", n, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
auth *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(auth *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{auth: auth}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User *domain.User `json:"user"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := parseBasicAuth(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
sess, u, err := h.auth.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == service.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Формат RFC3339 без микросекунд: "2026-10-09T19:00:36Z".
|
||||
// Python-клиент тестов ожидает 'Z' в конце строки.
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, sessionResponse{
|
||||
Token: sess.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: sess.ExpiresAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token := bearerToken(r)
|
||||
if token == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if err := h.auth.Logout(r.Context(), token); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasicAuth(h string) (string, string, bool) {
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(h[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
parts := strings.SplitN(string(raw), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", "", false
|
||||
}
|
||||
return parts[0], parts[1], true
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(h, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(h, "Bearer ")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Create(r.Context(), uid, body.Title, body.MemberIDs)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, c)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.chats.List(r.Context(), uid, cursor, limit)
|
||||
if err != nil {
|
||||
// ВРЕМЕННО: логируем точную ошибку
|
||||
slog.Error("ListChats failed", "err", err, "uid", uid, "cursor", cursor, "limit", limit)
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Get(r.Context(), uid, chatID)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, c)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redis *redis.Client
|
||||
draining *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, draining *atomic.Bool) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redis: redisClient, draining: draining}
|
||||
}
|
||||
|
||||
// Live проверяет только жизнь процесса.
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// Ready проверяет доступность PostgreSQL и Redis.
|
||||
// После SIGTERM возвращает 503, чтобы LB исключил реплику до закрытия listener.
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if h.draining.Load() {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if err := h.redis.Ping(ctx).Err(); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"runtime"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/config"
|
||||
)
|
||||
|
||||
// NewInternalStatsHandler отдаёт счётчики пула PostgreSQL и рантайма Go.
|
||||
// Нужен для поиска точки насыщения пула в экспериментах трека 1:
|
||||
// рост empty_acquire_count/acquire_duration означает ожидание свободного соединения.
|
||||
func NewInternalStatsHandler(pool *pgxpool.Pool, cfg config.Config) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /internal/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
st := pool.Stat()
|
||||
body := map[string]any{
|
||||
"instance_id": cfg.InstanceID,
|
||||
"cache_invalidation": cfg.CacheInvalidation,
|
||||
"pool": map[string]any{
|
||||
"max_conns": st.MaxConns(),
|
||||
"total_conns": st.TotalConns(),
|
||||
"acquired_conns": st.AcquiredConns(),
|
||||
"idle_conns": st.IdleConns(),
|
||||
"acquire_count": st.AcquireCount(),
|
||||
"empty_acquire_count": st.EmptyAcquireCount(),
|
||||
"canceled_acquire_count": st.CanceledAcquireCount(),
|
||||
"acquire_duration_ms": st.AcquireDuration().Milliseconds(),
|
||||
},
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
if body.Text == nil { // text обязателен по контракту, даже пустой
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
// Повтор с тем же ключом возвращает тот же 201 и то же сообщение.
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
m, err := h.messages.Send(r.Context(), uid, chatID, *body.Text, body.AttachmentIDs, key)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, m)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.messages.List(r.Context(), uid, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Auth проверяет Authorization: Bearer <token> через AuthService.
|
||||
func Auth(auth *service.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := auth.ValidateSession(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
slog.Error("auth: unexpected", "err", err)
|
||||
httputil.WriteError(w, r, nil)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := httputil.ContextWithUserID(r.Context(), u.ID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// InstanceID добавляет X-Instance-Id ко всем ответам API, включая ошибки и health.
|
||||
// Значение задаётся один раз при старте процесса и не меняется до его завершения.
|
||||
func InstanceID(id 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", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
slog.Info("http request",
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
slog.Error("panic in handler",
|
||||
"panic", rec,
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
)
|
||||
httputil.WriteError(w, r, nil)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func RequestID(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 = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := httputil.ContextWithRequestID(r.Context(), id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var b [12]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return fmt.Sprintf("%x", b[:])
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timeout ограничивает время выполнения запроса.
|
||||
func Timeout(d time.Duration) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), d)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
users *service.UserService,
|
||||
chats *service.ChatService,
|
||||
messages *service.MessageService,
|
||||
attachments *service.AttachmentService,
|
||||
auth *service.AuthService,
|
||||
pool *pgxpool.Pool,
|
||||
redisClient *redis.Client,
|
||||
instanceID string,
|
||||
draining *atomic.Bool,
|
||||
) http.Handler {
|
||||
userH := NewUserHandler(users)
|
||||
chatH := NewChatHandler(chats)
|
||||
msgH := NewMessageHandler(messages)
|
||||
authH := NewAuthHandler(auth)
|
||||
attH := NewAttachmentHandler(attachments)
|
||||
healthH := NewHealthHandler(pool, redisClient, draining)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Таймаут на запрос: обычный API — 5 s, передача файлов — 30 s.
|
||||
short := middleware.Timeout(5 * time.Second)
|
||||
long := middleware.Timeout(30 * time.Second)
|
||||
authMW := func(h http.Handler) http.Handler { return short(middleware.Auth(auth)(h)) }
|
||||
fileMW := func(h http.Handler) http.Handler { return long(middleware.Auth(auth)(h)) }
|
||||
|
||||
mux.Handle("GET /health/live", short(http.HandlerFunc(healthH.Live)))
|
||||
mux.Handle("GET /health/ready", short(http.HandlerFunc(healthH.Ready)))
|
||||
mux.Handle("POST /api/v1/users", short(http.HandlerFunc(userH.CreateUser)))
|
||||
mux.Handle("POST /api/v1/auth/sessions", short(http.HandlerFunc(authH.CreateSession)))
|
||||
|
||||
mux.Handle("DELETE /api/v1/auth/sessions/current", authMW(http.HandlerFunc(authH.RevokeSession)))
|
||||
mux.Handle("GET /api/v1/users/me", authMW(http.HandlerFunc(userH.CurrentUser)))
|
||||
mux.Handle("POST /api/v1/chats", authMW(http.HandlerFunc(chatH.CreateChat)))
|
||||
mux.Handle("GET /api/v1/chats", authMW(http.HandlerFunc(chatH.ListChats)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}", authMW(http.HandlerFunc(chatH.GetChat)))
|
||||
mux.Handle("POST /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.SendMessage)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.ListMessages)))
|
||||
mux.Handle("POST /api/v1/chats/{chat_id}/attachments", fileMW(http.HandlerFunc(attH.Upload)))
|
||||
mux.Handle("GET /api/v1/attachments/{attachment_id}", authMW(http.HandlerFunc(attH.Get)))
|
||||
mux.Handle("GET /api/v1/attachments/{attachment_id}/content", fileMW(http.HandlerFunc(attH.Content)))
|
||||
|
||||
handler := middleware.Logging(mux)
|
||||
handler = middleware.Recovery(handler)
|
||||
handler = middleware.RequestID(handler)
|
||||
handler = middleware.InstanceID(instanceID)(handler)
|
||||
return handler
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
"github.com/charawein/mtusi2026lab4/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *UserHandler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
u, err := h.users.GetByID(r.Context(), uid)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, u)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package httputil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/charawein/mtusi2026lab4/internal/service"
|
||||
)
|
||||
|
||||
// requestIDKey — ключ контекста для X-Request-Id.
|
||||
type requestIDKey struct{}
|
||||
|
||||
// ContextWithRequestID кладёт request_id в контекст. Используется middleware.RequestID.
|
||||
func ContextWithRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
// RequestIDFrom извлекает request_id из контекста.
|
||||
func RequestIDFrom(ctx context.Context) string {
|
||||
if v, ok := ctx.Value(requestIDKey{}).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// userIDKey — ключ контекста для аутентифицированного user_id.
|
||||
type userIDKey struct{}
|
||||
|
||||
// ContextWithUserID кладёт user_id в контекст. Используется middleware.Auth.
|
||||
func ContextWithUserID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey{}, id)
|
||||
}
|
||||
|
||||
// UserIDFromContext извлекает user_id из контекста.
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
if v, ok := ctx.Value(userIDKey{}).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// errorBody — формат тела ошибки по contracts/openapi.json.
|
||||
type errorBody struct {
|
||||
Error errorDetail `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// WriteJSON пишет JSON-ответ с заданным статусом.
|
||||
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
slog.Error("failed to encode response", "err", err, "request_id", RequestIDFrom(r.Context()))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError мапит доменную ошибку в HTTP-статус и пишет тело в формате контракта.
|
||||
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
status, code := mapError(err)
|
||||
reqID := RequestIDFrom(r.Context())
|
||||
if reqID == "" {
|
||||
reqID = "missing-request-id"
|
||||
}
|
||||
body := errorBody{Error: errorDetail{
|
||||
Code: code,
|
||||
Message: messageFor(code),
|
||||
RequestID: reqID,
|
||||
}}
|
||||
WriteJSON(w, r, status, body)
|
||||
}
|
||||
|
||||
func mapError(err error) (int, string) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable, "unavailable"
|
||||
case errors.Is(err, service.ErrPayloadTooLarge):
|
||||
return http.StatusRequestEntityTooLarge, "payload_too_large"
|
||||
case errors.Is(err, service.ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, "unsupported_media_type"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func messageFor(code string) string {
|
||||
switch code {
|
||||
case "invalid_request":
|
||||
return "Неверный запрос"
|
||||
case "unauthorized":
|
||||
return "Требуется аутентификация"
|
||||
case "not_found":
|
||||
return "Объект не найден"
|
||||
case "conflict":
|
||||
return "Конфликт"
|
||||
case "internal_error":
|
||||
return "Внутренняя ошибка"
|
||||
case "unavailable":
|
||||
return "Сервис недоступен"
|
||||
case "payload_too_large":
|
||||
return "Слишком большой файл или изображение"
|
||||
case "unsupported_media_type":
|
||||
return "Поддерживаются только корректные PNG и JPEG"
|
||||
default:
|
||||
return "Ошибка"
|
||||
}
|
||||
}
|
||||
|
||||
// DecodeJSON парсит тело запроса в v, строго запрещая неизвестные поля.
|
||||
func DecodeJSON(r *http.Request, v any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return service.ErrInvalidInput
|
||||
}
|
||||
if dec.More() {
|
||||
return service.ErrInvalidInput
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseLimit читает query-параметр limit с дефолтом и границами по контракту.
|
||||
func ParseLimit(r *http.Request) (int, error) {
|
||||
s := r.URL.Query().Get("limit")
|
||||
if s == "" {
|
||||
return 50, nil
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, service.ErrInvalidInput
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// PageResponse — универсальный ответ пагинации.
|
||||
type PageResponse struct {
|
||||
Items any `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// NextOrNull превращает пустую строку в nil (для сериализации в null).
|
||||
func NextOrNull(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Откат миграции 0001
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,50 @@
|
||||
-- migrations/0001_init.sql
|
||||
|
||||
-- Пользователи
|
||||
CREATE TABLE 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 chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Членство
|
||||
CREATE TABLE 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 INDEX chat_members_user_idx ON chat_members(user_id);
|
||||
|
||||
-- Сообщения
|
||||
CREATE TABLE 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()
|
||||
);
|
||||
|
||||
-- Главный индекс для пагинации
|
||||
CREATE INDEX messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Сессии (если SESSION_STORE=postgres)
|
||||
CREATE TABLE 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 sessions_expires_idx ON sessions(expires_at);
|
||||
CREATE INDEX sessions_user_idx ON sessions(user_id);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS idempotency_keys;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- migrations/0002_idempotency.sql
|
||||
|
||||
-- Ключи идемпотентности отправки сообщения (lab3).
|
||||
-- Область уникальности: пользователь + метод + путь чата + ключ.
|
||||
-- Метод всегда POST, путь однозначно задаётся chat_id, поэтому храним chat_id.
|
||||
-- Запись создаётся в одной транзакции с сообщением: либо есть обе, либо ни одной.
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
);
|
||||
|
||||
-- Для периодической очистки ключей старше IDEMPOTENCY_TTL_SECONDS.
|
||||
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys(created_at);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE chats DROP COLUMN IF EXISTS version;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- migrations/0003_chat_version.sql
|
||||
|
||||
-- Версия истории чата: увеличивается в той же транзакции, что и вставка сообщения.
|
||||
-- Входит в ключ кэша истории, поэтому видимость подтверждённой записи не зависит
|
||||
-- от доступности Redis. Только добавление столбца с DEFAULT — совместимо с
|
||||
-- работающей предыдущей версией API (expand).
|
||||
ALTER TABLE chats ADD COLUMN version BIGINT NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS message_attachments;
|
||||
DROP TABLE IF EXISTS attachments;
|
||||
@@ -0,0 +1,42 @@
|
||||
-- migrations/0004_attachments.sql
|
||||
|
||||
-- Метаданные вложений. Байты — только в приватном S3-bucket по object_key,
|
||||
-- который назначает сервер (filename используется только для отображения).
|
||||
--
|
||||
-- Жизненный цикл строки:
|
||||
-- uploading — намерение записано ДО PUT в S3; так у каждого объекта, который
|
||||
-- мог появиться в bucket, есть учётная запись. Брошенные намерения
|
||||
-- старше grace period убирает reconciler (cmd/reconcile);
|
||||
-- ready — объект записан и проверен, метаданные заполнены; только такие
|
||||
-- вложения видны через API и прикрепляются к сообщениям;
|
||||
-- missing — reconciler не нашёл объект в S3 (карантин, API отвечает 503).
|
||||
CREATE TABLE attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id),
|
||||
filename TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL CHECK (status IN ('uploading', 'ready', 'missing')),
|
||||
content_type TEXT CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes BIGINT CHECK (size_bytes > 0),
|
||||
sha256 TEXT CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CHECK (status = 'uploading' OR (content_type IS NOT NULL AND size_bytes IS NOT NULL AND sha256 IS NOT NULL))
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
|
||||
-- Для reconciler: брошенные намерения и карантин по возрасту.
|
||||
CREATE INDEX attachments_status_updated_idx ON attachments(status, updated_at);
|
||||
-- Для merge-обхода в порядке ключей S3 (байтовый порядок, как в ListObjectsV2).
|
||||
CREATE INDEX attachments_object_key_c_idx ON attachments(object_key COLLATE "C");
|
||||
|
||||
-- Связь сообщения с вложениями; position сохраняет порядок attachment_ids.
|
||||
CREATE TABLE message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||
position SMALLINT NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments(attachment_id);
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Прогоняет проверки lab4 на запущенном Docker-стенде и сохраняет вывод в evidence/.
|
||||
# Токены и секреты не печатаются (тесты держат их в памяти, mc читает их внутри контейнера).
|
||||
#
|
||||
# sh scripts/collect-evidence.sh base # уровни 3–4 lab3 + smoke/persistence/failover lab4
|
||||
# sh scripts/collect-evidence.sh files # вложения: негативный набор, отказы S3/БД, приватность, память
|
||||
# sh scripts/collect-evidence.sh track2 # reconciler: внедрение расхождений и стоимость обхода
|
||||
# sh scripts/collect-evidence.sh all
|
||||
# Windows (Git Bash): PYTHON=python STOP=scripts/win/stop-one.cmd RESTART=scripts/win/restart.cmd sh scripts/collect-evidence.sh all
|
||||
cd "$(dirname "$0")/.."
|
||||
PY=${PYTHON:-python3}
|
||||
STOP=${STOP:-scripts/stop-one.sh}
|
||||
RESTART=${RESTART:-scripts/restart.sh}
|
||||
BASE=${BASE_URL:-http://localhost:8080}
|
||||
WHAT=${1:-all}
|
||||
export PYTHONUTF8=1
|
||||
mkdir -p evidence evidence/track2
|
||||
|
||||
step() { echo "== $*"; }
|
||||
|
||||
base() {
|
||||
step "состояние стенда и образы"
|
||||
{ date -u +%Y-%m-%dT%H:%M:%SZ; docker compose version; docker compose ps; } > evidence/docker_ps.txt
|
||||
for img in $(docker compose config --images | sort -u); do
|
||||
printf '%s %s\n' "$img" "$(docker image inspect --format '{{index .RepoDigests 0}}' "$img" 2>/dev/null || echo local-build)"
|
||||
done > evidence/images.txt
|
||||
cat evidence/images.txt
|
||||
|
||||
step "X-Instance-Id через LB"
|
||||
$PY - "$BASE" > evidence/instances.txt <<'EOF'
|
||||
import sys, urllib.request, collections
|
||||
seen = collections.Counter()
|
||||
for _ in range(20):
|
||||
with urllib.request.urlopen(sys.argv[1] + '/health/ready') as r:
|
||||
seen[r.headers['X-Instance-Id']] += 1
|
||||
for k, v in sorted(seen.items()):
|
||||
print(k, v)
|
||||
EOF
|
||||
cat evidence/instances.txt
|
||||
|
||||
step "smoke (lab4: вложение, checksum, посторонний)"
|
||||
$PY tests/smoke.py --base-url "$BASE" | tee evidence/smoke.txt
|
||||
|
||||
step "конкурентная идемпотентность"
|
||||
$PY student-tests/idempotency_concurrent.py --base-url "$BASE" --output evidence/idempotency_concurrent.json | tail -1
|
||||
|
||||
step "регрессии lab3"
|
||||
$PY student-tests/regressions.py --base-url "$BASE" > evidence/regressions.txt 2>&1
|
||||
cat evidence/regressions.txt
|
||||
|
||||
step "публичный failover lab4 (с проверкой оригинала), 2 прогона"
|
||||
for n in 1 2; do
|
||||
{ $PY tests/resilience.py --mode failover --action-script "$STOP" --base-url "$BASE" || echo "FAILED"; \
|
||||
echo "-- контейнеры api после stop-one:"; docker compose ps -a api --format '{{.Name}} {{.ID}} {{.Status}}'; } \
|
||||
> evidence/failover_$n.txt 2>&1
|
||||
cat evidence/failover_$n.txt
|
||||
sh scripts/restore.sh >> evidence/failover_$n.txt
|
||||
done
|
||||
|
||||
step "persistence lab4 (restart всего стенда, включая S3, с volumes)"
|
||||
{ echo "-- до:"; docker compose ps --format '{{.Name}} {{.Status}}'; \
|
||||
$PY tests/resilience.py --mode persistence --action-script "$RESTART" --base-url "$BASE" || echo "FAILED"; \
|
||||
echo "-- после:"; docker compose ps --format '{{.Name}} {{.Status}}'; } > evidence/persistence.txt 2>&1
|
||||
cat evidence/persistence.txt
|
||||
|
||||
step "серия отказов каждой реплики под нагрузкой"
|
||||
$PY student-tests/failover_series.py --base-url "$BASE" --output evidence/failover_series.json | tail -1
|
||||
|
||||
step "rolling update под нагрузкой"
|
||||
docker compose build -q api
|
||||
{ echo "-- до:"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Status}}'; } > evidence/rolling_update.txt
|
||||
$PY tests/load.py --base-url "$BASE" --duration 90 --concurrency 4 --output evidence/rolling_update_load.json > /dev/null &
|
||||
LOAD=$!
|
||||
sleep 5
|
||||
start=$(date +%s)
|
||||
sh scripts/rolling-update.sh >> evidence/rolling_update.txt 2>&1
|
||||
echo "-- замена заняла $(( $(date +%s) - start )) s (внутри 90 s нагрузки)" >> evidence/rolling_update.txt
|
||||
wait $LOAD
|
||||
tail -4 evidence/rolling_update.txt; cat evidence/rolling_update_load.json
|
||||
}
|
||||
|
||||
files() {
|
||||
step "негативный набор вложений"
|
||||
$PY student-tests/attachments_negative.py --base-url "$BASE" > evidence/attachments_negative.txt 2>&1
|
||||
tail -3 evidence/attachments_negative.txt
|
||||
for s in failover s3-outage interrupt security db-gap memory; do
|
||||
step "вложения: $s"
|
||||
$PY student-tests/attachments_ops.py "$s" --base-url "$BASE" --output "evidence/files_$s.json" | tail -1
|
||||
done
|
||||
docker compose logs --no-color api 2>&1 | grep -E 'compensat|s3 get failed|object missing' | tail -20 > evidence/compensation_log.txt || true
|
||||
}
|
||||
|
||||
track2() {
|
||||
step "reconciler: внедрение расхождений с обеих сторон"
|
||||
$PY student-tests/reconcile_faults.py --base-url "$BASE" --output evidence/track2/faults.json | tail -1
|
||||
step "reconciler: стоимость обхода"
|
||||
$PY student-tests/reconcile_cost.py --base-url "$BASE" --sizes "${COST_SIZES:-1000,10000,30000}" \
|
||||
--output evidence/track2/cost.json | tail -1
|
||||
}
|
||||
|
||||
case "$WHAT" in
|
||||
base) base ;;
|
||||
files) files ;;
|
||||
track2) track2 ;;
|
||||
all) base; files; track2 ;;
|
||||
*) echo "usage: $0 base|files|track2|all" >&2; exit 2 ;;
|
||||
esac
|
||||
docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' > "evidence/docker_stats_$WHAT.txt"
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Создаёт локальные .env и secrets/ для учебного стенда. Повторный запуск ничего
|
||||
# не перезаписывает (иначе пароль разойдётся с уже инициализированным volume).
|
||||
cd "$(dirname "$0")/.."
|
||||
[ -f .env ] || cp .env.example .env
|
||||
mkdir -p secrets
|
||||
if [ ! -f secrets/postgres_password ]; then
|
||||
# 32 случайных байта в hex — без символов, требующих экранирования в URL.
|
||||
pw=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
|
||||
printf '%s' "$pw" > secrets/postgres_password
|
||||
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' "$pw" > secrets/database_url
|
||||
fi
|
||||
[ -f secrets/cache_url ] || printf '%s' 'redis://redis:6379/0' > secrets/cache_url
|
||||
rnd() { od -An -N"$1" -tx1 /dev/urandom | tr -d ' \n'; }
|
||||
# MinIO: root — только для s3 и s3-init; отдельный ключ API с правами на один bucket.
|
||||
[ -f secrets/s3_root_user ] || printf 'root-%s' "$(rnd 6)" > secrets/s3_root_user
|
||||
[ -f secrets/s3_root_password ] || printf '%s' "$(rnd 24)" > secrets/s3_root_password
|
||||
[ -f secrets/s3_access_key_id ] || printf 'api-%s' "$(rnd 8)" > secrets/s3_access_key_id
|
||||
[ -f secrets/s3_secret_access_key ] || printf '%s' "$(rnd 24)" > secrets/s3_secret_access_key
|
||||
chmod 600 secrets/* 2>/dev/null || true
|
||||
echo "secrets ready in ./secrets (values not printed)"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Перезапускает API, LB, reconciler и все хранилища (PostgreSQL, Redis, S3) с сохранением volumes.
|
||||
# Никаких down -v / FLUSH / повторного seed.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop lb api reconciler
|
||||
docker compose restart postgres redis s3
|
||||
|
||||
until docker compose exec -T postgres pg_isready -U messenger -d messenger >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
until docker compose exec -T redis redis-cli ping >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
until docker compose exec -T s3 mc ready local >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
docker compose start api lb reconciler
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Запускает остановленные stop-one.sh API-реплики и ждёт их готовности.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose start api >/dev/null
|
||||
deadline=$(( $(date +%s) + 60 ))
|
||||
while :; do
|
||||
bad=0
|
||||
for cid in $(docker compose ps -aq api); do
|
||||
st=$(docker inspect -f '{{.State.Health.Status}}' "$cid")
|
||||
[ "$st" = healthy ] || bad=1
|
||||
done
|
||||
[ $bad -eq 0 ] && break
|
||||
[ "$(date +%s)" -lt $deadline ] || { echo "api replicas not healthy in 60s" >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
docker compose ps api --format '{{.Name}} {{.Status}}'
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Поочерёдная замена API-реплик без остановки сервиса (Compose).
|
||||
# Для каждой старой реплики: поднять одну новую → дождаться healthy (LB сам
|
||||
# найдёт её через DNS) → остановить старую (drain) → удалить.
|
||||
# Миграции выполняются ДО замены отдельным сервисом migrate и должны быть
|
||||
# совместимы со старой версией (expand → contract).
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose build api
|
||||
docker compose run --rm migrate >/dev/null
|
||||
|
||||
wait_healthy() {
|
||||
want=$1; deadline=$(( $(date +%s) + 90 ))
|
||||
while :; do
|
||||
n=0
|
||||
# Своё имя переменной: в sh у функций общая область видимости, и `cid`
|
||||
# перезаписал бы переменную внешнего цикла (тогда удалялась бы новая реплика).
|
||||
for c in $(docker compose ps -q api); do
|
||||
[ "$(docker inspect -f '{{.State.Health.Status}}' "$c")" = healthy ] && n=$((n+1))
|
||||
done
|
||||
[ $n -ge "$want" ] && return 0
|
||||
[ "$(date +%s)" -lt $deadline ] || { echo "new replica not healthy in 90s" >&2; return 1; }
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
old=$(docker compose ps -q api)
|
||||
for cid in $old; do
|
||||
cur=$(docker compose ps -q api | wc -l | tr -d ' ')
|
||||
docker compose up -d --no-deps --no-recreate --scale api=$((cur + 1)) api
|
||||
wait_healthy $((cur + 1))
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid")
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
docker rm "$cid" >/dev/null
|
||||
echo "replaced $name"
|
||||
done
|
||||
docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}} {{.Status}}'
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Останавливает ОДНУ API-реплику, чей X-Instance-Id передан в TARGET_INSTANCE_ID,
|
||||
# и оставляет её остановленной. X-Instance-Id = hostname контейнера = префикс его ID.
|
||||
# БД, Redis, LB и volumes не трогаются. Восстановление: scripts/restore.sh.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]*) echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
[ ${#TARGET_INSTANCE_ID} -ge 12 ] || { echo "instance id too short" >&2; exit 2; }
|
||||
for cid in $(docker compose ps -q api); do
|
||||
case "$cid" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid")
|
||||
# SIGTERM → API отвечает 503 на /health/ready (DRAIN_DELAY), LB исключает её,
|
||||
# затем http.Server.Shutdown дожидается текущих запросов.
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
echo "stopped $name ($TARGET_INSTANCE_ID)"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
echo "no running api container matches $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\restart.sh" %*
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\restore.sh" %*
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\stop-one.sh" %*
|
||||
Executable
+139
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (уровень 4).
|
||||
|
||||
Покрывает: слишком большой файл (по Content-Length и по пикселям), «бомбу»,
|
||||
повреждённое изображение, подмену MIME, чужой формат, опасные filename,
|
||||
чужое attachment_id, вложение другого чата, правила text/attachment_ids,
|
||||
идемпотентность с вложениями, варианты. Любой 500 — провал (Client проверяет код).
|
||||
"""
|
||||
import hashlib
|
||||
import uuid
|
||||
from lab4util import bomb_png, fixture, noise_png, png, raw_post
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
MAX = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative suite (lab4 level 4)')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
results = []
|
||||
|
||||
def up(name, data, ctype, expected, chat_path=path, actor=alice):
|
||||
r = c.call('POST', chat_path + name, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 201 else None)
|
||||
results.append((name[:40], ctype, len(data), r['status']))
|
||||
return r
|
||||
|
||||
small_png, small_jpg = fixture('small.png'), fixture('small.jpg')
|
||||
|
||||
# --- корректные файлы ---
|
||||
a_png = up('ok.png', small_png, 'image/png', 201)['json']
|
||||
a_jpg = up('ok.jpg', small_jpg, 'image/jpeg', 201)['json']
|
||||
check(a_jpg['content_type'] == 'image/jpeg' and a_jpg['sha256'] == hashlib.sha256(small_jpg).hexdigest(), 'jpeg metadata')
|
||||
uni = up('%D1%84%D0%BE%D1%82%D0%BE%20%F0%9F%98%80.png', small_png, 'image/png', 201)['json']
|
||||
check(uni['filename'] == 'фото 😀.png', 'unicode filename not preserved')
|
||||
up('params.png', small_png, 'image/png; charset=binary', 201)
|
||||
near = noise_png(MAX - 200_000)
|
||||
check(len(near) <= MAX, 'generator produced too large file')
|
||||
big_ok = up('near-limit.png', near, 'image/png', 201)['json']
|
||||
got = c.call('GET', '/api/v1/attachments/' + big_ok['id'] + '/content', actor=bob)
|
||||
check(got['bytes'] == near, 'near-limit file changed on download')
|
||||
|
||||
# --- размер и пиксели ---
|
||||
# Content-Length больше лимита: 413 сразу, без чтения тела.
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}
|
||||
st, _ = raw_post(c.base, path + 'too-big.png', dict(hdr, **{'Content-Length': str(MAX + 1)}),
|
||||
(b'\x89PNG\r\n\x1a\n' + b'\0' * 65528 for _ in range(1)))
|
||||
check(st == 413, 'Content-Length > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big.png (Content-Length)', 'image/png', MAX + 1, st))
|
||||
# Без Content-Length (chunked), реально 11 MiB: сервер читает не больше лимита + 1 байт.
|
||||
def chunked(total=11 * 1024 * 1024, part=256 * 1024):
|
||||
yield b'%x\r\n\x89PNG\r\n\x1a\n\r\n' % 8
|
||||
sent = 8
|
||||
while sent < total:
|
||||
yield b'%x\r\n' % part + b'\0' * part + b'\r\n'
|
||||
sent += part
|
||||
yield b'0\r\n\r\n'
|
||||
st, _ = raw_post(c.base, path + 'too-big-chunked.png', dict(hdr, **{'Transfer-Encoding': 'chunked'}), chunked())
|
||||
check(st == 413, 'chunked > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big-chunked.png (no Content-Length)', 'image/png', 11 * 1024 * 1024, st))
|
||||
up('bomb.png', bomb_png(), 'image/png', 413)
|
||||
up('over-pixels.png', bomb_png(8000, 5001), 'image/png', 413)
|
||||
|
||||
# --- содержимое и MIME ---
|
||||
up('truncated.png', small_png[:len(small_png) // 2], 'image/png', 415)
|
||||
broken = bytearray(small_png)
|
||||
broken[len(broken) // 2] ^= 0xFF
|
||||
up('corrupt.png', bytes(broken), 'image/png', 415)
|
||||
up('truncated.jpg', small_jpg[:len(small_jpg) - 2], 'image/jpeg', 415)
|
||||
up('mime-swap.png', small_png, 'image/jpeg', 415) # PNG, объявлен как JPEG
|
||||
up('mime-swap.jpg', small_jpg, 'image/png', 415)
|
||||
up('text.png', b'definitely not an image', 'image/png', 415)
|
||||
up('gif.gif', b'GIF89a\x01\x00\x01\x00\x00\x00\x00;', 'image/gif', 415)
|
||||
up('ctype-missing.png', small_png, 'application/octet-stream', 415)
|
||||
up('empty.png', b'', 'image/png', 415)
|
||||
up('short-data.png', png(8, 8, raw=b'\x00' * 10), 'image/png', 415)
|
||||
|
||||
# --- filename ---
|
||||
for bad in ('..%2Fetc%2Fpasswd', 'a%5Cb.png', 'nul%00.png', 'bell%07.png', '%20%20%20', 'x' * 256, ''):
|
||||
up(bad, small_png, 'image/png', 400)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=small_png,
|
||||
headers={'Content-Type': 'image/png'})
|
||||
c.call('POST', path + 'a.png&filename=b.png', 400, actor=alice, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
|
||||
# --- доступ ---
|
||||
up('eve.png', small_png, 'image/png', 404, actor=eve)
|
||||
c.call('POST', path + 'anon.png', 401, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
c.call('GET', '/api/v1/attachments/not-a-uuid' + suffix, 400, actor=alice)
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=thumbnail', 404, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=bogus', 400, actor=bob)
|
||||
orig = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=original', actor=bob)
|
||||
check(orig['bytes'] == small_png and orig['headers'].get_content_type() == 'image/png', 'original variant')
|
||||
|
||||
# --- сообщения с вложениями ---
|
||||
foreign = up('foreign.png', small_png, 'image/png', 201,
|
||||
chat_path='/api/v1/chats/' + other['id'] + '/attachments?filename=')['json']
|
||||
mpath = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def msg(body, expected, key=None, actor=alice):
|
||||
return c.call('POST', mpath, expected, actor=actor, body=body,
|
||||
headers={'Idempotency-Key': key or uuid.uuid4().hex},
|
||||
schema='Message' if expected == 201 else None)
|
||||
|
||||
msg({'text': '', 'attachment_ids': [foreign['id']]}, 404) # вложение другого чата
|
||||
msg({'text': '', 'attachment_ids': [str(uuid.uuid4())]}, 404) # неизвестное
|
||||
msg({'text': 'x', 'attachment_ids': ['nope']}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [a_png['id'], a_png['id']]}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
|
||||
msg({'text': ''}, 400)
|
||||
msg({'text': ' ', 'attachment_ids': []}, 400)
|
||||
msg({'attachment_ids': [a_png['id']]}, 400) # text обязателен
|
||||
msg({'text': '', 'attachment_ids': [a_png['id']]}, 404, actor=eve)
|
||||
key = uuid.uuid4().hex
|
||||
m1 = msg({'text': '', 'attachment_ids': [a_png['id'], a_jpg['id']]}, 201, key=key)['json']
|
||||
check(m1['attachment_ids'] == [a_png['id'], a_jpg['id']] and m1['text'] == '', 'attachment order/text')
|
||||
m2 = msg({'attachment_ids': [a_png['id'], a_jpg['id']], 'text': ''}, 201, key=key)['json']
|
||||
check(m2 == m1, 'idempotent replay with attachments differs')
|
||||
msg({'text': '', 'attachment_ids': [a_jpg['id'], a_png['id']]}, 409, key=key) # другой порядок = другое тело
|
||||
plain = msg({'text': 'без вложений'}, 201)['json']
|
||||
check(plain['attachment_ids'] == [], 'missing attachment_ids must be []')
|
||||
hist = c.call('GET', mpath + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(m == m1 for m in hist), 'message with attachments not in history')
|
||||
# Bob (участник) прикрепляет вложение Alice — допустимо.
|
||||
msg({'text': 'и я', 'attachment_ids': [a_png['id']]}, 201, actor=bob)
|
||||
|
||||
for row in results:
|
||||
print('%-42s %-28s %9d -> %d' % row)
|
||||
print('PASS: attachment negative suite (%d upload cases, no 5xx)' % len(results))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+263
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операционные сценарии вложений на Docker-стенде (уровни 3–4).
|
||||
|
||||
failover upload → остановить обслужившую реплику → download через другую
|
||||
s3-outage остановить S3: загрузка/скачивание 503, текстовый чат и readiness работают
|
||||
interrupt обрыв клиента посреди тела: ни ready-вложения, ни намерения, ни объекта
|
||||
db-gap PUT в S3 прошёл, PostgreSQL недоступен на MarkReady: объект удалён
|
||||
компенсацией, намерение осталось → убирает reconciler
|
||||
security bucket приватен (анонимно 403), у API-ключа нет прав вне bucket,
|
||||
bootstrap идемпотентен, консоль/порты S3 не опубликованы
|
||||
memory N одновременных загрузок ~9.8 MiB: пик памяти (cgroup memory.peak) реплик
|
||||
|
||||
Каждый сценарий печатает JSON-итог и PASS/FAIL.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from lab4util import (BUCKET, api_container, compose, fixture, mc, noise_png, object_key, psql, raw_post, sh)
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, name='f.png', ctype='image/png', expected=201):
|
||||
return c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), expected,
|
||||
actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 201 else None)
|
||||
|
||||
|
||||
def wait_ready(c, timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure('stack not ready')
|
||||
|
||||
|
||||
def scenario_failover(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = noise_png(2 * 1024 * 1024)
|
||||
r = upload(c, alice, chat, data)
|
||||
att, served_by = r['json'], r['headers']['X-Instance-Id']
|
||||
cid = api_container(served_by)
|
||||
sh('docker', 'stop', '-t', '15', cid)
|
||||
try:
|
||||
seen = set()
|
||||
for _ in range(6):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'downloaded bytes differ after failover')
|
||||
seen.add(d['headers']['X-Instance-Id'])
|
||||
check(served_by not in seen, 'stopped replica still serving')
|
||||
finally:
|
||||
sh('docker', 'start', cid)
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
return {'uploaded_by': served_by, 'downloaded_by': sorted(seen), 'sha256': hashlib.sha256(data).hexdigest(),
|
||||
'stopped_container': cid[:12]}
|
||||
|
||||
|
||||
def scenario_s3_outage(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
small = fixture('small.png')
|
||||
att = upload(c, alice, chat, small)['json']
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
t0 = time.time()
|
||||
up = upload(c, alice, chat, small, expected=503)
|
||||
up_s = time.time() - t0
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 503, actor=bob)
|
||||
meta = c.call('GET', '/api/v1/attachments/%s' % att['id'], actor=bob, schema='Attachment')['json']
|
||||
msg = c.message(alice, chat, 'S3 лежит, а чат работает')['json']
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
leftovers = psql("SELECT count(*) FROM attachments WHERE chat_id = '%s' AND status = 'uploading'" % chat['id'])
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
compose('run', '--rm', 's3-init')
|
||||
for _ in range(30):
|
||||
try:
|
||||
again = upload(c, alice, chat, small)['json']
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise Failure('upload did not recover after S3 start')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == small, 'old attachment changed after S3 restart')
|
||||
check(leftovers == '0', 'intent rows left after failed upload: ' + leftovers)
|
||||
return {'upload_status_during_outage': up['status'], 'upload_error_seconds': round(up_s, 2),
|
||||
'download_status_during_outage': 503, 'metadata_during_outage': meta['status'],
|
||||
'text_message_during_outage': 201, 'readiness_during_outage': 200,
|
||||
'intents_left': int(leftovers), 'upload_after_recovery': again['status']}
|
||||
|
||||
|
||||
def scenario_interrupt(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(4 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png',
|
||||
'Content-Length': str(len(data))}
|
||||
# Отправляем 1 MiB из 4 и обрываем соединение.
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(c.base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80))
|
||||
head = 'POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n' % (chat['id'], u.netloc)
|
||||
s.sendall((head + ''.join('%s: %s\r\n' % kv for kv in hdr.items()) + '\r\n').encode())
|
||||
s.sendall(data[:1024 * 1024])
|
||||
time.sleep(1)
|
||||
s.close()
|
||||
time.sleep(3)
|
||||
rows = psql("SELECT status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
objs = mc('mc ls --recursive s3/%s/a/%s/ | wc -l' % (BUCKET, chat['id'])).stdout.strip()
|
||||
check(rows == '', 'rows left after interrupted upload: %r' % rows)
|
||||
check(objs == '0', 'objects left after interrupted upload: ' + objs)
|
||||
return {'sent_bytes': 1024 * 1024, 'declared_bytes': len(data), 'rows_after': 0, 'objects_after': 0}
|
||||
|
||||
|
||||
def scenario_db_gap(c):
|
||||
"""PUT прошёл, а PostgreSQL «пропал» до MarkReady (docker pause)."""
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(3 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png', 'Content-Length': str(len(data))}
|
||||
state = {}
|
||||
|
||||
def body():
|
||||
yield data[:512 * 1024] # намерение уже записано, PUT идёт
|
||||
time.sleep(2)
|
||||
compose('pause', 'postgres') # БД «пропала» до MarkReady
|
||||
state['paused_at'] = time.time()
|
||||
yield data[512 * 1024:]
|
||||
t0 = time.time()
|
||||
try:
|
||||
st, _ = raw_post(c.base, '/api/v1/chats/%s/attachments?filename=gap.png' % chat['id'], hdr, body(), read_timeout=60)
|
||||
finally:
|
||||
# Дольше таймаута запроса (30 s) и компенсации (10 s): DeleteIntent тоже не пройдёт.
|
||||
time.sleep(max(0, 45 - (time.time() - state.get('paused_at', time.time()))))
|
||||
compose('unpause', 'postgres')
|
||||
wait_ready(c)
|
||||
rows = psql("SELECT id || ' ' || status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
objs = mc('mc ls --recursive s3/%s/a/%s/ | wc -l' % (BUCKET, chat['id'])).stdout.strip()
|
||||
check(st != 201, 'upload must not report success when metadata was not committed (got %s)' % st)
|
||||
check(rows.endswith(' uploading'), 'expected one leftover intent, got %r' % rows)
|
||||
check(objs == '0', 'compensation must delete the object, objects=' + objs)
|
||||
# Reconciler (короткий grace для теста) убирает брошенное намерение.
|
||||
psql("UPDATE attachments SET updated_at = now() - interval '30 minutes' WHERE chat_id = '%s'" % chat['id'])
|
||||
out = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--apply', '--grace', '10m').stdout.strip().splitlines()[-1]
|
||||
rep = json.loads(out)
|
||||
after = psql("SELECT count(*) FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
check(after == '0', 'reconciler did not remove stale intent')
|
||||
return {'client_status': st, 'seconds': round(time.time() - t0, 1), 'after_gap': {'rows': rows.split()[-1], 'objects': int(objs)},
|
||||
'reconciler_fixed': rep['fixed'], 'rows_after_reconcile': int(after)}
|
||||
|
||||
|
||||
def scenario_security(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, fixture('small.png'))['json']
|
||||
key = object_key(att['id'])
|
||||
url = 'http://s3:9000/%s/%s' % (BUCKET, key)
|
||||
# Анонимно изнутри сети стенда (из контейнера API): объект и листинг закрыты.
|
||||
anon_get = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null', url, check=False)
|
||||
anon_list = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null',
|
||||
'http://s3:9000/%s?list-type=2' % BUCKET, check=False)
|
||||
check(anon_get.returncode != 0 and '403' in anon_get.stderr, 'anonymous GET must be 403')
|
||||
check(anon_list.returncode != 0 and '403' in anon_list.stderr, 'anonymous LIST must be 403')
|
||||
# Ключ API: свой bucket — да, остальное — нет.
|
||||
own = mc('mc stat s3/%s/%s >/dev/null && echo ok' % (BUCKET, key), as_user='api').stdout.strip()
|
||||
mb = mc('mc mb s3/evil-bucket-%s' % uuid.uuid4().hex[:6], check=False, as_user='api')
|
||||
admin = mc('mc admin user list s3', check=False, as_user='api')
|
||||
buckets = mc('mc ls s3', check=False, as_user='api')
|
||||
check(own == 'ok', 'api key cannot read own bucket')
|
||||
check(mb.returncode != 0, 'api key must not create buckets')
|
||||
check(admin.returncode != 0, 'api key must not use admin API')
|
||||
check(buckets.returncode != 0 or BUCKET not in buckets.stdout or 'evil' not in buckets.stdout, 'unexpected bucket listing')
|
||||
# Bootstrap идемпотентен: повторный запуск успешен, объект на месте.
|
||||
before = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
r1 = compose('run', '--rm', 's3-init')
|
||||
r2 = compose('run', '--rm', 's3-init')
|
||||
after = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
check(before == after, 'bootstrap changed objects')
|
||||
ports = compose('ps', 's3', '--format', '{{.Ports}}').stdout.strip()
|
||||
check('0.0.0.0' not in ports and '127.0.0.1' not in ports, 's3 port is published: ' + ports)
|
||||
return {'anonymous_get': '403', 'anonymous_list': '403', 'api_key_own_bucket': 'allowed',
|
||||
'api_key_make_bucket': 'denied', 'api_key_admin': 'denied',
|
||||
'api_key_list_all_buckets': 'denied' if buckets.returncode != 0 else 'allowed',
|
||||
'bootstrap_runs': [r1.returncode, r2.returncode], 'objects_before_after': [int(before), int(after)],
|
||||
's3_published_ports': ports or 'none'}
|
||||
|
||||
|
||||
def read_peak(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def read_current(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.current', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def scenario_memory(c, parallel_levels=(10, 20)):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(10 * 1024 * 1024 - 300_000)
|
||||
out = {'file_bytes': len(data), 'runs': []}
|
||||
for n in parallel_levels:
|
||||
compose('restart', 'api') # новый cgroup → memory.peak с нуля
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
wait_ready(c)
|
||||
cids = compose('ps', '-q', 'api').stdout.split()
|
||||
upload(c, alice, chat, fixture('small.png')) # прогрев пулов/соединений
|
||||
base = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
barrier = threading.Barrier(n)
|
||||
res = []
|
||||
|
||||
def worker():
|
||||
local = Client(c.base, timeout=60)
|
||||
barrier.wait()
|
||||
t0 = time.time()
|
||||
try:
|
||||
upload(local, alice, chat, data, name='mem.png')
|
||||
res.append(('ok', time.time() - t0))
|
||||
except Failure as e:
|
||||
res.append(('fail:' + str(e)[:60], time.time() - t0))
|
||||
ths = [threading.Thread(target=worker) for _ in range(n)]
|
||||
for t in ths:
|
||||
t.start()
|
||||
for t in ths:
|
||||
t.join()
|
||||
peak = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
ok = sum(1 for r in res if r[0] == 'ok')
|
||||
mib = lambda v: round(v / 1048576, 1) if v else None
|
||||
run = {'parallel': n, 'ok': ok, 'failed': [r[0] for r in res if r[0] != 'ok'],
|
||||
'max_seconds': round(max(r[1] for r in res), 2),
|
||||
'baseline_peak_mib': {k: mib(v) for k, v in base.items()},
|
||||
'peak_mib': {k: mib(v) for k, v in peak.items()},
|
||||
'payload_total_mib': round(n * len(data) / 1048576, 1)}
|
||||
growth = [peak[k] - base[k] for k in peak if peak[k] and base[k]]
|
||||
run['max_peak_growth_mib'] = mib(max(growth)) if growth else None
|
||||
out['runs'].append(run)
|
||||
check(ok == n, '%d of %d concurrent uploads failed: %s' % (n - ok, n, run['failed'][:3]))
|
||||
return out
|
||||
|
||||
|
||||
SCENARIOS = {'failover': scenario_failover, 's3-outage': scenario_s3_outage, 'interrupt': scenario_interrupt,
|
||||
'db-gap': scenario_db_gap, 'security': scenario_security, 'memory': scenario_memory}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Docker-level attachment scenarios (lab4)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+174
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Серия отказов под нагрузкой (уровень 4): поочерёдно останавливает КАЖДУЮ
|
||||
API-реплику (docker stop → SIGTERM → drain), восстанавливает её и переходит
|
||||
к следующей. Во время всей серии идёт closed-loop нагрузка через LB:
|
||||
POST сообщения (при ошибке повтор с тем же Idempotency-Key) и GET истории.
|
||||
|
||||
Измеряется на каждую реплику: RPS до/во время/после, число ошибок, время от
|
||||
начала остановки до последней ошибки (recovery), время до исчезновения реплики
|
||||
из ответов LB и время восстановления реплики после docker start.
|
||||
В конце проверяется: все подтверждённые сообщения на месте, дублей нет.
|
||||
|
||||
Скрипт сам вызывает docker CLI (это не публичный тест), запускать из корня репозитория.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
return docker('compose', 'ps', '-q', 'api').split()
|
||||
|
||||
|
||||
def health(cid):
|
||||
return docker('inspect', '-f', '{{.State.Health.Status}}', cid)
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, args, actor, reader, chat, concurrency):
|
||||
self.args, self.actor, self.reader, self.chat = args, actor, reader, chat
|
||||
self.concurrency = concurrency
|
||||
self.events = [] # (t, kind, ok, instance)
|
||||
self.confirmed = [] # подтверждённые Message
|
||||
self.lock = threading.Lock()
|
||||
self.stop = threading.Event()
|
||||
|
||||
def record(self, kind, ok, instance=None):
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), kind, ok, instance))
|
||||
|
||||
def worker(self, n):
|
||||
c = Client(self.args.base_url, self.args.ca_file, timeout=3)
|
||||
path = '/api/v1/chats/' + self.chat['id'] + '/messages?limit=20'
|
||||
key, text, i = None, None, 0
|
||||
while not self.stop.is_set():
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'series-%d-%d-%s' % (n, i, key)
|
||||
i += 1
|
||||
try:
|
||||
r = c.message(self.actor, self.chat, text, key=key)
|
||||
self.record('write', True, r['headers'].get('X-Instance-Id'))
|
||||
with self.lock:
|
||||
self.confirmed.append(r['json'])
|
||||
key = None
|
||||
except Failure:
|
||||
self.record('write', False) # неопределённый результат: тот же ключ
|
||||
try:
|
||||
r = c.call('GET', path, actor=self.reader, schema='MessagePage')
|
||||
self.record('read', True, r['headers'].get('X-Instance-Id'))
|
||||
except Failure:
|
||||
self.record('read', False)
|
||||
|
||||
def __enter__(self):
|
||||
self.pool = ThreadPoolExecutor(max_workers=self.concurrency)
|
||||
self.futures = [self.pool.submit(self.worker, n) for n in range(self.concurrency)]
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
for f in self.futures:
|
||||
f.result()
|
||||
self.pool.shutdown()
|
||||
|
||||
def window(self, a, b):
|
||||
with self.lock:
|
||||
ev = [e for e in self.events if a <= e[0] < b]
|
||||
ok = sum(1 for e in ev if e[2])
|
||||
return {'seconds': round(b - a, 2), 'ok': ok, 'errors': len(ev) - ok,
|
||||
'ok_rps': round(ok / (b - a), 1) if b > a else None}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--concurrency', type=int, default=4)
|
||||
p.add_argument('--warmup', type=float, default=5)
|
||||
p.add_argument('--observe', type=float, default=15)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Stop each API replica in turn under load; collect RPS/errors/recovery', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, 'need at least 2 api containers')
|
||||
results = []
|
||||
with Load(args, alice, bob, chat, args.concurrency) as load:
|
||||
time.sleep(args.warmup)
|
||||
for cid in replicas:
|
||||
target = cid[:12]
|
||||
before_start = time.monotonic() - args.warmup
|
||||
t0 = time.monotonic()
|
||||
docker('stop', '-t', '15', cid)
|
||||
stop_seconds = time.monotonic() - t0
|
||||
time.sleep(max(0.0, args.observe - stop_seconds))
|
||||
t_end = time.monotonic()
|
||||
with load.lock:
|
||||
after = [e for e in load.events if e[0] >= t0]
|
||||
errs = [e[0] for e in after if not e[2]]
|
||||
served = [e[0] for e in after if e[2] and e[3] == target]
|
||||
row = {
|
||||
'target_instance': target,
|
||||
'docker_stop_seconds': round(stop_seconds, 2),
|
||||
'before': load.window(before_start, t0),
|
||||
'during_stop_and_observe': load.window(t0, t_end),
|
||||
'errors_after_stop': len(errs),
|
||||
'recovery_seconds': round(max(errs) - t0, 2) if errs else 0.0,
|
||||
'target_last_served_after_stop_seconds': round(max(served) - t0, 2) if served else None,
|
||||
'other_instances_after': sorted({e[3] for e in after if e[2] and e[3] != target}),
|
||||
}
|
||||
# Восстановление реплики и её возврат в балансировку.
|
||||
r0 = time.monotonic()
|
||||
docker('start', cid)
|
||||
while health(cid) != 'healthy':
|
||||
check(time.monotonic() - r0 < 60, 'replica did not become healthy')
|
||||
time.sleep(0.5)
|
||||
healthy_at = time.monotonic() - r0
|
||||
while True:
|
||||
with load.lock:
|
||||
seen = any(e[0] > r0 and e[2] and e[3] == target for e in load.events)
|
||||
if seen:
|
||||
break
|
||||
check(time.monotonic() - r0 < 60, 'replica not seen behind LB after restore')
|
||||
time.sleep(0.2)
|
||||
row['restore_healthy_seconds'] = round(healthy_at, 2)
|
||||
row['restore_serving_via_lb_seconds'] = round(time.monotonic() - r0, 2)
|
||||
results.append(row)
|
||||
print(json.dumps(row, ensure_ascii=False))
|
||||
time.sleep(3)
|
||||
total = load.window(load.events[0][0], time.monotonic())
|
||||
confirmed = list(load.confirmed)
|
||||
|
||||
messages = history(c, bob, chat)
|
||||
ids = [m['id'] for m in messages]
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(ids) == len(set(ids)), 'duplicated message IDs')
|
||||
check(len(texts) == len(set(texts)), 'retry with same key created a duplicate')
|
||||
by_id = {m['id']: m for m in messages}
|
||||
lost = [m for m in confirmed if by_id.get(m['id']) != m]
|
||||
check(not lost, '%d confirmed messages lost/changed' % len(lost))
|
||||
summary = {'concurrency': args.concurrency, 'replicas': len(replicas), 'total': total,
|
||||
'confirmed_writes': len(confirmed), 'stored_messages': len(messages),
|
||||
'duplicates': 0, 'lost_confirmed': 0, 'per_replica': results}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(text)
|
||||
print('PASS: every replica stopped and restored under load; no lost or duplicated messages.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 900 B |
Binary file not shown.
|
After Width: | Height: | Size: 106 B |
@@ -0,0 +1,47 @@
|
||||
// Command genfixtures пишет маленькие синтетические изображения для собственных
|
||||
// тестов (student-tests/fixtures). Большие и вредоносные файлы тесты генерируют
|
||||
// сами в памяти — в Git они не хранятся.
|
||||
//
|
||||
// go run ./student-tests/genfixtures
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func img(w, h int) *image.RGBA {
|
||||
m := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
m.Set(x, y, color.RGBA{uint8(x * 4), uint8(y * 4), 128, 255})
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func main() {
|
||||
dir := filepath.Join("student-tests", "fixtures")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var j bytes.Buffer
|
||||
if err := jpeg.Encode(&j, img(64, 48), &jpeg.Options{Quality: 85}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var p bytes.Buffer
|
||||
if err := png.Encode(&p, img(40, 30)); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for name, data := range map[string][]byte{"small.jpg": j.Bytes(), "small.png": p.Bytes()} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентный повтор POST сообщения с одним Idempotency-Key через LB (lab3).
|
||||
|
||||
Каждый раунд: N потоков (каждый со своим соединением) по барьеру одновременно
|
||||
отправляют одинаковый body с одинаковым ключом. Ожидаем: все ответы 201 с одним
|
||||
и тем же Message, запросы обслужены ≥2 репликами, в истории ровно одно сообщение.
|
||||
Затем тот же ключ с другим body — 409; тот же ключ в другом чате — новое сообщение.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--rounds', type=int, default=10)
|
||||
p.add_argument('--parallel', type=int, default=16)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Concurrent Idempotency-Key replay across replicas', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Второй чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
|
||||
|
||||
rounds = []
|
||||
all_instances = set()
|
||||
for r in range(args.rounds):
|
||||
key = 'conc-' + uuid.uuid4().hex
|
||||
text = 'Конкурентный повтор %d %s' % (r, key)
|
||||
barrier = threading.Barrier(args.parallel)
|
||||
|
||||
def worker(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier.wait()
|
||||
try:
|
||||
resp = local.message(alice, chat, text, key=key)
|
||||
return resp['status'], resp['json'], resp['headers'].get('X-Instance-Id')
|
||||
except Failure as exc:
|
||||
return 'fail', str(exc), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
results = list(pool.map(worker, range(args.parallel)))
|
||||
statuses = [s for s, _, _ in results]
|
||||
check(all(s == 201 for s in statuses), 'round %d: not all 201: %s' % (r, statuses))
|
||||
bodies = {json.dumps(b, sort_keys=True) for _, b, _ in results}
|
||||
check(len(bodies) == 1, 'round %d: replays returned different messages' % r)
|
||||
instances = {i for _, _, i in results}
|
||||
all_instances |= instances
|
||||
stored = [m for m in history(c, bob, chat) if m['text'] == text]
|
||||
check(len(stored) == 1, 'round %d: %d messages stored for one key' % (r, len(stored)))
|
||||
# Другой body с тем же ключом — 409, не новое сообщение.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': text + ' (изменён)'}, headers={'Idempotency-Key': key})
|
||||
rounds.append({'round': r, 'requests': args.parallel, 'status_201': statuses.count(201),
|
||||
'distinct_messages': len(bodies), 'stored': len(stored), 'instances': len(instances)})
|
||||
|
||||
# Ключ уникален в пределах чата: тот же ключ в другом чате создаёт своё сообщение.
|
||||
key = 'scope-' + uuid.uuid4().hex
|
||||
a = c.message(alice, chat, 'scope', key=key)['json']
|
||||
b = c.message(alice, other, 'scope', key=key)['json']
|
||||
check(a['id'] != b['id'], 'key leaked across chats')
|
||||
# Другой пользователь с тем же ключом — тоже независим.
|
||||
d = c.message(bob, chat, 'scope', key=key)['json']
|
||||
check(d['id'] != a['id'], 'key leaked across users')
|
||||
# Без ключа и с неверным ключом — 400.
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'bad key!'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'k' * 129})
|
||||
# Повтор проверяет доступ: посторонний с тем же ключом получает 404.
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'scope'}, headers={'Idempotency-Key': key})
|
||||
|
||||
check(len(all_instances) >= 2, 'concurrent requests were served by fewer than 2 replicas')
|
||||
summary = {'rounds': args.rounds, 'parallel_per_round': args.parallel,
|
||||
'distinct_instances_seen': len(all_instances),
|
||||
'duplicates_found': sum(x['stored'] - 1 for x in rounds), 'per_round': rounds}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: concurrent Idempotency-Key replay produced exactly one message per key.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+133
@@ -0,0 +1,133 @@
|
||||
"""Общие помощники собственных тестов lab4: изображения, docker compose, psql, mc.
|
||||
|
||||
Только stdlib. Секреты не печатаются: mc получает их внутри контейнера из /run/secrets.
|
||||
"""
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests')) # публичный client.py
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
BUCKET = 'messenger-attachments'
|
||||
|
||||
|
||||
def chunk(typ, data):
|
||||
return struct.pack('>I', len(data)) + typ + data + struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(w, h, raw=None, color_type=2, interlace=0, level=6):
|
||||
"""PNG из сырых строк; по умолчанию RGB 8 bit, все пиксели чёрные."""
|
||||
if raw is None:
|
||||
raw = (b'\x00' + b'\x00' * (w * 3)) * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, color_type, 0, 0, interlace)
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, level))
|
||||
+ chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Почти несжимаемый PNG размером около target_bytes (шум из детерминированного PRNG)."""
|
||||
w = 1024
|
||||
h = max(1, target_bytes // (w * 3 + 1))
|
||||
seed = 0x2545F491
|
||||
rows = bytearray()
|
||||
for _ in range(h):
|
||||
rows.append(0)
|
||||
row = bytearray(w * 3)
|
||||
for i in range(0, w * 3, 4):
|
||||
seed = (seed * 1103515245 + 12345) & 0xffffffff
|
||||
row[i:i + 4] = seed.to_bytes(4, 'little')[:len(row) - i]
|
||||
rows += row
|
||||
return png(w, h, bytes(rows), level=1)
|
||||
|
||||
|
||||
def bomb_png(w=100_000, h=100_000):
|
||||
"""Маленький файл, огромные размеры в IHDR."""
|
||||
return png(w, h, raw=b'\x00')
|
||||
|
||||
|
||||
def raw_post(base_url, path, headers, body_iter, read_timeout=30):
|
||||
"""POST на сыром сокете: тело отправляется в фоне, ответ читается параллельно.
|
||||
|
||||
Нужен, когда сервер отвечает (413) до чтения тела и закрывает соединение:
|
||||
urllib в этом случае падает на отправке, не увидев ответа.
|
||||
Возвращает (status, body_bytes) или (None, b'') если ответа не было.
|
||||
"""
|
||||
import socket
|
||||
import threading
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(base_url)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=read_timeout)
|
||||
head = 'POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n' % (path, u.netloc)
|
||||
head += ''.join('%s: %s\r\n' % kv for kv in headers.items()) + '\r\n'
|
||||
s.sendall(head.encode())
|
||||
|
||||
def send():
|
||||
try:
|
||||
for part in body_iter:
|
||||
s.sendall(part)
|
||||
except OSError:
|
||||
pass # сервер уже ответил и закрыл соединение — ожидаемо
|
||||
t = threading.Thread(target=send, daemon=True)
|
||||
t.start()
|
||||
data = b''
|
||||
try:
|
||||
while True:
|
||||
b = s.recv(65536)
|
||||
if not b:
|
||||
break
|
||||
data += b
|
||||
if b'\r\n\r\n' in data and len(data) > 4096:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
if not data.startswith(b'HTTP/1.'):
|
||||
return None, b''
|
||||
status = int(data.split(b' ', 2)[1])
|
||||
return status, data.split(b'\r\n\r\n', 1)[-1]
|
||||
|
||||
|
||||
def fixture(name):
|
||||
return (FIXTURES / name).read_bytes()
|
||||
|
||||
|
||||
def sh(*args, check=True, timeout=300, input=None):
|
||||
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, timeout=timeout, input=input)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError('%s failed (%d): %s' % (' '.join(args[:4]), r.returncode, (r.stderr or r.stdout)[-800:]))
|
||||
return r
|
||||
|
||||
|
||||
def compose(*args, **kw):
|
||||
return sh('docker', 'compose', *args, **kw)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Одно значение/таблица из PostgreSQL стенда (через docker compose exec)."""
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-tAc', sql).stdout.strip()
|
||||
|
||||
|
||||
def mc(script, check=True, as_user='root'):
|
||||
"""Скрипт mc в одноразовом контейнере s3-init. Алиас `s3` — root или API-пользователь."""
|
||||
creds = {'root': ('s3_root_user', 's3_root_password'),
|
||||
'api': ('s3_access_key_id', 's3_secret_access_key')}[as_user]
|
||||
prelude = ('mc alias set s3 http://s3:9000 "$(cat /run/secrets/%s)" "$(cat /run/secrets/%s)" >/dev/null; '
|
||||
% creds)
|
||||
return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c', prelude + script,
|
||||
check=check)
|
||||
|
||||
|
||||
def api_container(instance_id):
|
||||
for cid in compose('ps', '-q', 'api').stdout.split():
|
||||
if cid.startswith(instance_id):
|
||||
return cid
|
||||
raise RuntimeError('no api container for ' + instance_id)
|
||||
|
||||
|
||||
def object_key(attachment_id):
|
||||
return psql("SELECT object_key FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
BASE = (sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080").rstrip("/")
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
|
||||
def post(path, body, headers=None):
|
||||
req = urllib.request.Request(BASE + path, method="POST",
|
||||
data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json", **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def get(path, headers=None):
|
||||
req = urllib.request.Request(BASE + path, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
|
||||
# 1. Неверный JSON → 400
|
||||
status, _ = post("/api/v1/users", "not-json")
|
||||
if status != 400:
|
||||
failures.append(f"invalid JSON: expected 400, got {status}")
|
||||
|
||||
# 2. Невалидный username → 400
|
||||
status, _ = post("/api/v1/users", {"username": "AB", "display_name": "Test", "password": PASSWORD})
|
||||
if status != 400:
|
||||
failures.append(f"invalid username: expected 400, got {status}")
|
||||
|
||||
# 3. Отсутствие Bearer на /users/me → 401
|
||||
status, _ = get("/api/v1/users/me")
|
||||
if status != 401:
|
||||
failures.append(f"no auth: expected 401, got {status}")
|
||||
|
||||
# 4. X-User-Id не даёт доступ → 401
|
||||
status, _ = get("/api/v1/users/me", {"X-User-Id": "00000000-0000-0000-0000-000000000000"})
|
||||
if status != 401:
|
||||
failures.append(f"X-User-Id bypass: expected 401, got {status}")
|
||||
|
||||
if failures:
|
||||
for f in failures:
|
||||
print(f"FAIL: {f}")
|
||||
sys.exit(1)
|
||||
print("PASS: negative checks")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+88
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: стоимость обхода reconciler в зависимости от числа вложений.
|
||||
|
||||
Для каждого N: досеиваем согласованные пары (строка в PostgreSQL + объект в S3)
|
||||
под отдельным префиксом чата-стенда, затем 3 раза запускаем dry-run и берём
|
||||
медиану duration_ms. Фиксируем число строк/объектов, LIST-страниц, Stat-вызовов
|
||||
и heap процесса reconciler. Дополнительно — прогон с 1% внедрённых расхождений.
|
||||
|
||||
Объекты — 1 KiB случайных байт (размер не влияет на обход: LIST возвращает
|
||||
метаданные, тела объектов не читаются).
|
||||
"""
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
from lab4util import BUCKET, compose, mc, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def reconcile_dry():
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', '1h', check=False, timeout=900)
|
||||
if r.returncode == 3:
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('lock busy')
|
||||
|
||||
|
||||
def seed(chat_id, owner_id, start, count):
|
||||
"""count согласованных пар с ключами a/<chat>/bench-<номер>."""
|
||||
# Объекты: генерируем count файлов в контейнере mc и заливаем одним mirror.
|
||||
mc('mkdir -p /tmp/b && head -c 1024 /dev/urandom > /tmp/one && i=%d; while [ $i -lt %d ]; do '
|
||||
'cp /tmp/one /tmp/b/bench-$(printf %%07d $i); i=$((i+1)); done && '
|
||||
'mc mirror -q --overwrite /tmp/b s3/%s/a/%s/ >/dev/null' % (start, start + count, BUCKET, chat_id))
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, content_type, size_bytes, sha256) "
|
||||
"SELECT gen_random_uuid(), '%s', '%s', 'b.png', 'a/%s/bench-' || lpad(g::text, 7, '0'), 'ready', "
|
||||
"'image/png', 1024, repeat('a', 64) FROM generate_series(%d, %d) g"
|
||||
% (chat_id, owner_id, chat_id, start, start + count - 1))
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--sizes', default='1000,10000,30000')
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler traversal cost (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
total_existing = int(psql('SELECT count(*) FROM attachments'))
|
||||
sizes = [int(x) for x in args.sizes.split(',')]
|
||||
seeded, runs = 0, []
|
||||
for n in sizes:
|
||||
t0 = time.time()
|
||||
seed(chat['id'], alice['id'], seeded, n - seeded)
|
||||
seed_s = time.time() - t0
|
||||
seeded = n
|
||||
reps = [reconcile_dry() for _ in range(3)]
|
||||
ms = [r['duration_ms'] for r in reps]
|
||||
r = reps[-1]
|
||||
runs.append({'bench_pairs': n, 'rows_scanned': r['rows_scanned'], 'objects_scanned': r['objects_scanned'],
|
||||
'duration_ms_runs': ms, 'duration_ms_median': statistics.median(ms),
|
||||
'us_per_pair': round(1000 * statistics.median(ms) / max(1, r['rows_scanned']), 1),
|
||||
'calls': r['calls'], 'heap_alloc_mb': r['heap_alloc_mb'], 'found': r['found'],
|
||||
'seed_seconds': round(seed_s, 1)})
|
||||
print(json.dumps(runs[-1], ensure_ascii=False))
|
||||
# 1% расхождений на самом большом наборе: удалённые объекты и сироты.
|
||||
k = max(1, sizes[-1] // 100)
|
||||
mc('i=0; while [ $i -lt %d ]; do mc rm -q s3/%s/a/%s/bench-$(printf %%07d $((i*97 %% %d))) >/dev/null 2>&1; i=$((i+1)); done'
|
||||
% (k // 2, BUCKET, chat['id'], sizes[-1]))
|
||||
mc('head -c 512 /dev/urandom > /tmp/o && i=0; while [ $i -lt %d ]; do mc cp -q /tmp/o s3/%s/a/%s/zz-orphan-$i >/dev/null; i=$((i+1)); done'
|
||||
% (k - k // 2, BUCKET, chat['id']))
|
||||
faulty = reconcile_dry()
|
||||
out = {'preexisting_rows': total_existing, 'object_size_bytes': 1024, 'runs': runs,
|
||||
'with_1pct_faults': {'injected_missing': k // 2, 'injected_orphans': k - k // 2,
|
||||
'duration_ms': faulty['duration_ms'], 'found': faulty['found'],
|
||||
'skipped': faulty['skipped'], 'calls': faulty['calls']},
|
||||
'note': 'dry-run, grace 1h: свежие сироты учитываются как skipped.fresh_object, а не удаляются'}
|
||||
text = json.dumps(out, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: reconciler cost measured for %s pairs' % sizes)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+171
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: внедрение расхождений PostgreSQL↔S3 и проверка reconciler.
|
||||
|
||||
Сценарий (Docker-стенд, reconciler запускается одноразово через docker compose run):
|
||||
1. Через API: чат, 6 вложений, два из них прикреплены к сообщениям.
|
||||
2. Внедряем ошибки с обеих сторон:
|
||||
S3: сирота (объект без строки, старый), сирота свежая (моложе grace),
|
||||
удалённый объект используемого и неиспользуемого вложения,
|
||||
объект с подменённым размером;
|
||||
БД: брошенное намерение с объектом и без, свежее намерение (загрузка «идёт»).
|
||||
3. dry-run: всё найдено, ничего не изменено (снимки БД и S3 совпадают).
|
||||
4. apply: исправлено; свежие и используемые не тронуты; API: здоровые вложения
|
||||
скачиваются байт-в-байт, потерянные отвечают 503, сообщение сохраняет attachment_ids.
|
||||
5. Повторный apply — ничего не исправляет (идемпотентность).
|
||||
6. Объект «восстановлен из бэкапа» → apply снимает карантин, скачивание снова работает.
|
||||
7. После grace: неиспользуемая запись карантина удаляется, используемая остаётся;
|
||||
свежая сирота, ставшая старой, удаляется.
|
||||
|
||||
Grace в тесте — 8 s (--unsafe-short-grace); «старые» строки сдвинуты на 30 минут
|
||||
назад, поэтому фоновый reconciler стенда (grace 1h) их не трогает.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from lab4util import BUCKET, compose, fixture, mc, noise_png, object_key, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
GRACE = '8s'
|
||||
|
||||
|
||||
def reconcile(*flags):
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', GRACE, '--unsafe-short-grace', *flags, check=False)
|
||||
if r.returncode == 3: # фоновый reconciler держит advisory lock
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-400:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('reconciler lock busy')
|
||||
|
||||
|
||||
def snapshot(chat_id):
|
||||
rows = psql("SELECT id || ':' || status || ':' || COALESCE(size_bytes, 0) FROM attachments "
|
||||
"WHERE chat_id = '%s' ORDER BY id" % chat_id)
|
||||
objs = mc('mc ls --recursive --json s3/%s/a/%s/' % (BUCKET, chat_id)).stdout
|
||||
keys = sorted((json.loads(l)['key'], json.loads(l)['size']) for l in objs.splitlines() if l.strip())
|
||||
return rows, keys
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler fault injection (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
cid = chat['id']
|
||||
up = lambda data: c.call('POST', '/api/v1/chats/%s/attachments?filename=r.png' % cid, 201, actor=alice,
|
||||
raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
datas = [noise_png(20_000 + i * 1000) for i in range(6)]
|
||||
ok, lost_used, lost_free, resized, keep_used, restore_me = [up(d) for d in datas]
|
||||
for att in (lost_used, keep_used, restore_me):
|
||||
c.message(alice, chat, 'с вложением', attachments=[att['id']])
|
||||
|
||||
# --- внедрение ошибок ---
|
||||
tmp = '/tmp/f.bin'
|
||||
put = 'head -c %d /dev/urandom > ' + tmp + ' && mc cp -q ' + tmp + ' s3/' + BUCKET + '/%s >/dev/null'
|
||||
orphan_old = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
orphan_fresh = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
stale_with = str(uuid.uuid4())
|
||||
stale_without = str(uuid.uuid4())
|
||||
inflight = str(uuid.uuid4())
|
||||
mc(' && '.join([
|
||||
put % (5000, orphan_old),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_used['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_free['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(restore_me['id'])),
|
||||
put % (777, object_key(resized['id'])),
|
||||
put % (4000, 'a/%s/%s' % (cid, stale_with)),
|
||||
put % (4000, 'a/%s/%s' % (cid, inflight)),
|
||||
]))
|
||||
for aid, age in ((stale_with, "now() - interval '30 minutes'"), (stale_without, "now() - interval '30 minutes'"),
|
||||
(inflight, 'now()')):
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, created_at, updated_at) "
|
||||
"VALUES ('%s', '%s', '%s', 'x.png', 'a/%s/%s', 'uploading', %s, %s)" % (aid, cid, alice['id'], cid, aid, age, age))
|
||||
time.sleep(9) # «старые» объекты стали старше grace
|
||||
mc(put % (3000, orphan_fresh)) # а эта сирота — свежая
|
||||
psql("UPDATE attachments SET updated_at = now() WHERE id = '%s'" % inflight) # загрузка «продолжается»
|
||||
|
||||
# --- dry-run ---
|
||||
before = snapshot(cid)
|
||||
dry = reconcile()
|
||||
check(snapshot(cid) == before, 'dry-run changed state')
|
||||
mine = lambda rep, kind: [i for i in rep['items'] if i['kind'] == kind and cid in i['key']]
|
||||
expect = {'orphan_object': 1, 'stale_intent': 2, 'missing_object': 3, 'size_mismatch': 1}
|
||||
for kind, n in expect.items():
|
||||
check(len(mine(dry, kind)) == n, 'dry-run %s: %d, want %d' % (kind, len(mine(dry, kind)), n))
|
||||
check(all(i['action'].startswith('would_') for i in dry['items'] if cid in i['key']), 'dry-run planned real actions')
|
||||
|
||||
# --- apply ---
|
||||
applied = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
key_set = {k for k, _ in keys}
|
||||
check(stale_with not in status and stale_without not in status, 'stale intents not removed')
|
||||
check('a/%s/%s' % (cid, stale_with) not in key_set, 'stale intent object not removed')
|
||||
check(orphan_old not in key_set, 'old orphan not removed')
|
||||
check(orphan_fresh in key_set, 'FRESH orphan was deleted')
|
||||
check(status.get(inflight) == 'uploading' and 'a/%s/%s' % (cid, inflight) in key_set, 'IN-FLIGHT upload touched')
|
||||
for att in (lost_used, lost_free, restore_me, resized):
|
||||
check(status.get(att['id']) == 'missing', '%s not quarantined' % att['id'])
|
||||
check(status.get(ok['id']) == 'ready' and status.get(keep_used['id']) == 'ready', 'healthy rows touched')
|
||||
# API после исправления
|
||||
for att, data in ((ok, datas[0]), (keep_used, datas[4])):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'healthy attachment changed')
|
||||
c.call('GET', '/api/v1/attachments/%s' % lost_used['id'], 503, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % lost_used['id'], 503, actor=bob)
|
||||
hist = c.call('GET', '/api/v1/chats/%s/messages?limit=100' % cid, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(lost_used['id'] in m['attachment_ids'] for m in hist), 'message lost its attachment reference')
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % cid, 409, actor=alice, body={'text': '', 'attachment_ids': [lost_free['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
|
||||
# --- идемпотентность ---
|
||||
again = reconcile('--apply')
|
||||
check(not [i for i in again['items'] if cid in i['key']], 'second apply changed something: %s' % [i for i in again['items'] if cid in i['key']])
|
||||
|
||||
# --- восстановление объекта ---
|
||||
with_data = datas[5]
|
||||
open_key = object_key(restore_me['id'])
|
||||
# Восстанавливаем исходные байты («из бэкапа») через stdin контейнера mc.
|
||||
import subprocess
|
||||
p = subprocess.run(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c',
|
||||
'mc alias set s3 http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
'cat > /tmp/r.png && mc cp -q /tmp/r.png s3/%s/%s >/dev/null' % (BUCKET, open_key)],
|
||||
input=with_data, capture_output=True)
|
||||
check(p.returncode == 0, 'restore put failed')
|
||||
restored = reconcile('--apply')
|
||||
check(len(mine(restored, 'restored')) == 1, 'restore not detected')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % restore_me['id'], actor=bob)
|
||||
check(d['bytes'] == with_data, 'restored attachment bytes differ')
|
||||
|
||||
# --- после grace ---
|
||||
time.sleep(9)
|
||||
late = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
check(lost_free['id'] not in status, 'unreferenced quarantined row not purged after grace')
|
||||
check(resized['id'] not in status or status[resized['id']] == 'missing', 'resized row state')
|
||||
check(status.get(lost_used['id']) == 'missing', 'REFERENCED quarantined row deleted')
|
||||
check(orphan_fresh not in {k for k, _ in keys}, 'orphan not removed after grace')
|
||||
|
||||
summary = {
|
||||
'injected': {'orphan_old': 1, 'orphan_fresh': 1, 'deleted_objects': 3, 'resized_object': 1,
|
||||
'stale_intents': 2, 'inflight_intent': 1},
|
||||
'dry_run_found': {k: len(mine(dry, k)) for k in expect}, 'dry_run_state_changed': False,
|
||||
'apply_found': {k: len(mine(applied, k)) for k in expect},
|
||||
'second_apply_actions': 0, 'restored': 1,
|
||||
'after_grace': {k: len(mine(late, k)) for k in ('purge_missing', 'orphan_object')},
|
||||
'never_deleted': ['fresh orphan (until grace)', 'in-flight intent', 'referenced quarantined row', 'healthy rows'],
|
||||
'reports': {'dry_run': dry, 'apply': applied, 'second_apply': again, 'restore': restored, 'after_grace': late},
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != 'reports'}, ensure_ascii=False, indent=2))
|
||||
print('PASS: reconciler detected and safely fixed faults on both sides; dry-run and repeat are safe')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии по замечаниям проверки lab3.
|
||||
|
||||
1. Видимость подтверждённой записи при отказе Redis в командах инвалидации:
|
||||
чат с двумя сообщениями → закэшировать историю → в Redis запретить команды
|
||||
через ACL (сначала только INCR, затем INCR+DEL+UNLINK+SCAN) → отправить
|
||||
третье сообщение → каждое следующее чтение через LB обязано вернуть его.
|
||||
2. Пароль из одних пробельных символов при регистрации → 400.
|
||||
|
||||
Нужен запущенный Docker-стенд (redis-cli вызывается через docker compose exec).
|
||||
ACL всегда восстанавливается в finally. --only cache|password запускает одну часть.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, ' ' * 8)
|
||||
|
||||
|
||||
def redis_cli(*args):
|
||||
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=30)
|
||||
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def visibility_case(c, alice, bob, chat, denied):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=50'
|
||||
before = [m['id'] for m in history(c, bob, chat)]
|
||||
# Прогреваем кэш на обеих репликах.
|
||||
for _ in range(4):
|
||||
c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
|
||||
try:
|
||||
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
|
||||
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
|
||||
for i in range(6):
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
ids = [m['id'] for m in page['json']['items']]
|
||||
check(sent['id'] in ids, 'read %d after 201 misses confirmed message (denied: %s)' % (i, denied))
|
||||
# Порядок (created_at до секунды, id): новое сообщение той же секунды может
|
||||
# встать раньше старых, поэтому проверяем наличие, а не префикс.
|
||||
check(set(before) <= set(ids), 'previously confirmed messages missing')
|
||||
finally:
|
||||
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
|
||||
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
|
||||
return len(before) + 1
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--only', choices=['password', 'cache'], default=None)
|
||||
args = arguments('Regression checks for lab3 review findings', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
# 2. Пароль из пробельных символов (пробелы, табуляции, неразрывные пробелы).
|
||||
if args.only in (None, 'password'):
|
||||
for pw in WHITESPACE_PASSWORDS:
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'ws_' + uuid.uuid4().hex[:10], 'display_name': 'WS', 'password': pw})
|
||||
print('PASS: whitespace-only password rejected with 400 (3 variants)')
|
||||
if args.only == 'password':
|
||||
return
|
||||
|
||||
# 1. Видимость записи при отказе Redis.
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
c.message(alice, chat, 'первое')
|
||||
c.message(bob, chat, 'второе')
|
||||
n = visibility_case(c, alice, bob, chat, ['incr'])
|
||||
print('PASS: Redis ACL -incr: message visible on every next read (%d in history)' % n)
|
||||
n = visibility_case(c, alice, bob, chat, ['incr', 'del', 'unlink', 'scan'])
|
||||
print('PASS: Redis ACL -incr -del -unlink -scan: message visible on every next read (%d in history)' % n)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user