lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
@@ -48,7 +49,7 @@ func (r *AttachmentRepository) Create(ctx context.Context, draft domain.Attachme
|
||||
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
return mapCreateAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) MarkReady(
|
||||
@@ -67,7 +68,7 @@ func (r *AttachmentRepository) MarkReady(
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
return mapMarkReadyAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
||||
@@ -96,7 +97,7 @@ func (r *AttachmentRepository) GetForMember(
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
return mapMemberAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetForOwner(
|
||||
@@ -114,7 +115,7 @@ func (r *AttachmentRepository) GetForOwner(
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
return mapOwnerAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListStates(
|
||||
@@ -160,7 +161,12 @@ func (r *AttachmentRepository) ListStalePending(
|
||||
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAll(rows, mapAttachment), nil
|
||||
stale := make([]domain.Attachment, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
stale = append(stale, mapStaleAttachment(row))
|
||||
}
|
||||
|
||||
return stale, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListKeys(
|
||||
@@ -191,23 +197,47 @@ func (r *AttachmentRepository) ListKeys(
|
||||
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),
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
if row.ErrorCode.Valid {
|
||||
code := row.ErrorCode.String
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const attachToMessage = `-- name: AttachToMessage :exec
|
||||
@@ -58,7 +59,22 @@ type CreateAttachmentParams struct {
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
|
||||
type CreateAttachmentRow 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
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (CreateAttachmentRow, error) {
|
||||
row := q.db.QueryRow(ctx, createAttachment,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
@@ -69,7 +85,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
)
|
||||
var i Attachment
|
||||
var i CreateAttachmentRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
@@ -113,9 +129,24 @@ type GetAttachmentForMemberParams struct {
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (Attachment, error) {
|
||||
type GetAttachmentForMemberRow 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
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (GetAttachmentForMemberRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForMember, arg.UserID, arg.ID)
|
||||
var i Attachment
|
||||
var i GetAttachmentForMemberRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
@@ -149,9 +180,24 @@ type GetAttachmentForOwnerParams struct {
|
||||
OwnerID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (Attachment, error) {
|
||||
type GetAttachmentForOwnerRow 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
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (GetAttachmentForOwnerRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForOwner, arg.ID, arg.OwnerID)
|
||||
var i Attachment
|
||||
var i GetAttachmentForOwnerRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
@@ -297,15 +343,30 @@ type ListStalePendingAttachmentsParams struct {
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]Attachment, error) {
|
||||
type ListStalePendingAttachmentsRow 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
|
||||
}
|
||||
|
||||
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]ListStalePendingAttachmentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listStalePendingAttachments, arg.CreatedBefore, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Attachment{}
|
||||
items := []ListStalePendingAttachmentsRow{}
|
||||
for rows.Next() {
|
||||
var i Attachment
|
||||
var i ListStalePendingAttachmentsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
@@ -346,9 +407,24 @@ type MarkAttachmentReadyParams struct {
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (Attachment, error) {
|
||||
type MarkAttachmentReadyRow 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
|
||||
}
|
||||
|
||||
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (MarkAttachmentReadyRow, error) {
|
||||
row := q.db.QueryRow(ctx, markAttachmentReady, arg.ObjectKey, arg.ID)
|
||||
var i Attachment
|
||||
var i MarkAttachmentReadyRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
|
||||
@@ -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'
|
||||
);
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'ready', 'failed')
|
||||
);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,135 @@
|
||||
//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)
|
||||
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)
|
||||
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)
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -22,6 +22,7 @@ type Store struct {
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
attachments *AttachmentRepository
|
||||
pipeline *PipelineRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
|
||||
@@ -67,6 +68,7 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
|
||||
store.messages = &MessageRepository{store: store}
|
||||
store.sessions = &SessionRepository{store: store}
|
||||
store.attachments = &AttachmentRepository{store: store}
|
||||
store.pipeline = &PipelineRepository{store: store}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
@@ -81,6 +83,8 @@ 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 {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
|
||||
Reference in New Issue
Block a user