lab5: исправления по ревью

Concurrent complete no longer deletes the shared verified source; admission is atomic and covers pending presign rows; relay reconciles queued jobs lost to dead-lettering; failed staging is protected until failed_retention; timestamps normalized to UTC; reprocess prefers the durable original and keeps job->attachment lock order; heartbeat errors no longer burn attempts; confirm timeout enforced; pinned images and sanitized health responses.
This commit is contained in:
Vladislav Kunetskiy
2026-10-30 23:13:44 +03:00
parent 4bdcac3dfa
commit 9d7a0acb5a
40 changed files with 592 additions and 521 deletions
+9 -2
View File
@@ -113,7 +113,7 @@ func declareTopology(channel *amqp.Channel, cfg Config) error {
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-delivery-limit": int32(8),
"x-delivery-limit": int32(100),
"x-delayed-retry-type": "all",
"x-delayed-retry-min": int32(5000),
"x-delayed-retry-max": int32(60000),
@@ -186,7 +186,14 @@ func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, messag
return fmt.Errorf("publish job: %w", err)
}
confirmed, err := confirmation.WaitContext(ctx)
confirmCtx := ctx
if c.cfg.ConfirmTimeout > 0 {
var cancel context.CancelFunc
confirmCtx, cancel = context.WithTimeout(ctx, c.cfg.ConfirmTimeout)
defer cancel()
}
confirmed, err := confirmation.WaitContext(confirmCtx)
if err != nil {
return fmt.Errorf("await publisher confirm: %w", err)
}
+1
View File
@@ -79,6 +79,7 @@ type Outbox struct {
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
ReconcileAfter time.Duration `mapstructure:"reconcile_after" validate:"omitempty,gt=0"`
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
}
+7
View File
@@ -107,6 +107,13 @@ type Attachment struct {
FailedAt *time.Time
}
// AdmissionLimits bounds accepted-but-unfinished work. Zero means unlimited.
type AdmissionLimits struct {
PerUser int
Total int
Bytes int64
}
// AttachmentDraft is a fully validated attachment awaiting persistence.
type AttachmentDraft struct {
ID uuid.UUID
+6 -1
View File
@@ -15,7 +15,12 @@ import (
// Enabled reports whether fault injection is explicitly switched on.
func Enabled() bool {
return os.Getenv("FAULTS_ENABLED") == "1"
if os.Getenv("FAULTS_ENABLED") != "1" {
return false
}
env := os.Getenv("APP_ENV")
return env == "" || env == "dev"
}
// Check exits the process if the action is armed for this job. It must be
+13
View File
@@ -17,6 +17,7 @@ type Repository interface {
ReleaseOutbox(ctx context.Context, id int64, reason string) error
ReapOutboxClaims(ctx context.Context) error
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int) (int, error)
PruneOutbox(ctx context.Context, retention time.Duration) error
OldestUnpublished(ctx context.Context) (time.Time, error)
}
@@ -31,6 +32,7 @@ type Config struct {
ClaimTTL time.Duration
Batch int
ReaperInterval time.Duration
ReconcileAfter time.Duration
Retention time.Duration
}
@@ -130,6 +132,17 @@ func (r *Relay) reap(ctx context.Context) {
r.log.InfoContext(ctx, "expired job leases requeued", slog.Int("count", reaped))
}
// The broker is not the source of truth. If a delivery was dead-lettered
// or lost, the queued job has no unpublished outbox row; republish it.
if r.config.ReconcileAfter > 0 {
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100)
if err != nil {
r.log.WarnContext(ctx, "queued-job reconciliation failed", slog.Any("error", err))
} else if reconciled > 0 {
r.log.InfoContext(ctx, "lost queued jobs reconciled", slog.Int("count", reconciled))
}
}
if r.config.Retention > 0 {
if err := r.repo.PruneOutbox(ctx, r.config.Retention); err != nil {
r.log.WarnContext(ctx, "outbox retention failed", slog.Any("error", err))
+36 -24
View File
@@ -229,8 +229,8 @@ func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context
}
// CreatePresign provides a mock function for the type MockRepository
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft)
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, limits)
if len(ret) == 0 {
panic("no return value specified for CreatePresign")
@@ -238,16 +238,16 @@ func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.Att
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) domain.Attachment); ok {
r0 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft) error); ok {
r1 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, limits)
} else {
r1 = ret.Error(1)
}
@@ -262,11 +262,12 @@ type MockRepository_CreatePresign_Call struct {
// CreatePresign is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any, limits any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft, limits)}
}
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits)) *MockRepository_CreatePresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -276,9 +277,14 @@ func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, d
if args[1] != nil {
arg1 = args[1].(domain.AttachmentDraft)
}
var arg2 domain.AdmissionLimits
if args[2] != nil {
arg2 = args[2].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
@@ -289,14 +295,14 @@ func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment
return _c
}
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
_c.Call.Return(run)
return _c
}
// CreateQueued provides a mock function for the type MockRepository
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job)
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job, limits)
if len(ret) == 0 {
panic("no return value specified for CreateQueued")
@@ -304,16 +310,16 @@ func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.Atta
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job) error); ok {
r1 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, job, limits)
} else {
r1 = ret.Error(1)
}
@@ -329,11 +335,12 @@ type MockRepository_CreateQueued_Call struct {
// - ctx context.Context
// - draft domain.AttachmentDraft
// - job domain.Job
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any, limits any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job, limits)}
}
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits)) *MockRepository_CreateQueued_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -347,10 +354,15 @@ func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, dr
if args[2] != nil {
arg2 = args[2].(domain.Job)
}
var arg3 domain.AdmissionLimits
if args[3] != nil {
arg3 = args[3].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
@@ -361,7 +373,7 @@ func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment,
return _c
}
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
_c.Call.Return(run)
return _c
}
+36 -5
View File
@@ -52,8 +52,13 @@ type Repository interface {
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
CompletePresign(
ctx context.Context,
ownerID, attachmentID uuid.UUID,
@@ -191,6 +196,8 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
CreatedAt: time.Now().UTC(),
}
limits := s.admissionLimits()
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
@@ -203,10 +210,16 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
SHA256: sum,
Status: domain.AttachmentQueued,
PipelineVersion: s.config.PipelineVersion,
}, job)
}, job, limits)
if err != nil {
s.deleteObject(ctx, id, stagingKey)
if errors.Is(err, domain.ErrRateLimited) {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, err
}
// An ambiguous COMMIT may have persisted the intent; leave the staging
// object for the sweeper instead of destroying a queued job's source.
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
@@ -357,7 +370,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
SHA256: request.SHA256,
Status: domain.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
}); err != nil {
}, s.admissionLimits()); err != nil {
return domain.PresignResult{}, err
}
@@ -511,7 +524,17 @@ func (s *Service) Complete(
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
s.deleteObject(ctx, id, verifiedKey)
// The verified key is shared by concurrent completions of this
// attachment. Never delete it here: a winning request may already have
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
if errors.Is(err, domain.ErrConflict) {
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
return s.withVariants(ctx, current)
}
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
}
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
@@ -530,6 +553,14 @@ func (s *Service) Complete(
// verifyStaging checks the freshly written object; a mismatch is a broken
// staging handoff and must never become a 202.
func (s *Service) admissionLimits() domain.AdmissionLimits {
return domain.AdmissionLimits{
PerUser: s.config.MaxPendingPerUser,
Total: s.config.MaxPending,
Bytes: s.config.MaxStagedBytes,
}
}
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
+84 -1
View File
@@ -189,7 +189,7 @@ func TestUploadStagesAndQueues(t *testing.T) {
}), mock.MatchedBy(func(job domain.Job) bool {
return job.PipelineVersion == 1 && job.Attempt == 1 &&
job.MaxAttempts == 5 && job.SourceKey != ""
})).Return(domain.Attachment{
}), domain.AdmissionLimits{}).Return(domain.Attachment{
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
@@ -355,6 +355,89 @@ func TestCompleteQueuesPresignedObject(t *testing.T) {
require.Len(t, store.objects, 1)
}
func TestCompleteConcurrentConflictKeepsVerifiedSource(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content, contentType: "image/png",
metadata: map[string]string{"sha256": digest},
}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
queued := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: "attachments/" + chatID.String() + "/" + id.String(),
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id, mock.Anything, mock.Anything,
1, 5, mock.Anything,
).Return(domain.Attachment{}, domain.ErrConflict).Once()
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(queued, nil).Once()
got, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
verified := 0
for key := range store.objects {
if strings.HasPrefix(key, "staging/verified/") {
verified++
}
}
require.Equal(t, 1, verified, "loser must not delete the winner's verified source")
}
func TestPresignHonoursAdmissionLimit(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().CreatePresign(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Presign(t.Context(), domain.PresignRequest{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("a", 64),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestUploadRateLimitedByAtomicAdmissionRemovesStaging(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
repo.EXPECT().CreateQueued(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
require.Empty(t, store.objects, "a rejected atomic admission must not leave staging")
}
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
@@ -1,245 +0,0 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"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 mapCreateAttachment(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 mapMarkReadyAttachment(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 mapMemberAttachment(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 mapOwnerAttachment(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))
}
stale := make([]domain.Attachment, 0, len(rows))
for _, row := range rows {
stale = append(stale, mapStaleAttachment(row))
}
return stale, 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 mapCreateAttachment(row sqlcgen.CreateAttachmentRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapMarkReadyAttachment(row sqlcgen.MarkAttachmentReadyRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapMemberAttachment(row sqlcgen.GetAttachmentForMemberRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapOwnerAttachment(row sqlcgen.GetAttachmentForOwnerRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapStaleAttachment(row sqlcgen.ListStalePendingAttachmentsRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func legacyAttachment(
id, chatID, ownerID uuid.UUID,
objectKey, filename, contentType string,
sizeBytes int64,
sha, status string,
errorCode pgtype.Text,
createdAt, updatedAt time.Time,
) domain.Attachment {
attachment := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: objectKey,
Filename: filename, ContentType: contentType, SizeBytes: sizeBytes,
SHA256: sha, Status: domain.AttachmentStatus(status),
PipelineVersion: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
}
if errorCode.Valid {
code := 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)
}
+148 -22
View File
@@ -64,6 +64,8 @@ func scanAttachmentRow(row rowScanner) (domain.Attachment, error) {
}
attachment.Status = domain.AttachmentStatus(status)
attachment.CreatedAt = toUTCTime(attachment.CreatedAt)
attachment.UpdatedAt = toUTCTime(attachment.UpdatedAt)
if errCode.Valid {
code := errCode.String
attachment.ErrorCode = &code
@@ -112,6 +114,9 @@ func scanJobRow(row rowScanner) (domain.Job, error) {
}
job.Status = domain.JobStatus(status)
job.AvailableAt = toUTCTime(job.AvailableAt)
job.CreatedAt = toUTCTime(job.CreatedAt)
job.UpdatedAt = toUTCTime(job.UpdatedAt)
if owner.Valid {
job.LeaseOwner = owner.String
}
@@ -330,12 +335,11 @@ func (r *PipelineRepository) Admission(
err = r.store.pool.QueryRow(ctx, `
SELECT
count(*) FILTER (WHERE a.owner_id = $1)::int,
count(*) FILTER (WHERE owner_id = $1)::int,
count(*)::int,
COALESCE(sum(a.size_bytes), 0)::bigint
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.status IN ('queued', 'processing')`, ownerID).Scan(
COALESCE(sum(size_bytes), 0)::bigint
FROM attachments
WHERE status IN ('pending', 'queued', 'processing')`, ownerID).Scan(
&userPending, &totalPending, &stagedBytes,
)
if err != nil {
@@ -394,10 +398,15 @@ func (r *PipelineRepository) CreateQueued(
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error) {
var created domain.Attachment
err := r.withTx(ctx, func(tx pgx.Tx) error {
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
return err
}
row := tx.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
@@ -1307,6 +1316,15 @@ func (r *PipelineRepository) Reprocess(
var created domain.Job
err := r.withTx(ctx, func(tx pgx.Tx) error {
// Keep the global lock order job -> attachment, as in CompleteJob.
if _, err := tx.Exec(ctx, `
SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
AND pipeline_version < $2
FOR UPDATE`, attachmentID, targetVersion); err != nil {
return fmt.Errorf("lock superseded jobs: %w", mapError(err))
}
attachmentRow := tx.QueryRow(ctx, `
SELECT `+attachmentReturning+`
FROM attachments WHERE id = $1 FOR UPDATE`, attachmentID)
@@ -1320,9 +1338,9 @@ func (r *PipelineRepository) Reprocess(
return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict)
}
sourceKey := attachment.StagingKey
sourceKey := attachment.ObjectKey
if sourceKey == "" {
sourceKey = attachment.ObjectKey
sourceKey = attachment.StagingKey
}
if sourceKey == "" {
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
@@ -1394,6 +1412,10 @@ func (r *PipelineRepository) ReplayJob(
jobID uuid.UUID,
extraAttempts int,
) (domain.Job, error) {
if extraAttempts < 1 {
return domain.Job{}, fmt.Errorf("%w: replay attempts must be >= 1", domain.ErrValidation)
}
var replayed domain.Job
err := r.withTx(ctx, func(tx pgx.Tx) error {
@@ -1629,7 +1651,7 @@ func (r *PipelineRepository) ListReferencedKeys(
SELECT object_key AS key FROM attachment_variants
UNION
SELECT staging_key AS key FROM attachments
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing')
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing', 'failed')
) referenced
WHERE key > $1
ORDER BY key
@@ -1776,30 +1798,89 @@ func (r *PipelineRepository) InsertRawOutbox(
func (r *PipelineRepository) CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var attachment domain.Attachment
row := r.store.pool.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, status, pipeline_version, staging_key
err := r.withTx(ctx, func(tx pgx.Tx) error {
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
return err
}
row := tx.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, status, pipeline_version, staging_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
RETURNING `+attachmentReturning,
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
draft.ContentType, draft.SizeBytes, draft.SHA256,
draft.PipelineVersion, draft.StagingKey,
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
RETURNING `+attachmentReturning,
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
draft.ContentType, draft.SizeBytes, draft.SHA256,
draft.PipelineVersion, draft.StagingKey,
)
attachment, err := scanAttachmentRow(row)
created, err := scanAttachmentRow(row)
if err != nil {
return fmt.Errorf("create presign attachment: %w", mapError(err))
}
attachment = created
return nil
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("create presign attachment: %w", mapError(err))
return domain.Attachment{}, err
}
return attachment, nil
}
const admissionLockKey int64 = 0x41444d31 // "ADM1"
// checkAdmissionTx serializes upload admission across API replicas with a
// transaction-scoped advisory lock, then re-counts pending/queued/processing
// rows. This closes the check-then-act window before the row is inserted.
func checkAdmissionTx(ctx context.Context, tx pgx.Tx, ownerID uuid.UUID, limits domain.AdmissionLimits) error {
if limits.PerUser == 0 && limits.Total == 0 && limits.Bytes == 0 {
return nil
}
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, admissionLockKey); err != nil {
return fmt.Errorf("lock admission: %w", mapError(err))
}
var (
total int
bytes int64
)
err := tx.QueryRow(ctx, `
SELECT count(*)::int, COALESCE(sum(size_bytes), 0)::bigint
FROM attachments
WHERE status IN ('pending', 'queued', 'processing')`).Scan(&total, &bytes)
if err != nil {
return fmt.Errorf("admission count: %w", mapError(err))
}
perUser := 0
if limits.PerUser > 0 {
if err := tx.QueryRow(ctx, `
SELECT count(*)::int FROM attachments
WHERE status IN ('pending', 'queued', 'processing')
AND owner_id = $1`, ownerID).Scan(&perUser); err != nil {
return fmt.Errorf("admission per-user count: %w", mapError(err))
}
}
if (limits.PerUser > 0 && perUser >= limits.PerUser) ||
(limits.Total > 0 && total >= limits.Total) ||
(limits.Bytes > 0 && bytes >= limits.Bytes) {
return fmt.Errorf("%w: admission limit reached", domain.ErrRateLimited)
}
return nil
}
// DuplicateJob publishes another copy of a specific job attempt. It is used by
// the fault-injection evidence to simulate duplicate delivery of an old version.
func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID) (domain.OutboxMessage, error) {
@@ -1832,3 +1913,48 @@ func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID)
return created, nil
}
// ReconcileQueuedJobs republishes jobs whose only broker delivery was lost
// (dead-lettered, dropped, or a broker data loss). The worker CAS makes an
// extra delivery a no-op. Only one unpublished outbox row is created per job.
func (r *PipelineRepository) ReconcileQueuedJobs(
ctx context.Context,
olderThan time.Duration,
limit int,
) (int, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
tag, err := r.store.pool.Exec(ctx, `
WITH lost AS (
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at
FROM attachment_jobs j
WHERE j.status = 'queued'
AND j.available_at < now() - $1::interval
AND NOT EXISTS (
SELECT 1 FROM outbox_messages o
WHERE o.job_id = j.job_id AND o.published_at IS NULL
)
ORDER BY j.available_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
INSERT INTO outbox_messages (job_id, attempt, kind, routing_key, payload, available_at)
SELECT job_id, attempt, 'reconcile', $3,
jsonb_build_object(
'schema_version', 1,
'job_id', job_id,
'type', $3::text,
'attachment_id', attachment_id,
'pipeline_version', pipeline_version,
'attempt', attempt,
'created_at', created_at),
now()
FROM lost`,
intervalString(olderThan), limit, defaultRoutingKey)
if err != nil {
return 0, fmt.Errorf("reconcile queued jobs: %w", mapError(err))
}
return int(tag.RowsAffected()), nil
}
@@ -64,7 +64,7 @@ func (s *PipelineSuite) TestCreateClaimCompleteAndIdempotentRedelivery() {
draft, job := s.attachmentDraft(chat, alice, 1)
repo := s.store.Pipeline()
created, err := repo.CreateQueued(s.T().Context(), draft, job)
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)
@@ -114,7 +114,7 @@ func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
job.MaxAttempts = 1
repo := s.store.Pipeline()
_, err := repo.CreateQueued(s.T().Context(), draft, job)
_, 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)
@@ -133,3 +133,74 @@ func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
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)
}
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)
}
+5 -9
View File
@@ -17,12 +17,11 @@ type Store struct {
queryTimeout time.Duration
idempotencyTTL time.Duration
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
attachments *AttachmentRepository
pipeline *PipelineRepository
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
pipeline *PipelineRepository
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
@@ -67,7 +66,6 @@ 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
@@ -81,8 +79,6 @@ 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 {
+8 -1
View File
@@ -225,7 +225,14 @@ func (w *Worker) process(
return
case <-ticker.C:
ok, err := w.repo.Heartbeat(jobCtx, job.ID, job.Attempt, w.config.Owner, w.config.LeaseTTL)
if err != nil || !ok {
if err != nil {
// A DB blip is not proof that the lease is gone. Keep trying;
// the fencing CAS still prevents a stale commit.
w.log.WarnContext(jobCtx, "heartbeat failed", slog.Any("error", err))
continue
}
if !ok {
leaseLost = true
cancel()