lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
This commit is contained in:
@@ -1,215 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//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)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -28,228 +27,6 @@ func (q *Queries) AttachToMessage(ctx context.Context, arg AttachToMessageParams
|
||||
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
|
||||
@@ -281,87 +58,3 @@ func (q *Queries) ListMessageAttachments(ctx context.Context, messageIds []uuid.
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -126,3 +126,32 @@ func (q *Queries) GetMessageIdempotency(ctx context.Context, arg GetMessageIdemp
|
||||
err := row.Scan(&i.MessageID, &i.RequestHash)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lookupMessageIdempotency = `-- name: LookupMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = $1
|
||||
AND chat_id = $2
|
||||
AND key = $3
|
||||
AND expires_at > now()
|
||||
`
|
||||
|
||||
type LookupMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type LookupMessageIdempotencyRow struct {
|
||||
MessageID pgtype.UUID
|
||||
RequestHash []byte
|
||||
}
|
||||
|
||||
// Read-only replay lookup used before attachment-state validation. A live key
|
||||
// returns the stored message; an expired key is ignored and may be claimed.
|
||||
func (q *Queries) LookupMessageIdempotency(ctx context.Context, arg LookupMessageIdempotencyParams) (LookupMessageIdempotencyRow, error) {
|
||||
row := q.db.QueryRow(ctx, lookupMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
|
||||
var i LookupMessageIdempotencyRow
|
||||
err := row.Scan(&i.MessageID, &i.RequestHash)
|
||||
return i, err
|
||||
}
|
||||
|
||||
@@ -12,18 +12,62 @@ import (
|
||||
)
|
||||
|
||||
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
|
||||
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
|
||||
PipelineVersion int32
|
||||
StagingKey pgtype.Text
|
||||
ReadyAt pgtype.Timestamptz
|
||||
FailedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJob struct {
|
||||
JobID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
SourceKey string
|
||||
Attempt int32
|
||||
MaxAttempts int32
|
||||
Status string
|
||||
AvailableAt time.Time
|
||||
LeaseOwner pgtype.Text
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
LastErrorCode pgtype.Text
|
||||
ReplayCount int32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CompletedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJobEvent struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Event string
|
||||
Attempt pgtype.Int4
|
||||
Detail []byte
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
Name string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int32
|
||||
Height int32
|
||||
Sha256 string
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
@@ -62,6 +106,22 @@ type MessageIdempotency struct {
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type OutboxMessage struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Attempt int32
|
||||
Kind string
|
||||
RoutingKey string
|
||||
Payload []byte
|
||||
AvailableAt time.Time
|
||||
PublishedAt pgtype.Timestamptz
|
||||
ClaimedBy pgtype.Text
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
PublishAttempts int32
|
||||
LastError pgtype.Text
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
|
||||
@@ -56,6 +56,61 @@ func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraf
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// Replay returns the stored message for a live Idempotency-Key without
|
||||
// touching attachment state. The caller uses it before attachment validation so
|
||||
// a replay stays 201 even if a linked attachment later failed.
|
||||
func (r *MessageRepository) Replay(
|
||||
ctx context.Context,
|
||||
draft domain.MessageDraft,
|
||||
) (domain.Message, bool, error) {
|
||||
var (
|
||||
replayed domain.Message
|
||||
found bool
|
||||
)
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
stored, err := queries.LookupMessageIdempotency(ctx, sqlcgen.LookupMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
replayed = mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, false, fmt.Errorf("replay idempotent message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return replayed, found, nil
|
||||
}
|
||||
|
||||
// createIdempotent stores the message and its Idempotency-Key in one
|
||||
// transaction: either both are committed or neither, so a replay never observes
|
||||
// a claimed key whose message is missing. Claiming is a single statement, so
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
-- +goose Up
|
||||
-- Lab5 async attachment pipeline: durable intent (jobs + transactional outbox),
|
||||
-- per-version results (variants), and operator audit (events).
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'queued', 'processing', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_status_check;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status IN ('ready', 'queued', 'processing') AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_error_consistency;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1
|
||||
CHECK (pipeline_version >= 1),
|
||||
ADD COLUMN staging_key text,
|
||||
ADD COLUMN ready_at timestamptz,
|
||||
ADD COLUMN failed_at timestamptz;
|
||||
|
||||
CREATE UNIQUE INDEX attachments_staging_key_key
|
||||
ON attachments (staging_key)
|
||||
WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE INDEX attachments_pipeline_status_idx
|
||||
ON attachments (status, pipeline_version);
|
||||
|
||||
-- One logical job per (attachment, pipeline version). job_id is stable across
|
||||
-- redelivery; attempt is the managed attempt number (1-based).
|
||||
CREATE TABLE attachment_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
source_key text NOT NULL,
|
||||
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
||||
max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 100),
|
||||
status text NOT NULL CHECK (
|
||||
status IN ('queued', 'processing', 'ready', 'failed', 'superseded')
|
||||
),
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
lease_owner text,
|
||||
lease_expires_at timestamptz,
|
||||
last_error_code text,
|
||||
replay_count integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
completed_at timestamptz,
|
||||
|
||||
CONSTRAINT attachment_jobs_attachment_version_key UNIQUE (attachment_id, pipeline_version),
|
||||
CONSTRAINT attachment_jobs_lease_consistency CHECK (
|
||||
(status = 'processing' AND lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL) OR
|
||||
(status <> 'processing')
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_jobs_due_idx
|
||||
ON attachment_jobs (status, available_at);
|
||||
|
||||
CREATE INDEX attachment_jobs_lease_idx
|
||||
ON attachment_jobs (status, lease_expires_at);
|
||||
|
||||
-- Delivery ledger. available_at is the only retry scheduler; RabbitMQ is the
|
||||
-- durable transport. No UNIQUE(job_id, attempt): a graceful shutdown may
|
||||
-- re-publish the same attempt, and duplicates are harmless (worker CAS).
|
||||
CREATE TABLE outbox_messages (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
attempt integer NOT NULL CHECK (attempt >= 1),
|
||||
kind text NOT NULL DEFAULT 'publish',
|
||||
routing_key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz,
|
||||
claimed_by text,
|
||||
claimed_until timestamptz,
|
||||
publish_attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_due_idx
|
||||
ON outbox_messages (available_at, id)
|
||||
WHERE published_at IS NULL;
|
||||
|
||||
CREATE INDEX outbox_claim_expiry_idx
|
||||
ON outbox_messages (claimed_until)
|
||||
WHERE published_at IS NULL AND claimed_by IS NOT NULL;
|
||||
|
||||
-- Effect key (attachment_id, pipeline_version, name). The primary key is the
|
||||
-- idempotency boundary for redelivery and versioned pipelines.
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
content_type text NOT NULL CHECK (
|
||||
content_type IN ('image/jpeg', 'image/png', 'image/webp')
|
||||
),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_job_events (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
event text NOT NULL,
|
||||
attempt integer,
|
||||
detail jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_job_events_job_idx
|
||||
ON attachment_job_events (job_id, created_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE attachment_job_events;
|
||||
DROP TABLE attachment_variants;
|
||||
DROP TABLE outbox_messages;
|
||||
DROP TABLE attachment_jobs;
|
||||
|
||||
DROP INDEX attachments_pipeline_status_idx;
|
||||
DROP INDEX attachments_staging_key_key;
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP COLUMN failed_at,
|
||||
DROP COLUMN ready_at,
|
||||
DROP COLUMN staging_key,
|
||||
DROP COLUMN pipeline_version;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status = 'ready' AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,552 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type PipelineSuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestPipelineSuite(t *testing.T) {
|
||||
suite.Run(t, new(PipelineSuite))
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) attachmentDraft(chat domain.Chat, owner domain.User, version int) (domain.AttachmentDraft, domain.Job) {
|
||||
s.T().Helper()
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
jobID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
draft := domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: chat.ID,
|
||||
OwnerID: owner.ID,
|
||||
ObjectKey: domain.OriginalObjectKey(chat.ID, id),
|
||||
StagingKey: domain.StagingUploadKey(chat.ID, id),
|
||||
Filename: "photo.png",
|
||||
ContentType: "image/png",
|
||||
SizeBytes: 10,
|
||||
SHA256: strings.Repeat("a", 64),
|
||||
Status: domain.AttachmentQueued,
|
||||
PipelineVersion: version,
|
||||
}
|
||||
|
||||
job := domain.Job{
|
||||
ID: jobID,
|
||||
AttachmentID: id,
|
||||
PipelineVersion: version,
|
||||
SourceKey: draft.StagingKey,
|
||||
Attempt: 1,
|
||||
MaxAttempts: 5,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return draft, job
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestCreateClaimCompleteAndIdempotentRedelivery() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
created, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentQueued, created.Status)
|
||||
s.Equal(1, created.PipelineVersion)
|
||||
|
||||
message := domain.NewJobMessage(job)
|
||||
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
s.Equal(domain.AttachmentProcessing, claim.Attachment.Status)
|
||||
|
||||
duplicate, err := repo.ClaimJob(s.T().Context(), message, "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimBusyLease, duplicate.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
ready, err := repo.GetForMember(s.T().Context(), bob.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, ready.Status)
|
||||
|
||||
stored, err := repo.ListVariants(s.T().Context(), draft.ID, 1)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(stored, 1)
|
||||
s.Equal(domain.VariantThumbnail, stored[0].Name)
|
||||
|
||||
// A redelivery after ready is a no-op, even with the same attempt.
|
||||
again, err := repo.ClaimJob(s.T().Context(), message, "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAlreadyReady, again.Outcome)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
job.MaxAttempts = 1
|
||||
|
||||
repo := s.store.Pipeline()
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Millisecond)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
reaped, err := repo.ReapExpiredLeases(s.T().Context(), 10)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, reaped)
|
||||
|
||||
dead, err := repo.GetJob(s.T().Context(), job.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.JobFailed, dead.Status)
|
||||
s.NotNil(dead.LastErrorCode)
|
||||
s.Equal("retry_exhausted", *dead.LastErrorCode)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestAdmissionCountsPendingPresignAndIsAtomic() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, _ := s.attachmentDraft(chat, alice, 1)
|
||||
draft.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + draft.ID.String()
|
||||
draft.StagingKey = draft.ObjectKey
|
||||
draft.Status = domain.AttachmentPending
|
||||
|
||||
limits := domain.AdmissionLimits{PerUser: 1, Total: 10}
|
||||
|
||||
_, err := repo.CreatePresign(s.T().Context(), draft, limits)
|
||||
s.Require().NoError(err)
|
||||
|
||||
second, _ := s.attachmentDraft(chat, alice, 1)
|
||||
second.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + second.ID.String()
|
||||
second.StagingKey = second.ObjectKey
|
||||
second.Status = domain.AttachmentPending
|
||||
|
||||
_, err = repo.CreatePresign(s.T().Context(), second, limits)
|
||||
s.Require().ErrorIs(err, domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
// A queued upload whose worker never ran still has its verified bytes only in
|
||||
// staging. Reprocessing it must use staging as the source; pointing at the
|
||||
// not-yet-written final original left the attachment queued forever after the
|
||||
// v1 job was superseded (v2 then failed with source_missing).
|
||||
func (s *PipelineSuite) TestReprocessQueuedUsesStagingSource() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, created.PipelineVersion)
|
||||
s.Equal(draft.StagingKey, created.SourceKey)
|
||||
}
|
||||
|
||||
// Once a pipeline has published the final original, the staging copy may be
|
||||
// past its retention window; a reprocess of a ready attachment must source
|
||||
// from the final object that actually exists.
|
||||
func (s *PipelineSuite) TestReprocessReadyUsesObjectSource() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
message := domain.NewJobMessage(job)
|
||||
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, created.PipelineVersion)
|
||||
s.Equal(draft.ObjectKey, created.SourceKey)
|
||||
}
|
||||
|
||||
// A reprocess failure before any version was published must settle the
|
||||
// attachment as failed instead of leaving it queued with no active jobs.
|
||||
func (s *PipelineSuite) TestReprocessFailureSettlesUnpublishedAttachment() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentFailed, current.Status)
|
||||
s.Require().NotNil(current.ErrorCode)
|
||||
s.Equal("invalid_image", *current.ErrorCode)
|
||||
}
|
||||
|
||||
// A reprocess failure while an older ready version is serving must keep that
|
||||
// version ready and downloadable; only the new job fails.
|
||||
func (s *PipelineSuite) TestReprocessFailureKeepsReadyServingVersion() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(1, current.PipelineVersion)
|
||||
s.Nil(current.ErrorCode)
|
||||
}
|
||||
|
||||
// Replaying a failed newer version must clear the stale terminal projection
|
||||
// for an attachment that never published any version.
|
||||
func (s *PipelineSuite) TestReplayNewerFailedVersionRequeuesUnpublishedAttachment() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentFailed, current.Status)
|
||||
|
||||
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, replayed.Attempt)
|
||||
|
||||
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentQueued, current.Status)
|
||||
s.Nil(current.ErrorCode)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(replayed), "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("c", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), replayed.ID, replayed.Attempt, "lease-3", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(2, current.PipelineVersion)
|
||||
}
|
||||
|
||||
// Replaying a failed newer version must not disturb a published ready
|
||||
// serving version; only the new job returns to queued.
|
||||
func (s *PipelineSuite) TestReplayNewerFailedVersionKeepsReadyServingVersion() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 1)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, replayed.Attempt)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(1, current.PipelineVersion)
|
||||
s.Nil(current.ErrorCode)
|
||||
}
|
||||
|
||||
// Replaying an older failed version is refused while a newer job exists,
|
||||
// even before that newer version becomes the published serving version.
|
||||
func (s *PipelineSuite) TestReplayOlderFailedVersionRefusedWhenNewerJobExists() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease-1", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = repo.ReplayJob(s.T().Context(), job.ID, 1)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
|
||||
var v1Status string
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&v1Status))
|
||||
s.Equal(string(domain.JobFailed), v1Status)
|
||||
}
|
||||
|
||||
// A queued job for an older version is retired on claim instead of being
|
||||
// acknowledged and republished by reconciliation forever.
|
||||
func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("d", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), reprocess.ID, 1, "lease-2", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
// Simulate a legacy/racing replay that left the old version queued.
|
||||
_, err = s.pool.Exec(s.T().Context(), `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = 1, last_error_code = NULL
|
||||
WHERE job_id = $1`, job.ID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
stale, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimVersionStale, stale.Outcome)
|
||||
|
||||
var status string
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status))
|
||||
s.Equal(string(domain.JobSuperseded), status)
|
||||
|
||||
var supersededEvents int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), `
|
||||
SELECT count(*) FROM attachment_job_events
|
||||
WHERE job_id = $1 AND event = $2`,
|
||||
job.ID, string(domain.EventSuperseded)).Scan(&supersededEvents))
|
||||
s.Equal(2, supersededEvents)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(claimed, 1)
|
||||
s.Require().NoError(repo.MarkPublished(s.T().Context(), []int64{claimed[0].ID}))
|
||||
|
||||
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, reconciled)
|
||||
|
||||
pending, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(pending, 1)
|
||||
s.Equal("reconcile", pending[0].Kind)
|
||||
s.Equal(job.ID, pending[0].JobID)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestFailedStagingStaysReferencedUntilRetention() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
ok, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
keys, err := repo.ListReferencedKeys(s.T().Context(), "", 100)
|
||||
s.Require().NoError(err)
|
||||
s.Contains(keys, draft.StagingKey)
|
||||
}
|
||||
@@ -1,56 +1,3 @@
|
||||
-- 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));
|
||||
@@ -60,23 +7,3 @@ 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);
|
||||
|
||||
@@ -38,3 +38,13 @@ WHERE actor_id = sqlc.arg(actor_id)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- Read-only replay lookup used before attachment-state validation. A live key
|
||||
-- returns the stored message; an expired key is ignored and may be claimed.
|
||||
-- name: LookupMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key)
|
||||
AND expires_at > now();
|
||||
|
||||
@@ -17,11 +17,11 @@ type Store struct {
|
||||
queryTimeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
attachments *AttachmentRepository
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
pipeline *PipelineRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
|
||||
@@ -66,7 +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}
|
||||
store.pipeline = &PipelineRepository{store: store}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
@@ -79,7 +79,7 @@ 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) Pipeline() *PipelineRepository { return s.pipeline }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user