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
+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
}