lab4: вложения в S3 (MinIO), reconciler PostgreSQL↔S3, тесты и CI

This commit is contained in:
2026-11-04 20:11:33 +03:00
parent ec540a1a72
commit 77b6e5c2c7
86 changed files with 6921 additions and 2 deletions
+127
View File
@@ -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
}
+51
View File
@@ -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),
})
}
+30
View File
@@ -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),
})
}
+30
View File
@@ -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),
})
}
+10
View File
@@ -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:"-"`
}
+25
View File
@@ -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),
})
}
+475
View File
@@ -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
}
}
}
+168
View File
@@ -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")
}
}
+363
View File
@@ -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"]++
}
}
+232
View File
@@ -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)
}
}
+191
View File
@@ -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
}
+180
View File
@@ -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
}
+200
View File
@@ -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
}
+39
View File
@@ -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
}
+77
View File
@@ -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()
}
+73
View File
@@ -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
}
+57
View File
@@ -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
}
+281
View File
@@ -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
}
+99
View File
@@ -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
}
+138
View File
@@ -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
}
+39
View File
@@ -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
}
+14
View File
@@ -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")
)
+23
View File
@@ -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)
}
+190
View File
@@ -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
}
+66
View File
@@ -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
}
+64
View File
@@ -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
}
+53
View File
@@ -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
}
+39
View File
@@ -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")
}
}
+130
View File
@@ -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
}
+90
View File
@@ -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)
}
}
+92
View File
@@ -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 ")
}
+86
View File
@@ -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)
}
+54
View File
@@ -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"`
}
+39
View File
@@ -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
}
+80
View File
@@ -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))
})
}
}
+62
View File
@@ -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
}
+49
View File
@@ -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)
}
+166
View File
@@ -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
}