forked from mtusi2026/mtusi2026lab4
лаба 4 на оценку 5
This commit is contained in:
@@ -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