Files
mtusi2026lab4/internal/store/attachments.go

185 lines
6.6 KiB
Go

package store
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"mtusi.ru/messenger-lab4/internal/model"
)
// AttachmentRecord is the database view of an attachment. ObjectKey is an
// internal server detail and is never serialised into the public API.
type AttachmentRecord struct {
model.Attachment
ObjectKey string
}
// ReconcileAttachment is the minimal row the offline reconciler needs. It is
// intentionally not an API shape.
type ReconcileAttachment struct {
ID string
ObjectKey string
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
// CreatePendingAttachment records the upload intent before the S3 PUT. If the
// process dies after this insert, the row is still accounted for and the
// reconciler can remove it after the grace period; it is never returned by the
// public API because only ready rows are visible.
func (s *Store) CreatePendingAttachment(ctx context.Context, record AttachmentRecord, createdAt time.Time) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
status, error_code, object_key, created_at, updated_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7,
'pending', NULL, $8, $9, $9)`,
record.ID, record.ChatID, record.OwnerID, record.Filename,
record.ContentType, record.SizeBytes, record.SHA256, record.ObjectKey, createdAt,
)
return s.classify(err)
}
// MarkAttachmentReady promotes the pending row after the original bytes are in
// S3. If the update fails, the row stays pending and the object remains
// accounted; the reconciler owns the cleanup. Nothing is deleted here because
// an ambiguous commit must never destroy a successfully stored original.
func (s *Store) MarkAttachmentReady(ctx context.Context, id string, updatedAt time.Time) (time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var stored time.Time
err := s.pool.QueryRow(ctx, `
UPDATE attachments
SET status = 'ready', updated_at = $2
WHERE id = $1::uuid AND status = 'pending'
RETURNING updated_at`, id, updatedAt).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, ErrNotFound
}
if err != nil {
return time.Time{}, s.classify(err)
}
return stored.UTC(), nil
}
// ReadyAttachmentForUser applies the ACL in SQL: the row is returned only when
// the caller is a member of the attachment's chat and the attachment is ready.
// A foreign and a nonexistent attachment are indistinguishable.
func (s *Store) ReadyAttachmentForUser(ctx context.Context, attachmentID, userID string) (AttachmentRecord, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var record AttachmentRecord
var createdAt, updatedAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename,
a.content_type, a.size_bytes, a.sha256, a.status, a.error_code,
a.object_key, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2::uuid
WHERE a.id = $1::uuid AND a.status = 'ready'`,
attachmentID, userID,
).Scan(&record.ID, &record.ChatID, &record.OwnerID, &record.Filename,
&record.ContentType, &record.SizeBytes, &record.SHA256, &record.Status, &record.ErrorCode,
&record.ObjectKey, &createdAt, &updatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return AttachmentRecord{}, ErrNotFound
}
return AttachmentRecord{}, s.classify(err)
}
record.CreatedAt = model.Time{Time: createdAt.UTC()}
record.UpdatedAt = model.Time{Time: updatedAt.UTC()}
record.Variants = []model.Variant{}
return record, nil
}
// DeleteAttachmentRow removes a pending upload intent. It is used only after a
// failed S3 PUT or by the reconciler; ready rows are never deleted here.
func (s *Store) DeleteAttachmentRow(ctx context.Context, id string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id)
return s.classify(err)
}
// ListAttachmentsForReconcile returns every row, including internal pending
// upload intents. Only the offline reconciler calls it.
func (s *Store) ListAttachmentsForReconcile(ctx context.Context) ([]ReconcileAttachment, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
rows, err := s.pool.Query(ctx, `
SELECT id::text, object_key, status, created_at, updated_at
FROM attachments
ORDER BY created_at, id`)
if err != nil {
return nil, s.classify(err)
}
defer rows.Close()
result := make([]ReconcileAttachment, 0, 128)
for rows.Next() {
var item ReconcileAttachment
if err := rows.Scan(&item.ID, &item.ObjectKey, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
return nil, s.classify(err)
}
result = append(result, item)
}
if err := rows.Err(); err != nil {
return nil, s.classify(err)
}
return result, nil
}
// AttachmentByObjectKey reports whether a row still references the key. The
// reconciler re-checks this immediately before deleting an object, so a
// concurrent upload that committed between the snapshot and the delete is not
// destroyed.
func (s *Store) AttachmentByObjectKey(ctx context.Context, key string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var exists bool
if err := s.pool.QueryRow(ctx,
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&exists); err != nil {
return false, s.classify(err)
}
return exists, nil
}
// AttachmentState re-reads the status and key before a mutation. A pending row
// that became ready while the reconciler was scanning must not be deleted.
func (s *Store) AttachmentState(ctx context.Context, id string) (string, string, time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var status, objectKey string
var updatedAt time.Time
err := s.pool.QueryRow(ctx,
`SELECT status, object_key, updated_at FROM attachments WHERE id = $1::uuid`, id,
).Scan(&status, &objectKey, &updatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", time.Time{}, ErrNotFound
}
if err != nil {
return "", "", time.Time{}, s.classify(err)
}
return status, objectKey, updatedAt.UTC(), nil
}
// DeleteAttachmentIfPending deletes the row only while it is still pending.
// The status predicate is the last line of defence against deleting a row that
// a concurrent request has already promoted to ready.
func (s *Store) DeleteAttachmentIfPending(ctx context.Context, id string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx,
`DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`, id)
if err != nil {
return false, s.classify(err)
}
return tag.RowsAffected() == 1, nil
}