forked from mtusi2026/mtusi2026lab4
лаба 4 на оценку 5
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Checker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type MultiChecker struct {
|
||||
checkers []Checker
|
||||
}
|
||||
|
||||
func NewMultiChecker(checkers ...Checker) *MultiChecker {
|
||||
filtered := make([]Checker, 0, len(checkers))
|
||||
for _, checker := range checkers {
|
||||
if checker != nil {
|
||||
filtered = append(filtered, checker)
|
||||
}
|
||||
}
|
||||
return &MultiChecker{checkers: filtered}
|
||||
}
|
||||
|
||||
func (checker *MultiChecker) Ping(ctx context.Context) error {
|
||||
for index, dependency := range checker.checkers {
|
||||
if err := dependency.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("dependency %d: %w", index, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -166,6 +166,15 @@ func (r *MemoryRepository) CreateMessageIdempotently(
|
||||
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
for _, attachmentID := range write.AttachmentIDs {
|
||||
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
|
||||
if err != nil || attachment.ChatID != write.ChatID {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusReady {
|
||||
return domain.Message{}, application.ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
if stored, exists := r.idempotencyByScope[scope]; exists {
|
||||
if stored.expiresAt.After(now) {
|
||||
@@ -177,7 +186,12 @@ func (r *MemoryRepository) CreateMessageIdempotently(
|
||||
delete(r.idempotencyByScope, scope)
|
||||
}
|
||||
|
||||
message, err := r.legacy.CreateMessage(write.ChatID, write.ActorID, write.Text)
|
||||
message, err := r.legacy.CreateMessage(
|
||||
write.ChatID,
|
||||
write.ActorID,
|
||||
write.Text,
|
||||
write.AttachmentIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
@@ -277,6 +291,74 @@ func (r *MemoryRepository) DeleteSession(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := r.legacy.PutAttachment(attachment); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) MarkAttachmentReady(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return r.legacy.UpdateAttachmentStatus(
|
||||
attachmentID,
|
||||
domain.AttachmentStatusReady,
|
||||
nil,
|
||||
updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) MarkAttachmentFailed(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := r.legacy.UpdateAttachmentStatus(
|
||||
attachmentID,
|
||||
domain.AttachmentStatusFailed,
|
||||
&errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
callerID string,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
|
||||
var key [32]byte
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ type MemoryStore struct {
|
||||
chatsByID map[string]domain.Chat //key = chat UUID
|
||||
|
||||
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
|
||||
|
||||
attachmentsByID map[string]domain.Attachment
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
@@ -28,6 +30,7 @@ func NewMemoryStore() *MemoryStore {
|
||||
usersByUsername: make(map[string]string),
|
||||
chatsByID: make(map[string]domain.Chat),
|
||||
messagesByChatID: make(map[string][]domain.Message),
|
||||
attachmentsByID: make(map[string]domain.Attachment),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,12 +180,86 @@ func (s *MemoryStore) GetChatsForUser(
|
||||
return items, end < len(chats), nil
|
||||
}
|
||||
|
||||
// PutAttachment stores metadata for adapter and application tests. Binary
|
||||
// content intentionally does not belong to this in-memory metadata store.
|
||||
func (s *MemoryStore) PutAttachment(attachment domain.Attachment) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, exists := s.attachmentsByID[attachment.ID]; exists {
|
||||
return ErrConflict
|
||||
}
|
||||
|
||||
chat, exists := s.chatsByID[attachment.ChatID]
|
||||
if !exists {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
ownerIsMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == attachment.OwnerID {
|
||||
ownerIsMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ownerIsMember {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
s.attachmentsByID[attachment.ID] = attachment
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetAttachmentByID(
|
||||
attachmentID string,
|
||||
) (domain.Attachment, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
attachment, exists := s.attachmentsByID[attachmentID]
|
||||
if !exists {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) UpdateAttachmentStatus(
|
||||
attachmentID string,
|
||||
status domain.AttachmentStatus,
|
||||
errorCode *string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
attachment, exists := s.attachmentsByID[attachmentID]
|
||||
if !exists {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusPending {
|
||||
return domain.Attachment{}, ErrConflict
|
||||
}
|
||||
attachment.Status = status
|
||||
attachment.ErrorCode = errorCode
|
||||
attachment.UpdatedAt = updatedAt
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
s.attachmentsByID[attachmentID] = attachment
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
// ---Сообщения---
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
chatID, senderID, text string,
|
||||
attachmentLists ...[]string,
|
||||
) (domain.Message, error) {
|
||||
messageID := uuid.NewString()
|
||||
attachmentIDs := make([]string, 0)
|
||||
if len(attachmentLists) > 0 {
|
||||
attachmentIDs = append(attachmentIDs, attachmentLists[0]...)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -216,11 +293,12 @@ func (s *MemoryStore) CreateMessage(
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: messageID,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
ID: messageID,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChatID[chatID] = append(messages, message)
|
||||
@@ -282,6 +360,12 @@ func (s *MemoryStore) GetMessages(
|
||||
|
||||
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
|
||||
items := make([]domain.Message, end-start)
|
||||
copy(items, messages[start:end])
|
||||
for index, message := range messages[start:end] {
|
||||
message.AttachmentIDs = append(
|
||||
make([]string, 0, len(message.AttachmentIDs)),
|
||||
message.AttachmentIDs...,
|
||||
)
|
||||
items[index] = message
|
||||
}
|
||||
return items, end < len(messages), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/application"
|
||||
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type MinIOStore struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
operationTimeout time.Duration
|
||||
}
|
||||
|
||||
type StoredObject struct {
|
||||
Key string
|
||||
SizeBytes int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
func NewMinIOStore(
|
||||
endpoint string,
|
||||
region string,
|
||||
bucket string,
|
||||
accessKeyID string,
|
||||
secretAccessKey string,
|
||||
operationTimeout time.Duration,
|
||||
) (*MinIOStore, error) {
|
||||
parsedEndpoint, err := url.Parse(endpoint)
|
||||
if err != nil || parsedEndpoint.Host == "" {
|
||||
return nil, fmt.Errorf("S3 endpoint must be an absolute HTTP(S) URL")
|
||||
}
|
||||
if parsedEndpoint.Scheme != "http" && parsedEndpoint.Scheme != "https" {
|
||||
return nil, fmt.Errorf("S3 endpoint scheme must be http or https")
|
||||
}
|
||||
if parsedEndpoint.Path != "" && parsedEndpoint.Path != "/" {
|
||||
return nil, fmt.Errorf("S3 endpoint must not contain a path")
|
||||
}
|
||||
if parsedEndpoint.RawQuery != "" || parsedEndpoint.Fragment != "" || parsedEndpoint.User != nil {
|
||||
return nil, fmt.Errorf("S3 endpoint must not contain credentials, query or fragment")
|
||||
}
|
||||
if strings.TrimSpace(bucket) == "" || strings.TrimSpace(accessKeyID) == "" ||
|
||||
strings.TrimSpace(secretAccessKey) == "" {
|
||||
return nil, fmt.Errorf("S3 bucket and credentials are required")
|
||||
}
|
||||
if operationTimeout <= 0 {
|
||||
return nil, fmt.Errorf("S3 operation timeout must be positive")
|
||||
}
|
||||
|
||||
client, err := minio.New(parsedEndpoint.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: parsedEndpoint.Scheme == "https",
|
||||
Region: region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create MinIO client: %w", err)
|
||||
}
|
||||
return &MinIOStore{client: client, bucket: bucket, operationTimeout: operationTimeout}, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Put(ctx context.Context, object application.ObjectPut) error {
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
upload, err := store.client.PutObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
object.Key,
|
||||
object.Body,
|
||||
object.SizeBytes,
|
||||
minio.PutObjectOptions{ContentType: object.ContentType},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("put MinIO object: %w", err)
|
||||
}
|
||||
if upload.Size != object.SizeBytes {
|
||||
return fmt.Errorf("put MinIO object: stored %d bytes, want %d", upload.Size, object.SizeBytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Get(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
) (application.ObjectContent, error) {
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
stat, err := store.client.StatObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.StatObjectOptions{},
|
||||
)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("stat MinIO object: %w", err)
|
||||
}
|
||||
object, err := store.client.GetObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.GetObjectOptions{},
|
||||
)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("get MinIO object: %w", err)
|
||||
}
|
||||
firstByte := make([]byte, 1)
|
||||
readCount, readError := object.Read(firstByte)
|
||||
if readError != nil && readCount == 0 {
|
||||
_ = object.Close()
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("read MinIO object: %w", readError)
|
||||
}
|
||||
if readCount != 1 {
|
||||
_ = object.Close()
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("read MinIO object: expected non-empty object")
|
||||
}
|
||||
return application.ObjectContent{
|
||||
Body: &cancelingReadCloser{
|
||||
Reader: io.MultiReader(bytes.NewReader(firstByte), object),
|
||||
Closer: object,
|
||||
cancel: cancel,
|
||||
},
|
||||
SizeBytes: stat.Size,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) List(
|
||||
ctx context.Context,
|
||||
prefix string,
|
||||
) ([]StoredObject, error) {
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
|
||||
objects := make([]StoredObject, 0)
|
||||
for object := range store.client.ListObjects(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
minio.ListObjectsOptions{Prefix: prefix, Recursive: true},
|
||||
) {
|
||||
if object.Err != nil {
|
||||
return nil, fmt.Errorf("list MinIO objects: %w", object.Err)
|
||||
}
|
||||
objects = append(objects, StoredObject{
|
||||
Key: object.Key,
|
||||
SizeBytes: object.Size,
|
||||
LastModified: object.LastModified.UTC(),
|
||||
})
|
||||
}
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Delete(ctx context.Context, key string) error {
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
if err := store.client.RemoveObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.RemoveObjectOptions{},
|
||||
); err != nil {
|
||||
return fmt.Errorf("delete MinIO object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Ping(ctx context.Context) error {
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
exists, err := store.client.BucketExists(operationContext, store.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check MinIO bucket: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return fmt.Errorf("MinIO bucket %q does not exist", store.bucket)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type cancelingReadCloser struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (reader *cancelingReadCloser) Close() error {
|
||||
err := reader.Closer.Close()
|
||||
reader.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
var _ application.ObjectStore = (*MinIOStore)(nil)
|
||||
@@ -0,0 +1,37 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewMinIOStoreValidatesConfiguration(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
endpoint string
|
||||
bucket string
|
||||
accessKey string
|
||||
secretKey string
|
||||
timeout time.Duration
|
||||
wantError bool
|
||||
}{
|
||||
{name: "valid HTTP", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
|
||||
{name: "valid HTTPS", endpoint: "https://s3.example.test", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
|
||||
{name: "relative endpoint", endpoint: "minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "endpoint path", endpoint: "http://minio:9000/path", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "embedded credentials", endpoint: "http://user:pass@minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "empty bucket", endpoint: "http://minio:9000", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "empty credentials", endpoint: "http://minio:9000", bucket: "attachments", timeout: time.Second, wantError: true},
|
||||
{name: "invalid timeout", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", wantError: true},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
_, err := NewMinIOStore(testCase.endpoint, "us-east-1", testCase.bucket,
|
||||
testCase.accessKey, testCase.secretKey, testCase.timeout)
|
||||
if (err != nil) != testCase.wantError {
|
||||
t.Fatalf("NewMinIOStore() error = %v, wantError %v", err, testCase.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
"mtusi2026lab4/internal/reconcile"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, status, error_code,
|
||||
created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, decode($8, 'hex'), $9, $10, $11, $12,
|
||||
$13, $14
|
||||
)
|
||||
RETURNING created_at, updated_at
|
||||
`,
|
||||
attachment.ID,
|
||||
attachment.ChatID,
|
||||
attachment.OwnerID,
|
||||
attachment.ObjectKey,
|
||||
attachment.Filename,
|
||||
attachment.ContentType,
|
||||
attachment.SizeBytes,
|
||||
attachment.SHA256,
|
||||
attachment.Width,
|
||||
attachment.Height,
|
||||
attachment.Status,
|
||||
attachment.ErrorCode,
|
||||
attachment.CreatedAt,
|
||||
attachment.UpdatedAt,
|
||||
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err)
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentReady(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'ready', error_code = NULL, updated_at = $2
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
RETURNING
|
||||
id::text, chat_id::text, owner_id::text, object_key,
|
||||
filename, content_type, size_bytes, sha256, width, height,
|
||||
status, error_code, created_at, updated_at
|
||||
`,
|
||||
attachmentID,
|
||||
updatedAt,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailed(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
commandTag, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = $3
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
`,
|
||||
attachmentID,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment failed: %w", err)
|
||||
}
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
callerID string,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text, a.chat_id::text, a.owner_id::text, a.object_key,
|
||||
a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.width, a.height, a.status, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1
|
||||
`,
|
||||
attachmentID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListAttachmentInventory(
|
||||
ctx context.Context,
|
||||
) ([]reconcile.AttachmentRecord, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text,
|
||||
a.object_key,
|
||||
a.status,
|
||||
a.updated_at,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced
|
||||
FROM attachments AS a
|
||||
ORDER BY a.id
|
||||
`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query attachment inventory: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
records := make([]reconcile.AttachmentRecord, 0)
|
||||
for rows.Next() {
|
||||
var record reconcile.AttachmentRecord
|
||||
if err = rows.Scan(
|
||||
&record.ID,
|
||||
&record.ObjectKey,
|
||||
&record.Status,
|
||||
&record.UpdatedAt,
|
||||
&record.Referenced,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment inventory: %w", err)
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate attachment inventory: %w", err)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
expectedStatus domain.AttachmentStatus,
|
||||
updatedBefore time.Time,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var lockedAttachmentID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text
|
||||
FROM attachments
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
`,
|
||||
attachmentID,
|
||||
).Scan(&lockedAttachmentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment during reconciliation: %w", err)
|
||||
}
|
||||
|
||||
// This is deliberately a second statement. Under READ COMMITTED it gets a
|
||||
// fresh snapshot after the row lock was acquired, so a message transaction
|
||||
// that linked this attachment while we waited is visible to NOT EXISTS.
|
||||
commandTag, err := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments AS a
|
||||
SET status = 'failed', error_code = $4, updated_at = $5
|
||||
WHERE a.id = $1
|
||||
AND a.status = $2
|
||||
AND a.updated_at <= $3
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
)
|
||||
`,
|
||||
attachmentID,
|
||||
expectedStatus,
|
||||
updatedBefore,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err)
|
||||
}
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit attachment reconciliation: %w", err)
|
||||
}
|
||||
return commandTag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil)
|
||||
@@ -48,6 +48,59 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs))
|
||||
for index, attachmentID := range write.AttachmentIDs {
|
||||
parsedID, parseErr := uuid.Parse(attachmentID)
|
||||
if parseErr != nil {
|
||||
return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr)
|
||||
}
|
||||
attachmentUUIDs[index] = parsedID
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
rows, queryError := transaction.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1
|
||||
AND id = ANY($2::uuid[])
|
||||
ORDER BY id
|
||||
FOR UPDATE
|
||||
`,
|
||||
write.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError)
|
||||
}
|
||||
availableCount := 0
|
||||
readyCount := 0
|
||||
for rows.Next() {
|
||||
var attachmentID string
|
||||
var status domain.AttachmentStatus
|
||||
if queryError = rows.Scan(&attachmentID, &status); queryError != nil {
|
||||
rows.Close()
|
||||
return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError)
|
||||
}
|
||||
availableCount++
|
||||
if status == domain.AttachmentStatusReady {
|
||||
readyCount++
|
||||
}
|
||||
}
|
||||
queryError = rows.Err()
|
||||
rows.Close()
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError)
|
||||
}
|
||||
if availableCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
if readyCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, application.ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
@@ -68,10 +121,11 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: write.ChatID,
|
||||
SenderID: write.ActorID,
|
||||
Text: write.Text,
|
||||
ID: uuid.NewString(),
|
||||
ChatID: write.ChatID,
|
||||
SenderID: write.ActorID,
|
||||
Text: write.Text,
|
||||
AttachmentIDs: append([]string(nil), write.AttachmentIDs...),
|
||||
}
|
||||
|
||||
var storedHash []byte
|
||||
@@ -141,7 +195,15 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`,
|
||||
@@ -152,6 +214,7 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
@@ -187,6 +250,28 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_attachments (
|
||||
message_id,
|
||||
chat_id,
|
||||
attachment_id,
|
||||
position
|
||||
)
|
||||
SELECT $1, $2, attachment_id, (ordinality - 1)::smallint
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality)
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("link message attachments: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
@@ -241,7 +326,15 @@ func (s *PostgreSQLStore) GetMessages(
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY
|
||||
@@ -261,7 +354,15 @@ func (s *PostgreSQLStore) GetMessages(
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
@@ -296,6 +397,7 @@ func (s *PostgreSQLStore) GetMessages(
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"scan message page: %w",
|
||||
|
||||
Reference in New Issue
Block a user