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:
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user