lab4 done

This commit is contained in:
Khakimov Dmitrij
2026-10-28 22:41:10 +03:00
parent a7bedda183
commit dbc700fafe
75 changed files with 5611 additions and 227 deletions
+68
View File
@@ -0,0 +1,68 @@
package chat
import (
"context"
"mime"
"net/http"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"github.com/labstack/echo/v4"
)
func (h *Chat) WithAttachments(service *attachment.Service) *Chat { h.attachments = service; return h }
func (h *Chat) uploadAttachment(c echo.Context) error {
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: c.Param("chat_id")})
if err != nil || !ok {
return err
}
filename, present, err := oneQueryValue(c, "filename")
if err != nil || !present {
return h.invalid(c, "Требуется один filename")
}
if c.Request().ContentLength > attachment.MaxBytes {
return h.writeError(c, 413, "payload_too_large", "Файл превышает 10 MiB")
}
// Both socket reads and the application operation have a fixed deadline.
deadline := time.Now().Add(attachment.UploadTimeout)
_ = http.NewResponseController(c.Response().Writer).SetReadDeadline(deadline)
defer http.NewResponseController(c.Response().Writer).SetReadDeadline(time.Time{})
c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, attachment.MaxBytes+1)
a, err := h.attachments.Upload(c.Request().Context(), chat.ID, authenticatedUser(c).ID, filename, c.Request().Header.Get("Content-Type"), c.Request().Body)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, a)
}
func (h *Chat) getAttachment(c echo.Context) error {
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusOK, a)
}
func (h *Chat) attachmentContent(c echo.Context) error {
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
if err != nil {
return h.useCaseError(c, err)
}
variant, present, err := oneQueryValue(c, "variant")
if err != nil {
return h.invalid(c, "Некорректный variant")
}
if present && variant != "original" {
return h.writeError(c, 404, "not_found", "Вариант не найден")
}
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
defer cancel()
obj, err := h.attachments.Content(ctx, a)
if err != nil {
return h.useCaseError(c, err)
}
defer obj.Close()
c.Response().Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
c.Response().Header().Set("Cache-Control", "private, no-store")
return c.Stream(http.StatusOK, a.ContentType, obj)
}
+9 -2
View File
@@ -40,12 +40,19 @@ func (h *Chat) createMessage(c echo.Context) error {
}
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
return domain.Message{ChatID: request.ChatID, Text: request.Text}
return domain.Message{ChatID: request.ChatID, Text: request.Text, AttachmentIDs: request.AttachmentIDs}
}
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
return dto.CreateMessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
}
}
func nonnilIDs(ids []string) []string {
if ids == nil {
return []string{}
}
return ids
}
+4
View File
@@ -33,6 +33,10 @@ func (h *Chat) useCaseError(c echo.Context, err error) error {
}
status := http.StatusInternalServerError
switch applicationError.Code {
case "unsupported_media_type":
status = http.StatusUnsupportedMediaType
case "payload_too_large":
status = http.StatusRequestEntityTooLarge
case domain.ErrorUnavailable:
status = http.StatusServiceUnavailable
case domain.ErrorInvalid:
+1 -1
View File
@@ -63,7 +63,7 @@ func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string)
for _, message := range page.Items {
items = append(items, dto.ListMessagesItem{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
})
}
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
+5
View File
@@ -16,5 +16,10 @@ func (h *Chat) readiness(c echo.Context) error {
if err := h.useCase.Ready(ctx); err != nil {
return h.useCaseError(c, err)
}
if h.attachments != nil {
if err := h.attachments.Ready(ctx); err != nil {
return h.useCaseError(c, err)
}
}
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
}
+11 -4
View File
@@ -1,6 +1,7 @@
package chat
import (
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"log"
"os"
"sync/atomic"
@@ -13,10 +14,11 @@ import (
// Chat is the HTTP handler and depends only on the application boundary.
type Chat struct {
instanceID string
draining atomic.Bool
useCase UseCase
cursor cursorCodec
attachments *attachment.Service
instanceID string
draining atomic.Bool
useCase UseCase
cursor cursorCodec
}
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
@@ -81,6 +83,11 @@ func (h *Chat) Router() *echo.Echo {
api.GET("/chats/:chat_id", h.getChat)
api.POST("/chats/:chat_id/messages", h.createMessage)
api.GET("/chats/:chat_id/messages", h.listMessages)
if h.attachments != nil {
api.POST("/chats/:chat_id/attachments", h.uploadAttachment)
api.GET("/attachments/:attachment_id", h.getAttachment)
api.GET("/attachments/:attachment_id/content", h.attachmentContent)
}
return e
}
+128
View File
@@ -0,0 +1,128 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"os"
"strings"
"unicode"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const MaxBytes int64 = 10 * 1024 * 1024
const MaxPixels int64 = 40_000_000
func appError(code domain.ErrorCode, message string) error {
return domain.NewApplicationError(code, message)
}
func unavailable() error {
return appError(domain.ErrorUnavailable, "Хранилище вложений недоступно")
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return appError(domain.ErrorInvalid, "Некорректный filename")
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return appError(domain.ErrorInvalid, "Недопустимые символы filename")
}
}
return nil
}
type Original struct {
File *os.File
Size int64
SHA256, ContentType string
Width, Height int
}
func (o *Original) Close() { name := o.File.Name(); o.File.Close(); os.Remove(name) }
// Spool bounds compressed bytes on disk before any decode. DecodeConfig checks the
// pixel budget before a full decode verifies CRCs/truncated scan data.
func Spool(ctx context.Context, body io.Reader, declared string) (*Original, error) {
media, _, err := mime.ParseMediaType(declared)
if err != nil || (media != "image/png" && media != "image/jpeg") {
return nil, appError("unsupported_media_type", "Допустимы PNG и JPEG")
}
f, err := os.CreateTemp("", "messenger-upload-*")
if err != nil {
return nil, unavailable()
}
o := &Original{File: f}
good := false
defer func() {
if !good {
o.Close()
}
}()
hash := sha256.New()
n, err := io.Copy(io.MultiWriter(f, hash), io.LimitReader(&contextReader{ctx: ctx, r: body}, MaxBytes+1))
if n > MaxBytes {
return nil, appError("payload_too_large", "Файл превышает 10 MiB")
}
if err != nil {
return nil, appError(domain.ErrorInvalid, "Загрузка прервана")
}
o.Size = n
o.SHA256 = hex.EncodeToString(hash.Sum(nil))
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
actual := "image/" + format
if actual != media {
return nil, appError("unsupported_media_type", "MIME не соответствует содержимому")
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
return nil, appError("payload_too_large", "Изображение превышает 40 миллионов пикселей")
}
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
decoded, format, err := image.Decode(f)
if err != nil || decoded == nil || "image/"+format != actual {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
if decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
return nil, appError("unsupported_media_type", "Некорректные размеры изображения")
}
decoded = nil
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
o.ContentType = actual
o.Width = cfg.Width
o.Height = cfg.Height
good = true
return o, nil
}
type contextReader struct {
ctx context.Context
r io.Reader
}
func (r *contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.r.Read(p)
if errors.Is(err, context.Canceled) {
return n, err
}
return n, err
}
+139
View File
@@ -0,0 +1,139 @@
package attachment
import (
"bytes"
"context"
"encoding/binary"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func pngFixture(t *testing.T) []byte {
t.Helper()
m := image.NewRGBA(image.Rect(0, 0, 10, 8))
m.Set(1, 1, color.RGBA{R: 255, A: 255})
var b bytes.Buffer
if err := png.Encode(&b, m); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func code(t *testing.T, err error, want domain.ErrorCode) {
t.Helper()
app, ok := domain.AsApplicationError(err)
if !ok || app.Code != want {
t.Fatalf("want %s, got %v", want, err)
}
}
func TestSpoolOriginalAndFullValidation(t *testing.T) {
original := pngFixture(t)
good, err := Spool(context.Background(), bytes.NewReader(original), "image/png")
if err != nil {
t.Fatal(err)
}
defer good.Close()
got, err := io.ReadAll(good.File)
if err != nil || !bytes.Equal(got, original) {
t.Fatal("original changed")
}
if good.Width != 10 || good.Height != 8 || good.Size != int64(len(original)) || len(good.SHA256) != 64 {
t.Fatalf("wrong metadata %+v", good)
}
_, err = Spool(context.Background(), bytes.NewReader(original), "image/jpeg")
code(t, err, "unsupported_media_type")
_, err = Spool(context.Background(), bytes.NewReader(original[:len(original)-12]), "image/png")
code(t, err, "unsupported_media_type")
corrupted := bytes.Clone(original)
corrupted[len(corrupted)-18] ^= 0x80
_, err = Spool(context.Background(), bytes.NewReader(corrupted), "image/png")
code(t, err, "unsupported_media_type")
var jpegBytes bytes.Buffer
if err = jpeg.Encode(&jpegBytes, image.NewRGBA(image.Rect(0, 0, 12, 9)), nil); err != nil {
t.Fatal(err)
}
jpegOriginal, err := Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()), "image/jpeg")
if err != nil {
t.Fatal(err)
}
jpegOriginal.Close()
_, err = Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()[:jpegBytes.Len()/2]), "image/jpeg")
code(t, err, "unsupported_media_type")
}
func TestSpoolLimitsBeforeDecode(t *testing.T) {
// Oversized compressed input is stopped after exactly MaxBytes+1 reads.
source := &countingReader{remaining: MaxBytes + 100_000}
_, err := Spool(context.Background(), source, "image/png")
code(t, err, "payload_too_large")
if source.read != MaxBytes+1 {
t.Fatalf("read %d bytes", source.read)
}
bomb := bytes.Clone(pngFixture(t))
binary.BigEndian.PutUint32(bomb[16:20], 40001)
binary.BigEndian.PutUint32(bomb[20:24], 1000)
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
_, err = Spool(context.Background(), bytes.NewReader(bomb), "image/png")
code(t, err, "payload_too_large")
}
type countingReader struct{ remaining, read int64 }
func (c *countingReader) Read(p []byte) (int, error) {
if c.remaining == 0 {
return 0, io.EOF
}
n := min(int64(len(p)), c.remaining)
clear(p[:n])
c.remaining -= n
c.read += n
return int(n), nil
}
func TestFilenameAndCancelledUpload(t *testing.T) {
for _, name := range []string{"", "../x.png", "x\\photo.jpg", "a\x00b", "a\nb", "\t"} {
code(t, ValidateFilename(name), domain.ErrorInvalid)
}
for _, name := range []string{"фото.png", "image.jpg", ".."} {
if err := ValidateFilename(name); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := Spool(ctx, bytes.NewReader(pngFixture(t)), "image/png")
code(t, err, domain.ErrorInvalid)
}
func TestReconcileRejectsUnsafeGrace(t *testing.T) {
s := &Service{}
if _, err := s.Reconcile(context.Background(), true, 89*time.Second); err == nil {
t.Fatal("unsafe grace accepted")
}
if MinimumGrace <= UploadTimeout {
t.Fatal("grace does not cover in-flight PUT")
}
}
func TestValid16BitWidePNG(t *testing.T) {
// Exercise the same RGBA64 + scanline allocation path as an extreme-aspect
// 40M image, at 1/1000 of that pixel count to keep the unit suite small.
img := image.NewNRGBA64(image.Rect(0, 0, 40000, 1))
img.SetNRGBA64(1, 0, color.NRGBA64{R: 65535, G: 12345, B: 4, A: 32000})
var encoded bytes.Buffer
if err := png.Encode(&encoded, img); err != nil {
t.Fatal(err)
}
original, err := Spool(context.Background(), bytes.NewReader(encoded.Bytes()), "image/png")
if err != nil {
t.Fatal(err)
}
defer original.Close()
if original.Width != 40000 || original.Height != 1 {
t.Fatal("wide PNG dimensions changed")
}
}
+18
View File
@@ -0,0 +1,18 @@
package attachment
import (
"encoding/json"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
// MarshalJSON uses the API's fixed microsecond precision instead of time.Time's
// variable fractional precision, which Python 3.9 clients cannot always parse.
func (a Attachment) MarshalJSON() ([]byte, error) {
type fields Attachment
return json.Marshal(struct {
fields
CreatedAt dto.Timestamp `json:"created_at"`
UpdatedAt dto.Timestamp `json:"updated_at"`
}{fields: fields(a), CreatedAt: dto.Timestamp(a.CreatedAt), UpdatedAt: dto.Timestamp(a.UpdatedAt)})
}
+37
View File
@@ -0,0 +1,37 @@
package attachment
import (
"encoding/json"
"testing"
"time"
)
func TestAttachmentTimestampsUseFixedMicroseconds(t *testing.T) {
value := Attachment{ID: "attachment-id", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC), UpdatedAt: time.Date(2026, 1, 2, 6, 4, 5, 0, time.FixedZone("MSK", 3*60*60)), Key: "original/private", Variants: []any{}}
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err = json.Unmarshal(encoded, &fields); err != nil {
t.Fatal(err)
}
if fields["created_at"] != "2026-01-02T03:04:05.123400Z" {
t.Fatalf("created_at=%v", fields["created_at"])
}
if fields["updated_at"] != "2026-01-02T03:04:05.000000Z" {
t.Fatalf("updated_at=%v", fields["updated_at"])
}
if fields["id"] != value.ID {
t.Fatal("serialization lost metadata")
}
if _, exposed := fields["Key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if _, exposed := fields["key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if fields["error_code"] != nil {
t.Fatal("ready error_code must be null")
}
}
+222
View File
@@ -0,0 +1,222 @@
package attachment
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
)
type Summary struct {
Apply bool `json:"apply"`
GraceSeconds float64 `json:"grace_seconds"`
ObjectsScanned int `json:"objects_scanned"`
MetadataScanned int `json:"metadata_scanned"`
BytesScanned int64 `json:"bytes_scanned"`
ListRequestsEstimate int `json:"list_requests_estimate"`
StatRequests int `json:"stat_requests"`
DBQueries int `json:"db_queries"`
Orphans int `json:"orphans"`
Missing int `json:"missing"`
FreshSkipped int `json:"fresh_skipped"`
LockedSkipped int `json:"locked_skipped"`
ReferencedMissing int `json:"referenced_missing"`
Deleted int `json:"deleted"`
MarkedFailed int `json:"marked_failed"`
DurationMS int64 `json:"duration_ms"`
Actions []Action `json:"actions"`
}
type Action struct {
Kind string `json:"kind"`
Key string `json:"key"`
Applied bool `json:"applied"`
}
// Reconcile scans a fixed cutoff and rechecks each candidate while holding the
// same transaction-scoped advisory lock as upload. Metadata, including message
// references, is never deleted. Missing originals become failed tombstones.
func (s *Service) Reconcile(ctx context.Context, apply bool, grace time.Duration) (result Summary, err error) {
started := time.Now()
result = Summary{Apply: apply, GraceSeconds: grace.Seconds(), Actions: []Action{}}
defer func() { result.DurationMS = time.Since(started).Milliseconds() }()
if grace < MinimumGrace {
return result, fmt.Errorf("grace must be at least %s (upload timeout %s)", MinimumGrace, UploadTimeout)
}
cutoff := started.Add(-grace)
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
if obj.Err != nil {
return result, fmt.Errorf("S3 listing failed")
}
result.ObjectsScanned++
result.BytesScanned += obj.Size
if result.ObjectsScanned%1000 == 1 {
result.ListRequestsEstimate++
}
if !obj.LastModified.Before(cutoff) {
result.FreshSkipped++
continue
}
err = s.reconcileObject(ctx, obj.Key, cutoff, apply, &result)
if err != nil {
return result, err
}
}
// Bounded keyset pages avoid retaining the entire bucket or a DB cursor while
// making per-object transactions. A later run picks up concurrent new rows.
last := "00000000-0000-0000-0000-000000000000"
for {
result.DBQueries++
rows, e := s.Pool.Query(ctx, `SELECT id::text,object_key,created_at,status FROM attachments WHERE id>$1 ORDER BY id LIMIT 100`, last)
if e != nil {
return result, fmt.Errorf("metadata scan failed")
}
type metadata struct {
id, key, status string
created time.Time
}
page := []metadata{}
for rows.Next() {
var m metadata
if e = rows.Scan(&m.id, &m.key, &m.created, &m.status); e != nil {
rows.Close()
return result, e
}
page = append(page, m)
}
e = rows.Err()
rows.Close()
if e != nil {
return result, e
}
if len(page) == 0 {
break
}
for _, m := range page {
last = m.id
result.MetadataScanned++
if m.status != "ready" {
continue
}
if !m.created.Before(cutoff) {
result.FreshSkipped++
continue
}
if e = s.reconcileMetadata(ctx, m.id, m.key, cutoff, apply, &result); e != nil {
return result, e
}
}
}
if ctx.Err() != nil {
return result, ctx.Err()
}
return result, nil
}
func (s *Service) locked(ctx context.Context, key string, r *Summary) (pgx.Tx, bool, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return nil, false, fmt.Errorf("DB unavailable")
}
var locked bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, key).Scan(&locked); err != nil {
tx.Rollback(context.Background())
return nil, false, fmt.Errorf("lock failed")
}
if !locked {
r.LockedSkipped++
tx.Rollback(context.Background())
return nil, false, nil
}
return tx, true, nil
}
func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var exists bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)`, key).Scan(&exists); err != nil {
return fmt.Errorf("metadata recheck failed")
}
if exists {
return nil
}
r.StatRequests++
obj, err := s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if IsMissing(err) {
return nil
}
if err != nil {
return fmt.Errorf("object recheck failed")
}
if !obj.LastModified.Before(cutoff) {
r.FreshSkipped++
return nil
}
r.Orphans++
if apply {
if err = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{}); err != nil {
return fmt.Errorf("orphan deletion failed")
}
r.Deleted++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "orphan", Key: key, Applied: apply})
}
return nil
}
func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var created time.Time
var status string
r.DBQueries++
err = tx.QueryRow(ctx, `SELECT created_at,status FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&created, &status)
if err == pgx.ErrNoRows {
return nil
}
if err != nil {
return fmt.Errorf("metadata recheck failed")
}
if status != "ready" || !created.Before(cutoff) {
return nil
}
r.StatRequests++
_, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if err == nil {
return nil
}
if !IsMissing(err) {
return fmt.Errorf("object stat failed (no mutation)")
}
var referenced bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE $1::uuid=ANY(attachment_ids))`, id).Scan(&referenced); err != nil {
return fmt.Errorf("reference check failed")
}
r.Missing++
if referenced {
r.ReferencedMissing++
}
if apply {
r.DBQueries++
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing' WHERE id=$1 AND status='ready'`, id); err != nil {
return fmt.Errorf("mark missing failed")
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("commit missing failed")
}
r.MarkedFailed++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "missing", Key: key, Applied: apply})
}
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package attachment
import (
"context"
"crypto/tls"
"net"
"net/http"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type Store struct {
Client *minio.Client
Bucket string
}
func NewStore(endpoint, bucket, access, secret string, secure bool) (*Store, error) {
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 16, MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 5 * time.Second, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}}
c, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: secure, Region: "us-east-1", Transport: transport, MaxRetries: 1})
if err != nil {
return nil, err
}
return &Store{Client: c, Bucket: bucket}, nil
}
func (s *Store) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
for item := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "original/", MaxKeys: 1, Recursive: true}) {
if item.Err != nil {
return unavailable()
}
return nil
}
if ctx.Err() != nil {
return unavailable()
}
return nil
}
func IsMissing(err error) bool {
code := minio.ToErrorResponse(err).Code
return code == "NoSuchKey" || code == "NoSuchObject"
}
+132
View File
@@ -0,0 +1,132 @@
package attachment
import (
"context"
"errors"
"io"
"log"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const UploadTimeout = 45 * time.Second
const MinimumGrace = 90 * time.Second
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Key string `json:"-"`
}
type Service struct {
Pool *pgxpool.Pool
Store *Store
slots chan struct{}
}
func New(pool *pgxpool.Pool, store *Store) *Service {
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
}
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
if err := ValidateFilename(name); err != nil {
return Attachment{}, err
}
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
defer cancel()
select {
case s.slots <- struct{}{}:
defer func() { <-s.slots }()
case <-ctx.Done():
return Attachment{}, unavailable()
}
original, err := Spool(ctx, body, contentType)
if err != nil {
return Attachment{}, err
}
defer original.Close()
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "ready", Variants: []any{}}
a.Key = "original/" + a.ID
tx, err := s.Pool.Begin(ctx)
if err != nil {
return Attachment{}, unavailable()
}
defer tx.Rollback(context.Background())
// Keep the object lock through PUT, metadata insert and COMMIT. A crash releases
// the lock; the grace protects a still-running client PUT at the S3 server.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, a.Key); err != nil {
return Attachment{}, unavailable()
}
_, err = s.Store.Client.PutObject(ctx, s.Store.Bucket, a.Key, original.File, a.Size, minio.PutObjectOptions{ContentType: a.ContentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": a.SHA256}})
if err != nil {
return Attachment{}, unavailable()
}
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING created_at`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height).Scan(&a.CreatedAt)
if err != nil {
log.Print("attachment metadata failed; orphan retained for grace-period reconciliation")
return Attachment{}, unavailable()
}
// Never DELETE on an ambiguous COMMIT failure: the DB may have committed. A
// later reconciler checks both stores under the same lock before any cleanup.
if err = tx.Commit(ctx); err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
return a, nil
}
func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error) {
parsed, err := uuid.Parse(id)
if err != nil {
return Attachment{}, appError(domain.ErrorInvalid, "Некорректный attachment_id")
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
a := Attachment{Variants: []any{}}
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
}
if err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
// Keep the mandatory lab4 ready-only metadata schema. Failed originals are
// represented by 409; internal status remains inspectable in reconciliation.
if a.Status != "ready" {
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return a, nil
}
func (s *Service) Content(ctx context.Context, a Attachment) (*minio.Object, error) {
if a.Status != "ready" {
return nil, appError(domain.ErrorConflict, "Вложение не готово")
}
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, a.Key, minio.GetObjectOptions{})
if err != nil {
return nil, unavailable()
}
if _, err = obj.Stat(); err != nil {
obj.Close()
if IsMissing(err) {
return nil, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return nil, unavailable()
}
return obj, nil
}
+19
View File
@@ -10,6 +10,11 @@ import (
)
type Config struct {
S3Endpoint string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3UseSSL bool
Port string
PostgresHost string
PostgresPort uint16
@@ -96,5 +101,19 @@ func Load() (Config, error) {
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
}
copy(c.CursorKey[:], decoded)
c.S3Endpoint = value("S3_ENDPOINT", "minio:9000")
c.S3Bucket = value("S3_BUCKET", "attachments")
c.S3UseSSL, err = strconv.ParseBool(value("S3_USE_SSL", "false"))
if err != nil {
return c, fmt.Errorf("invalid S3_USE_SSL")
}
c.S3AccessKey, err = secret("S3_ACCESS_KEY")
if err != nil {
return c, err
}
c.S3SecretKey, err = secret("S3_SECRET_KEY")
if err != nil {
return c, err
}
return c, nil
}
+1
View File
@@ -7,6 +7,7 @@ type Message struct {
ID string
ChatID string
SenderID string
AttachmentIDs []string
Text string
CreatedAt time.Time
}
@@ -0,0 +1,341 @@
package postgres_test
import (
"bufio"
"bytes"
"context"
"encoding/xml"
"fmt"
"image"
"image/png"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type fakeObject struct {
data []byte
modified time.Time
}
type fakeS3 struct {
mu sync.Mutex
objects map[string]fakeObject
failPUT bool
}
func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
key := strings.TrimPrefix(r.URL.Path, "/attachments/")
if r.Method == "GET" && r.URL.Path == "/attachments/" || r.Method == "GET" && r.URL.Path == "/attachments" {
type item struct {
Key string
LastModified string
ETag string
Size int
}
type listing struct {
XMLName xml.Name `xml:"ListBucketResult"`
Xmlns string `xml:"xmlns,attr"`
Name string
Prefix string
MaxKeys int
IsTruncated bool
Contents []item
}
l := listing{Xmlns: "http://s3.amazonaws.com/doc/2006-03-01/", Name: "attachments", Prefix: r.URL.Query().Get("prefix"), MaxKeys: 1000}
for k, v := range f.objects {
if strings.HasPrefix(k, l.Prefix) {
l.Contents = append(l.Contents, item{Key: k, LastModified: v.modified.UTC().Format("2006-01-02T15:04:05.000Z"), ETag: `"abc"`, Size: len(v.data)})
}
}
w.Header().Set("Content-Type", "application/xml")
xml.NewEncoder(w).Encode(l)
return
}
if r.Method == "PUT" {
if f.failPUT {
w.WriteHeader(503)
fmt.Fprint(w, `<Error><Code>ServiceUnavailable</Code></Error>`)
return
}
var data []byte
var err error
if strings.Contains(r.Header.Get("Content-Encoding"), "aws-chunked") || strings.HasPrefix(r.Header.Get("X-Amz-Content-Sha256"), "STREAMING-") {
reader := bufio.NewReader(r.Body)
for {
line, e := reader.ReadString('\n')
if e != nil {
err = e
break
}
size, e := strconv.ParseInt(strings.Split(strings.TrimSpace(line), ";")[0], 16, 64)
if e != nil {
err = e
break
}
if size == 0 {
break
}
chunk := make([]byte, size)
if _, e = io.ReadFull(reader, chunk); e != nil {
err = e
break
}
data = append(data, chunk...)
if _, e = reader.Discard(2); e != nil {
err = e
break
}
}
} else {
data, err = io.ReadAll(r.Body)
}
if err != nil {
w.WriteHeader(400)
return
}
f.objects[key] = fakeObject{data: data, modified: time.Now().UTC()}
w.Header().Set("ETag", `"900150983cd24fb0d6963f7d28e17f72"`)
w.WriteHeader(200)
return
}
obj, ok := f.objects[key]
if !ok {
w.WriteHeader(404)
if r.Method != "HEAD" {
fmt.Fprint(w, `<Error><Code>NoSuchKey</Code></Error>`)
}
return
}
if r.Method == "DELETE" {
delete(f.objects, key)
w.WriteHeader(204)
return
}
w.Header().Set("Last-Modified", obj.modified.UTC().Format(http.TimeFormat))
w.Header().Set("ETag", `"abc"`)
w.Header().Set("Content-Length", fmt.Sprint(len(obj.data)))
w.Header().Set("Content-Type", "image/png")
if r.Method == "GET" {
w.Write(obj.data)
}
}
func lab4Backend(t *testing.T, pool *pgxpool.Pool, repo *postgres.Storage, user domain.User, chat domain.Chat) {
ctx := context.Background()
fake := &fakeS3{objects: map[string]fakeObject{}}
server := httptest.NewServer(fake)
defer server.Close()
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
if err != nil {
t.Fatal(err)
}
service := attachment.New(pool, &attachment.Store{Client: client, Bucket: "attachments"})
var imageBytes bytes.Buffer
if err = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 10, 8))); err != nil {
t.Fatal(err)
}
upload := func(name string) attachment.Attachment {
t.Helper()
a, e := service.Upload(ctx, chat.ID, user.ID, name, "image/png", bytes.NewReader(imageBytes.Bytes()))
if e != nil {
t.Fatal(e)
}
return a
}
first := upload("first.png")
second := upload("second.png")
requireCode := func(err error, want domain.ErrorCode) {
t.Helper()
e, ok := domain.AsApplicationError(err)
if !ok || e.Code != want {
t.Fatalf("expected %s, got %v", want, err)
}
}
outside, err := repo.CreateUser(ctx, "attachment_outsider", "Outside", "hash")
if err != nil {
t.Fatal(err)
}
_, err = service.Get(ctx, first.ID, outside.ID)
requireCode(err, domain.ErrorNotFound)
obj, err := service.Content(ctx, first)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(obj)
obj.Close()
if err != nil || !bytes.Equal(data, imageBytes.Bytes()) {
t.Fatalf("original mismatch: %v", err)
}
otherChat, err := repo.CreateChat(ctx, "Other", []string{user.ID})
if err != nil {
t.Fatal(err)
}
_, err = repo.CreateMessageWithAttachments(ctx, otherChat.ID, user.ID, "", "cross-chat", []string{first.ID})
requireCode(err, domain.ErrorNotFound)
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "unknown", []string{uuid.NewString()})
requireCode(err, domain.ErrorNotFound)
sent, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil {
t.Fatal(err)
}
replay, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil || sent.ID != replay.ID {
t.Fatalf("replay failed: %v", err)
}
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{second.ID, first.ID})
requireCode(err, domain.ErrorConflict)
textOnly, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", nil)
if err != nil {
t.Fatal(err)
}
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", []string{})
if err != nil || textOnly.ID != replay.ID {
t.Fatalf("absent/empty differs: %v", err)
}
const callers = 12
outcomes := make(chan domain.Message, callers)
failures := make(chan error, callers)
var concurrent sync.WaitGroup
start := make(chan struct{})
for i := 0; i < callers; i++ {
concurrent.Add(1)
go func() {
defer concurrent.Done()
<-start
m, e := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "concurrent-attachments", []string{first.ID, second.ID})
if e != nil {
failures <- e
} else {
outcomes <- m
}
}()
}
close(start)
concurrent.Wait()
close(outcomes)
close(failures)
for e := range failures {
t.Fatal(e)
}
identity := ""
for m := range outcomes {
if identity == "" {
identity = m.ID
}
if m.ID != identity {
t.Fatal("duplicate concurrent attachment message")
}
}
var effects int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id=$1 AND idempotency_key='concurrent-attachments'`, chat.ID).Scan(&effects); err != nil || effects != 1 {
t.Fatalf("concurrent effects=%d %v", effects, err)
}
t.Log("ACL, original bytes, cross-chat attachment rejection, ordered/concurrent idempotency and absent=[] passed")
old := time.Now().Add(-3 * time.Minute)
orphan := "original/" + uuid.NewString()
fresh := "original/" + uuid.NewString()
locked := "original/" + uuid.NewString()
fake.mu.Lock()
delete(fake.objects, first.Key)
v := fake.objects[second.Key]
v.modified = old
fake.objects[second.Key] = v
fake.objects[orphan] = fakeObject{data: []byte("orphan"), modified: old}
fake.objects[fresh] = fakeObject{data: []byte("fresh"), modified: time.Now()}
fake.objects[locked] = fakeObject{data: []byte("locked"), modified: old}
fake.mu.Unlock()
if _, err = pool.Exec(ctx, `UPDATE attachments SET created_at=$1 WHERE id=ANY($2::uuid[])`, old, []string{first.ID, second.ID}); err != nil {
t.Fatal(err)
}
hold, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer hold.Rollback(ctx)
if _, err = hold.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, locked); err != nil {
t.Fatal(err)
}
dry, err := service.Reconcile(ctx, false, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if dry.Orphans != 1 || dry.Missing != 1 || dry.ReferencedMissing != 1 || dry.LockedSkipped != 1 || dry.FreshSkipped < 1 || dry.Deleted != 0 || dry.MarkedFailed != 0 {
t.Fatalf("bad dry-run %+v", dry)
}
var status string
if err = pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1`, first.ID).Scan(&status); err != nil || status != "ready" {
t.Fatalf("dry-run mutated metadata %s %v", status, err)
}
applied, err := service.Reconcile(ctx, true, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if applied.Deleted != 1 || applied.MarkedFailed != 1 {
t.Fatalf("bad apply %+v", applied)
}
fake.mu.Lock()
_, hasOrphan := fake.objects[orphan]
_, hasFresh := fake.objects[fresh]
_, hasLinked := fake.objects[second.Key]
_, hasLocked := fake.objects[locked]
fake.mu.Unlock()
if hasOrphan || !hasFresh || !hasLinked || !hasLocked {
t.Fatal("unsafe object cleanup")
}
_, err = service.Get(ctx, first.ID, user.ID)
requireCode(err, domain.ErrorConflict)
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "failed-attachment", []string{first.ID})
requireCode(err, domain.ErrorConflict)
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
if err != nil || replay.ID != sent.ID {
t.Fatalf("historical replay changed after missing: %v", err)
}
repeated, err := service.Reconcile(ctx, true, 90*time.Second)
if err != nil {
t.Fatal(err)
}
if repeated.Deleted != 0 || repeated.MarkedFailed != 0 || repeated.Orphans != 0 || repeated.Missing != 0 {
t.Fatalf("not repeatable %+v", repeated)
}
t.Logf("dry-run=%+v apply=%+v repeat=%+v; fresh, locked and referenced objects retained", dry, applied, repeated)
}
func TestS3WireFixture(t *testing.T) {
fake := &fakeS3{objects: map[string]fakeObject{}}
server := httptest.NewServer(fake)
defer server.Close()
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
if err != nil {
t.Fatal(err)
}
payload := []byte("exact object bytes")
_, err = client.PutObject(context.Background(), "attachments", "original/test", bytes.NewReader(payload), int64(len(payload)), minio.PutObjectOptions{ContentType: "image/png", DisableMultipart: true})
if err != nil {
t.Fatal(err)
}
obj, err := client.GetObject(context.Background(), "attachments", "original/test", minio.GetObjectOptions{})
if err != nil {
t.Fatal(err)
}
defer obj.Close()
got, err := io.ReadAll(obj)
if err != nil || !bytes.Equal(got, payload) {
t.Fatalf("wire fixture did not store original: %q %v", got, err)
}
}
+57 -22
View File
@@ -3,41 +3,76 @@ package postgres
import (
"context"
"errors"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"slices"
)
func (s *Storage) CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error) {
return s.CreateMessageWithAttachments(ctx, chatID, senderID, text, key, nil)
}
func (s *Storage) CreateMessageWithAttachments(ctx context.Context, chatID, senderID, text, key string, ids []string) (domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
message := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text}
if ids == nil {
ids = []string{}
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return domain.Message{}, dbError(err)
}
defer tx.Rollback(context.Background())
// Serialize this idempotency scope before validating attachments. A replay remains a
// replay even when reconciliation has since marked an original as missing.
if key != "" {
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, senderID+":"+chatID+":"+key)
if err != nil {
return domain.Message{}, dbError(err)
}
old := domain.Message{ChatID: chatID, SenderID: senderID}
err = tx.QueryRow(ctx, `SELECT id::text,text,attachment_ids::text[],created_at FROM messages WHERE sender_id=$1 AND chat_id=$2 AND idempotency_key=$3`, senderID, chatID, key).Scan(&old.ID, &old.Text, &old.AttachmentIDs, &old.CreatedAt)
if err == nil {
if old.Text != text || !slices.Equal(old.AttachmentIDs, ids) {
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
}
return old, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.Message{}, dbError(err)
}
}
// Lock each metadata row against reconciler updates until the link is committed.
for _, id := range ids {
var status string
err = tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE`, id, chatID).Scan(&status)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Message{}, domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
}
if err != nil {
return domain.Message{}, dbError(err)
}
if status != "ready" {
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Вложение не готово")
}
}
m := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}
var storedKey *string
if key != "" {
storedKey = &key
}
// One row contains both the side effect and its durable replay result.
err := s.pool.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,idempotency_key)
VALUES($1,$2,$3,$4,$5) ON CONFLICT (sender_id,chat_id,idempotency_key) DO NOTHING RETURNING created_at`,
message.ID, chatID, senderID, text, storedKey).Scan(&message.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
// A new READ COMMITTED statement sees the winner after the unique-index wait.
err = s.pool.QueryRow(ctx, `SELECT id::text,text,created_at FROM messages
WHERE sender_id=$1 AND chat_id=$2 AND idempotency_key=$3`, senderID, chatID, key).
Scan(&message.ID, &message.Text, &message.CreatedAt)
if err == nil && message.Text != text {
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
}
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,idempotency_key,attachment_ids) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, m.ID, chatID, senderID, text, storedKey, ids).Scan(&m.CreatedAt)
if err != nil {
return domain.Message{}, dbError(err)
}
return message, dbError(err)
return m, dbError(tx.Commit(ctx))
}
func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m WHERE m.chat_id=$1`
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.attachment_ids::text[],m.created_at FROM messages m WHERE m.chat_id=$1`
args := []any{chatID, limit}
if after != nil {
query += ` AND (m.created_at,m.id)>($3,$4)`
@@ -49,13 +84,13 @@ func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain
return nil, dbError(err)
}
defer rows.Close()
messages := make([]domain.Message, 0)
result := []domain.Message{}
for rows.Next() {
var m domain.Message
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.AttachmentIDs, &m.CreatedAt); err != nil {
return nil, dbError(err)
}
messages = append(messages, m)
result = append(result, m)
}
return messages, dbError(rows.Err())
return result, dbError(rows.Err())
}
@@ -142,6 +142,13 @@ func TestIntegration(t *testing.T) {
if err != nil {
t.Fatal(err)
}
t.Run("lab4_attachments_and_reconciliation", func(t *testing.T) {
isolated, e := repo.CreateChat(ctx, "Lab4", []string{user.ID})
if e != nil {
t.Fatal(e)
}
lab4Backend(t, pool, repo, user, isolated)
})
_, err = pool.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT md5(i::text)::uuid,$1,$2,'synthetic message '||i,
timestamptz '2026-01-01 00:00:00+00' + (i / 10) * interval '1 millisecond'
+26 -2
View File
@@ -3,7 +3,9 @@ package chat
import (
"context"
"errors"
"strings"
"time"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
@@ -105,10 +107,32 @@ func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message do
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.Message{}, err
}
if !validRequiredText(message.Text, 4000) {
if !utf8.ValidString(message.Text) || utf8.RuneCountInString(message.Text) > 4000 || (strings.TrimSpace(message.Text) == "" && len(message.AttachmentIDs) == 0) {
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
}
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
if len(message.AttachmentIDs) > 10 {
return domain.Message{}, invalid("Не более 10 вложений")
}
seen := map[string]bool{}
for i, id := range message.AttachmentIDs {
normalized, ok := normalizeUUID(id)
if !ok || seen[normalized] {
return domain.Message{}, invalid("Некорректные или повторные attachment_ids")
}
seen[normalized] = true
message.AttachmentIDs[i] = normalized
}
var created domain.Message
var err error
if repository, ok := u.repository.(interface {
CreateMessageWithAttachments(context.Context, string, string, string, string, []string) (domain.Message, error)
}); ok {
created, err = repository.CreateMessageWithAttachments(ctx, chatID, callerID, message.Text, message.IdempotencyKey, message.AttachmentIDs)
} else if len(message.AttachmentIDs) > 0 {
return domain.Message{}, notFound()
} else {
created, err = u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
}
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Message{}, notFound()
}