forked from mtusi2026/mtusi2026lab4
feat: attachments over S3 (grade 3)
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS message_attachments;
|
||||
DROP TABLE IF EXISTS attachments;
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_created_id_idx ON attachments (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
position int NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|
||||
@@ -200,6 +200,22 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, k
|
||||
if storedHash != requestHash {
|
||||
return domain.Message{}, domain.ErrConflict
|
||||
}
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, stored.ID)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
stored.AttachmentIDs, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (uuid.UUID, error) {
|
||||
var id uuid.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if stored.AttachmentIDs == nil {
|
||||
stored.AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
@@ -208,6 +224,20 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, k
|
||||
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if len(m.AttachmentIDs) > 0 {
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
SELECT $1, a.id, u.ord::int
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)
|
||||
JOIN attachments a ON a.id = u.id AND a.chat_id = $3 AND a.status = $4`,
|
||||
m.ID, m.AttachmentIDs, m.ChatID, domain.AttachmentReady)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if int(tag.RowsAffected()) != len(m.AttachmentIDs) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
@@ -247,9 +277,59 @@ func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domai
|
||||
if more {
|
||||
msgs = msgs[:limit]
|
||||
}
|
||||
if err := s.loadMessageAttachments(ctx, msgs); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return msgs, more, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a domain.Attachment) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.Status, a.ErrorCode, a.CreatedAt, a.UpdatedAt)
|
||||
return dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (domain.Attachment, error) {
|
||||
var a domain.Attachment
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at
|
||||
FROM attachments WHERE id = $1`, id,
|
||||
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
return a, dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) loadMessageAttachments(ctx context.Context, msgs []domain.Message) error {
|
||||
for i := range msgs {
|
||||
msgs[i].AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]uuid.UUID, len(msgs))
|
||||
index := make(map[uuid.UUID]int, len(msgs))
|
||||
for i, m := range msgs {
|
||||
ids[i] = m.ID
|
||||
index[m.ID] = i
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY($1) ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var messageID, attachmentID uuid.UUID
|
||||
if err := rows.Scan(&messageID, &attachmentID); err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
i := index[messageID]
|
||||
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, attachmentID)
|
||||
}
|
||||
return dbErr(rows.Err())
|
||||
}
|
||||
|
||||
func dbErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
region string
|
||||
}
|
||||
|
||||
func New(endpoint, region, accessKeyID, secretAccessKey, bucket string) (*Store, error) {
|
||||
host, secure := endpoint, false
|
||||
if parsed, err := url.Parse(endpoint); err == nil && parsed.Host != "" {
|
||||
host = parsed.Host
|
||||
secure = parsed.Scheme == "https"
|
||||
}
|
||||
client, err := minio.New(strings.TrimRight(host, "/"), &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Region: region,
|
||||
Secure: secure,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{client: client, bucket: bucket, region: region}, nil
|
||||
}
|
||||
|
||||
func (s *Store) EnsureBucket(ctx context.Context) error {
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return s.wrap(err)
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region}); err != nil {
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
|
||||
return nil
|
||||
}
|
||||
return s.wrap(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
_, err := s.client.BucketExists(ctx, s.bucket)
|
||||
return s.wrap(err)
|
||||
}
|
||||
|
||||
func (s *Store) 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})
|
||||
if err != nil && minio.ToErrorResponse(err).Code == "NoSuchBucket" {
|
||||
if ensureErr := s.EnsureBucket(ctx); ensureErr == nil {
|
||||
_, err = s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType})
|
||||
}
|
||||
}
|
||||
return s.wrap(err)
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, s.wrap(err)
|
||||
}
|
||||
if _, err := object.Stat(); err != nil {
|
||||
object.Close()
|
||||
return nil, s.wrap(err)
|
||||
}
|
||||
return object, nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
return s.wrap(s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
|
||||
}
|
||||
|
||||
func (s *Store) wrap(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
if response.StatusCode == http.StatusNotFound {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
Reference in New Issue
Block a user