lab4: S3-вложения, presigned upload и проверки

This commit is contained in:
Vladislav Kunetskiy
2026-10-21 22:42:48 +03:00
parent d342b2a227
commit 49c2fe3071
79 changed files with 12266 additions and 910 deletions
@@ -0,0 +1,215 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type AttachmentRepository struct {
store *Store
}
func (r *AttachmentRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return false, fmt.Errorf("check chat membership: %w", mapError(err))
}
return member, nil
}
func (r *AttachmentRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateAttachment(ctx, sqlcgen.CreateAttachmentParams{
ID: draft.ID,
ChatID: draft.ChatID,
OwnerID: draft.OwnerID,
ObjectKey: draft.ObjectKey,
Filename: draft.Filename,
ContentType: draft.ContentType,
SizeBytes: draft.SizeBytes,
Sha256: draft.SHA256,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
}
return mapAttachment(row), nil
}
func (r *AttachmentRepository) MarkReady(
ctx context.Context,
id uuid.UUID,
objectKey string,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.MarkAttachmentReady(ctx, sqlcgen.MarkAttachmentReadyParams{
ID: id,
ObjectKey: objectKey,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
}
return mapAttachment(row), nil
}
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
if err := r.store.queries.DeletePendingAttachment(ctx, id); err != nil {
return fmt.Errorf("delete pending attachment: %w", mapError(err))
}
return nil
}
func (r *AttachmentRepository) GetForMember(
ctx context.Context,
userID, id uuid.UUID,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetAttachmentForMember(ctx, sqlcgen.GetAttachmentForMemberParams{
ID: id,
UserID: userID,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
}
return mapAttachment(row), nil
}
func (r *AttachmentRepository) GetForOwner(
ctx context.Context,
ownerID, id uuid.UUID,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetAttachmentForOwner(ctx, sqlcgen.GetAttachmentForOwnerParams{
ID: id,
OwnerID: ownerID,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
}
return mapAttachment(row), nil
}
func (r *AttachmentRepository) ListStates(
ctx context.Context,
chatID uuid.UUID,
ids []uuid.UUID,
) ([]domain.AttachmentState, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListAttachmentStatesForChat(ctx, sqlcgen.ListAttachmentStatesForChatParams{
ChatID: chatID,
Ids: ids,
})
if err != nil {
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
}
states := make([]domain.AttachmentState, 0, len(rows))
for _, row := range rows {
states = append(states, domain.AttachmentState{
ID: row.ID,
Status: domain.AttachmentStatus(row.Status),
})
}
return states, nil
}
func (r *AttachmentRepository) ListStalePending(
ctx context.Context,
createdBefore time.Time,
limit int32,
) ([]domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListStalePendingAttachments(ctx, sqlcgen.ListStalePendingAttachmentsParams{
CreatedBefore: createdBefore,
RowLimit: limit,
})
if err != nil {
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
}
return mapAll(rows, mapAttachment), nil
}
func (r *AttachmentRepository) ListKeys(
ctx context.Context,
limit, offset int32,
) ([]domain.AttachmentKey, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListAttachmentKeys(ctx, sqlcgen.ListAttachmentKeysParams{
RowLimit: limit,
RowOffset: offset,
})
if err != nil {
return nil, fmt.Errorf("list attachment keys: %w", mapError(err))
}
keys := make([]domain.AttachmentKey, 0, len(rows))
for _, row := range rows {
keys = append(keys, domain.AttachmentKey{
ID: row.ID,
ObjectKey: row.ObjectKey,
Status: domain.AttachmentStatus(row.Status),
CreatedAt: toUTCTime(row.CreatedAt),
})
}
return keys, nil
}
func mapAttachment(row sqlcgen.Attachment) domain.Attachment {
attachment := domain.Attachment{
ID: row.ID,
ChatID: row.ChatID,
OwnerID: row.OwnerID,
ObjectKey: row.ObjectKey,
Filename: row.Filename,
ContentType: row.ContentType,
SizeBytes: row.SizeBytes,
SHA256: row.Sha256,
Status: domain.AttachmentStatus(row.Status),
CreatedAt: toUTCTime(row.CreatedAt),
UpdatedAt: toUTCTime(row.UpdatedAt),
}
if row.ErrorCode.Valid {
code := row.ErrorCode.String
attachment.ErrorCode = &code
}
return attachment
}
@@ -0,0 +1,92 @@
//go:build integration
package postgres_test
import (
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type AttachmentRepositorySuite struct {
BaseSuite
}
func TestAttachmentRepositorySuite(t *testing.T) {
suite.Run(t, new(AttachmentRepositorySuite))
}
func (s *AttachmentRepositorySuite) TestLifecycleAndMessageLinks() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob)
id, err := uuid.NewV7()
s.Require().NoError(err)
objectKey := "attachments/" + chat.ID.String() + "/" + id.String()
digest := strings.Repeat("a", 64)
created, err := s.store.Attachments().Create(s.T().Context(), domain.AttachmentDraft{
ID: id,
ChatID: chat.ID,
OwnerID: alice.ID,
ObjectKey: objectKey,
Filename: "photo.png",
ContentType: "image/png",
SizeBytes: 123,
SHA256: digest,
})
s.Require().NoError(err)
s.Equal(domain.AttachmentPending, created.Status)
visible, err := s.store.Attachments().GetForMember(s.T().Context(), bob.ID, id)
s.Require().NoError(err)
s.Equal(alice.ID, visible.OwnerID)
_, err = s.store.Attachments().GetForMember(s.T().Context(), eve.ID, id)
s.Require().ErrorIs(err, domain.ErrNotFound)
ready, err := s.store.Attachments().MarkReady(s.T().Context(), id, objectKey)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, ready.Status)
states, err := s.store.Attachments().ListStates(
s.T().Context(), chat.ID, []uuid.UUID{id},
)
s.Require().NoError(err)
s.Require().Len(states, 1)
s.Equal(domain.AttachmentReady, states[0].Status)
key := uuid.NewString()
draft := domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: "",
AttachmentIDs: []uuid.UUID{id},
Idempotency: domain.MessageIdempotency{
Key: key,
RequestHash: [32]byte{1},
},
}
message, err := s.store.Messages().Create(s.T().Context(), draft)
s.Require().NoError(err)
s.Equal([]uuid.UUID{id}, message.AttachmentIDs)
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
s.Require().NoError(err)
s.Require().Len(page.Items, 1)
s.Equal([]uuid.UUID{id}, page.Items[0].AttachmentIDs)
s.Empty(page.Items[0].Text)
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
s.Require().NoError(err)
s.Equal(message.ID, replayed.ID)
s.Equal([]uuid.UUID{id}, replayed.AttachmentIDs)
}
@@ -0,0 +1,367 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: attachments.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const attachToMessage = `-- name: AttachToMessage :exec
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES ($1, $2, $3)
`
type AttachToMessageParams struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Position int16
}
func (q *Queries) AttachToMessage(ctx context.Context, arg AttachToMessageParams) error {
_, err := q.db.Exec(ctx, attachToMessage, arg.MessageID, arg.AttachmentID, arg.Position)
return err
}
const createAttachment = `-- name: CreateAttachment :one
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
'pending'
)
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
`
type CreateAttachmentParams struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, createAttachment,
arg.ID,
arg.ChatID,
arg.OwnerID,
arg.ObjectKey,
arg.Filename,
arg.ContentType,
arg.SizeBytes,
arg.Sha256,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.ObjectKey,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deletePendingAttachment = `-- name: DeletePendingAttachment :exec
DELETE FROM attachments
WHERE id = $1
AND status = 'pending'
`
func (q *Queries) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, deletePendingAttachment, id)
return err
}
const getAttachmentForMember = `-- name: GetAttachmentForMember :one
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id
AND cm.user_id = $1
WHERE a.id = $2
`
type GetAttachmentForMemberParams struct {
UserID uuid.UUID
ID uuid.UUID
}
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachmentForMember, arg.UserID, arg.ID)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.ObjectKey,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAttachmentForOwner = `-- name: GetAttachmentForOwner :one
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id
AND cm.user_id = a.owner_id
WHERE a.id = $1
AND a.owner_id = $2
`
type GetAttachmentForOwnerParams struct {
ID uuid.UUID
OwnerID uuid.UUID
}
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachmentForOwner, arg.ID, arg.OwnerID)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.ObjectKey,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const listAttachmentKeys = `-- name: ListAttachmentKeys :many
SELECT id, object_key, status, created_at
FROM attachments
ORDER BY id
LIMIT $2 OFFSET $1
`
type ListAttachmentKeysParams struct {
RowOffset int32
RowLimit int32
}
type ListAttachmentKeysRow struct {
ID uuid.UUID
ObjectKey string
Status string
CreatedAt time.Time
}
func (q *Queries) ListAttachmentKeys(ctx context.Context, arg ListAttachmentKeysParams) ([]ListAttachmentKeysRow, error) {
rows, err := q.db.Query(ctx, listAttachmentKeys, arg.RowOffset, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListAttachmentKeysRow{}
for rows.Next() {
var i ListAttachmentKeysRow
if err := rows.Scan(
&i.ID,
&i.ObjectKey,
&i.Status,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAttachmentStatesForChat = `-- name: ListAttachmentStatesForChat :many
SELECT id, status
FROM attachments
WHERE chat_id = $1
AND id = ANY($2::uuid[])
`
type ListAttachmentStatesForChatParams struct {
ChatID uuid.UUID
Ids []uuid.UUID
}
type ListAttachmentStatesForChatRow struct {
ID uuid.UUID
Status string
}
func (q *Queries) ListAttachmentStatesForChat(ctx context.Context, arg ListAttachmentStatesForChatParams) ([]ListAttachmentStatesForChatRow, error) {
rows, err := q.db.Query(ctx, listAttachmentStatesForChat, arg.ChatID, arg.Ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListAttachmentStatesForChatRow{}
for rows.Next() {
var i ListAttachmentStatesForChatRow
if err := rows.Scan(&i.ID, &i.Status); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessageAttachments = `-- name: ListMessageAttachments :many
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY($1::uuid[])
ORDER BY message_id, position
`
type ListMessageAttachmentsRow struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
}
func (q *Queries) ListMessageAttachments(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsRow, error) {
rows, err := q.db.Query(ctx, listMessageAttachments, messageIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListMessageAttachmentsRow{}
for rows.Next() {
var i ListMessageAttachmentsRow
if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listStalePendingAttachments = `-- name: ListStalePendingAttachments :many
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
FROM attachments
WHERE status = 'pending'
AND created_at < $1
ORDER BY created_at
LIMIT $2
`
type ListStalePendingAttachmentsParams struct {
CreatedBefore time.Time
RowLimit int32
}
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]Attachment, error) {
rows, err := q.db.Query(ctx, listStalePendingAttachments, arg.CreatedBefore, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
for rows.Next() {
var i Attachment
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.ObjectKey,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markAttachmentReady = `-- name: MarkAttachmentReady :one
UPDATE attachments
SET status = 'ready',
object_key = $1,
updated_at = now()
WHERE id = $2
AND status = 'pending'
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
`
type MarkAttachmentReadyParams struct {
ObjectKey string
ID uuid.UUID
}
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (Attachment, error) {
row := q.db.QueryRow(ctx, markAttachmentReady, arg.ObjectKey, arg.ID)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.ObjectKey,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -11,6 +11,21 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
type Chat struct {
ID uuid.UUID
Title string
@@ -31,6 +46,12 @@ type Message struct {
CreatedAt time.Time
}
type MessageAttachment struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Position int16
}
type MessageIdempotency struct {
ActorID uuid.UUID
ChatID uuid.UUID
+112 -12
View File
@@ -19,6 +19,21 @@ type MessageRepository struct {
store *Store
}
func (r *MessageRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return false, fmt.Errorf("check chat membership: %w", mapError(err))
}
return member, nil
}
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
var created domain.Message
@@ -80,6 +95,16 @@ func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.M
return domain.Message{}, mapError(err)
}
for position, attachmentID := range draft.AttachmentIDs {
if err := queries.AttachToMessage(ctx, sqlcgen.AttachToMessageParams{
MessageID: row.ID,
AttachmentID: attachmentID,
Position: int16(position),
}); err != nil {
return domain.Message{}, mapError(err)
}
}
err = queries.CompleteMessageIdempotency(ctx, sqlcgen.CompleteMessageIdempotencyParams{
MessageID: pgtype.UUID{Bytes: row.ID, Valid: true},
ActorID: draft.SenderID,
@@ -90,7 +115,11 @@ func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.M
return domain.Message{}, mapError(err)
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
created := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
created.AttachmentIDs = make([]uuid.UUID, 0, len(draft.AttachmentIDs))
created.AttachmentIDs = append(created.AttachmentIDs, draft.AttachmentIDs...)
return created, nil
}
func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
@@ -116,7 +145,34 @@ func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domai
return domain.Message{}, mapError(err)
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
replayed := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
if err != nil {
return domain.Message{}, err
}
return replayed, nil
}
// listAttachmentIDs returns attachment IDs in the order the sender supplied
// them. An empty result is normalised to an empty slice, never nil: the
// contract marks attachment_ids as required.
func listAttachmentIDs(
ctx context.Context,
queries *sqlcgen.Queries,
messageID uuid.UUID,
) ([]uuid.UUID, error) {
rows, err := queries.ListMessageAttachments(ctx, []uuid.UUID{messageID})
if err != nil {
return nil, fmt.Errorf("list message attachments: %w", mapError(err))
}
ids := make([]uuid.UUID, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.AttachmentID)
}
return ids, nil
}
func (r *MessageRepository) ListVisible(
@@ -164,6 +220,8 @@ func (r *MessageRepository) fetch(
after *domain.Cursor,
fetch int32,
) ([]domain.Message, error) {
var messages []domain.Message
if after == nil {
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
ChatID: chatID,
@@ -174,21 +232,63 @@ func (r *MessageRepository) fetch(
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
messages = mapAll(rows, mapMessageRow)
} else {
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
ChatID: chatID,
CallerID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
messages = mapAll(rows, mapMessageRow)
}
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
ChatID: chatID,
CallerID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err := attachMessageLinks(ctx, r.store.queries, messages); err != nil {
return nil, err
}
return messages, nil
}
// attachMessageLinks fetches all links for a page in one query and normalises
// absent lists to empty slices.
func attachMessageLinks(
ctx context.Context,
queries *sqlcgen.Queries,
messages []domain.Message,
) error {
if len(messages) == 0 {
return nil
}
ids := make([]uuid.UUID, 0, len(messages))
for index := range messages {
ids = append(ids, messages[index].ID)
messages[index].AttachmentIDs = []uuid.UUID{}
}
rows, err := queries.ListMessageAttachments(ctx, ids)
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
return fmt.Errorf("list message attachments: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
byMessage := make(map[uuid.UUID][]uuid.UUID, len(messages))
for _, row := range rows {
byMessage[row.MessageID] = append(byMessage[row.MessageID], row.AttachmentID)
}
for index := range messages {
if linked, ok := byMessage[messages[index].ID]; ok {
messages[index].AttachmentIDs = linked
}
}
return nil
}
func mapMessageRow(row sqlcgen.Message) domain.Message {
@@ -0,0 +1,55 @@
-- +goose Up
-- Attachment metadata lives in PostgreSQL; the original bytes live only in S3.
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) ON DELETE RESTRICT,
object_key text NOT NULL,
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
status text NOT NULL,
error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
CONSTRAINT attachments_status_check CHECK (status IN ('pending', 'ready', 'failed')),
CONSTRAINT attachments_content_type_check CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_size_check CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_check CHECK (sha256 ~ '^[0-9a-f]{64}$'),
CONSTRAINT attachments_error_consistency CHECK (
(status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending'
)
);
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
CREATE INDEX attachments_status_created_at_idx ON attachments (status, created_at);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
position smallint NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_check CHECK (position BETWEEN 0 AND 9),
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position)
);
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
-- Lab1-3 messages must stay valid. Attachment-only messages use text = '';
-- the "text OR attachment" rule is enforced by the service and ogen.
ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank;
-- +goose Down
-- WARNING: fails if attachment-only messages already exist. Roll back such
-- rows or the constraint cannot be restored.
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> '');
DROP TABLE message_attachments;
DROP TABLE attachments;
@@ -0,0 +1,82 @@
-- name: CreateAttachment :one
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
)
VALUES (
sqlc.arg(id),
sqlc.arg(chat_id),
sqlc.arg(owner_id),
sqlc.arg(object_key),
sqlc.arg(filename),
sqlc.arg(content_type),
sqlc.arg(size_bytes),
sqlc.arg(sha256),
'pending'
)
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at;
-- name: MarkAttachmentReady :one
UPDATE attachments
SET status = 'ready',
object_key = sqlc.arg(object_key),
updated_at = now()
WHERE id = sqlc.arg(id)
AND status = 'pending'
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at;
-- name: GetAttachmentForMember :one
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id
AND cm.user_id = sqlc.arg(user_id)
WHERE a.id = sqlc.arg(id);
-- name: GetAttachmentForOwner :one
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id
AND cm.user_id = a.owner_id
WHERE a.id = sqlc.arg(id)
AND a.owner_id = sqlc.arg(owner_id);
-- name: ListAttachmentStatesForChat :many
SELECT id, status
FROM attachments
WHERE chat_id = sqlc.arg(chat_id)
AND id = ANY(sqlc.arg(ids)::uuid[]);
-- name: AttachToMessage :exec
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES (sqlc.arg(message_id), sqlc.arg(attachment_id), sqlc.arg(position));
-- name: ListMessageAttachments :many
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
ORDER BY message_id, position;
-- name: DeletePendingAttachment :exec
DELETE FROM attachments
WHERE id = sqlc.arg(id)
AND status = 'pending';
-- name: ListStalePendingAttachments :many
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
FROM attachments
WHERE status = 'pending'
AND created_at < sqlc.arg(created_before)
ORDER BY created_at
LIMIT sqlc.arg(row_limit);
-- name: ListAttachmentKeys :many
SELECT id, object_key, status, created_at
FROM attachments
ORDER BY id
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
+45 -4
View File
@@ -17,10 +17,11 @@ type Store struct {
queryTimeout time.Duration
idempotencyTTL time.Duration
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
attachments *AttachmentRepository
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
@@ -65,6 +66,7 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
store.sessions = &SessionRepository{store: store}
store.attachments = &AttachmentRepository{store: store}
return store, nil
}
@@ -77,6 +79,8 @@ func (s *Store) Messages() *MessageRepository { return s.messages }
func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Attachments() *AttachmentRepository { return s.attachments }
func (s *Store) Ping(ctx context.Context) error {
if err := s.pool.Ping(ctx); err != nil {
return fmt.Errorf("ping database: %w", err)
@@ -87,6 +91,43 @@ func (s *Store) Ping(ctx context.Context) error {
func (s *Store) Close() { s.pool.Close() }
// sweepLockKey is a process-independent constant: every replica contends for the
// same PostgreSQL session lock, so only one sweeper runs at a time.
const sweepLockKey int64 = 0x4c414234 // "LAB4"
// AcquireSweepLock holds a session-level advisory lock on a dedicated
// connection. The returned release function must be called on that same
// connection before it is returned to the pool.
func (s *Store) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return nil, false, fmt.Errorf("acquire sweep connection: %w", err)
}
var acquired bool
if err := conn.QueryRow(ctx, "SELECT pg_try_advisory_lock($1)", sweepLockKey).Scan(&acquired); err != nil {
conn.Release()
return nil, false, fmt.Errorf("acquire sweep lock: %w", err)
}
if !acquired {
conn.Release()
return nil, false, nil
}
release := func() {
unlockCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", sweepLockKey)
conn.Release()
}
return release, true, nil
}
func (s *Store) timeout(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return context.WithCancel(ctx)