forked from mtusi2026/mtusi2026lab4
307 lines
7.2 KiB
Go
307 lines
7.2 KiB
Go
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)
|