lab5: очередь RabbitMQ, outbox, worker, варианты, fault-injection
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type AttachmentRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAttachmentRepository(pool *pgxpool.Pool) *AttachmentRepository {
|
||||
return &AttachmentRepository{pool: pool}
|
||||
}
|
||||
|
||||
const attachmentColumns = `id, chat_id, owner_id, filename, object_key, status,
|
||||
COALESCE(content_type, ''), COALESCE(size_bytes, 0), COALESCE(sha256, ''), created_at, updated_at,
|
||||
COALESCE(error_code, ''), pipeline_version, COALESCE(staging_key, '')`
|
||||
|
||||
func scanAttachment(row pgx.Row) (*domain.Attachment, error) {
|
||||
var a domain.Attachment
|
||||
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.Status,
|
||||
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt,
|
||||
&a.ErrorCode, &a.PipelineVersion, &a.StagingKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// CreateIntent записывает намерение загрузки (status=uploading) ДО записи в S3.
|
||||
func (r *AttachmentRepository) CreateIntent(ctx context.Context, a *domain.Attachment) error {
|
||||
const q = `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, staging_key, status, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $5, 'uploading', $6, $6)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkQueued — точка 202. В ОДНОЙ транзакции: метаданные проверенного оригинала
|
||||
// и status=queued, логическое задание (jobs) и сообщение для broker (outbox).
|
||||
// После COMMIT работа не теряется: даже если broker недоступен или relay упал,
|
||||
// outbox будет опубликован позже. Если строки uploading уже нет — ErrNotFound.
|
||||
func (r *AttachmentRepository) MarkQueued(ctx context.Context, a *domain.Attachment, pipelineVersion, maxAttempts int) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', content_type = $2, size_bytes = $3, sha256 = $4, updated_at = $5
|
||||
WHERE id = $1::uuid AND status = 'uploading'
|
||||
`
|
||||
tag, err := tx.Exec(ctx, q, a.ID, a.ContentType, a.SizeBytes, a.SHA256, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("mark attachment queued: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
jobID, err := EnqueueJobTx(ctx, tx, a.ID, pipelineVersion, maxAttempts, "upload")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return jobID, nil
|
||||
}
|
||||
|
||||
// Variants — варианты указанной версии pipeline.
|
||||
func (r *AttachmentRepository) Variants(ctx context.Context, attachmentID string, version int) ([]domain.Variant, error) {
|
||||
const q = `
|
||||
SELECT name, content_type, size_bytes, width, height, sha256, object_key, pipeline_version
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1::uuid AND pipeline_version = $2
|
||||
ORDER BY CASE name WHEN 'thumbnail' THEN 1 WHEN 'crop' THEN 2 ELSE 3 END
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, attachmentID, version)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select variants: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []domain.Variant{}
|
||||
for rows.Next() {
|
||||
var v domain.Variant
|
||||
if err := rows.Scan(&v.Name, &v.ContentType, &v.SizeBytes, &v.Width, &v.Height, &v.SHA256, &v.ObjectKey, &v.PipelineVersion); err != nil {
|
||||
return nil, fmt.Errorf("scan variant: %w", err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteIntent убирает намерение, если загрузка не удалась (компенсация).
|
||||
func (r *AttachmentRepository) DeleteIntent(ctx context.Context, id string) error {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading'`
|
||||
if _, err := r.pool.Exec(ctx, q, id); err != nil {
|
||||
return fmt.Errorf("delete attachment intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetForMember возвращает вложение, если пользователь — участник его чата.
|
||||
// Чужое и несуществующее вложение неразличимы (ErrNotFound).
|
||||
func (r *AttachmentRepository) GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error) {
|
||||
q := `SELECT ` + attachmentColumns + `
|
||||
FROM attachments a
|
||||
WHERE a.id = $1::uuid
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2::uuid)`
|
||||
a, err := scanAttachment(r.pool.QueryRow(ctx, q, id, userID))
|
||||
if err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, fmt.Errorf("select attachment: %w", err)
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// --- для reconciler ---
|
||||
|
||||
// StreamByKey отдаёт все известные БД ключи объектов в байтовом порядке (как
|
||||
// ListObjectsV2): оригинал вложения (object_key), отдельный staging-объект и
|
||||
// объекты вариантов. Для staging и вариантов Status — «staging»/«variant», чтобы
|
||||
// reconciler не путал их с оригиналом.
|
||||
func (r *AttachmentRepository) StreamByKey(ctx context.Context, prefix string, fn func(*domain.Attachment) error) error {
|
||||
const q = `
|
||||
SELECT key, id::text, status, size_bytes, updated_at FROM (
|
||||
SELECT object_key AS key, id, status, COALESCE(size_bytes, 0) AS size_bytes, updated_at FROM attachments
|
||||
UNION ALL
|
||||
SELECT staging_key, id, 'staging', COALESCE(size_bytes, 0), updated_at FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND staging_key <> object_key
|
||||
UNION ALL
|
||||
SELECT object_key, attachment_id, 'variant', size_bytes, created_at FROM attachment_variants
|
||||
) k
|
||||
WHERE starts_with(key, $1)
|
||||
ORDER BY key COLLATE "C"`
|
||||
rows, err := r.pool.Query(ctx, q, prefix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stream object keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
if err := rows.Scan(&a.ObjectKey, &a.ID, &a.Status, &a.SizeBytes, &a.UpdatedAt); err != nil {
|
||||
return fmt.Errorf("scan object key: %w", err)
|
||||
}
|
||||
if err := fn(&a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
// HasKey — есть ли строка с этим object_key (повторная проверка перед удалением объекта).
|
||||
func (r *AttachmentRepository) HasKey(ctx context.Context, key string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1 OR staging_key = $1)
|
||||
OR EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// DeleteStaleIntent удаляет намерение, только если оно всё ещё uploading и старше cutoff.
|
||||
func (r *AttachmentRepository) DeleteStaleIntent(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'uploading' AND updated_at < $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, cutoff)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// SetStatus меняет статус ready↔missing (карантин и восстановление).
|
||||
func (r *AttachmentRepository) SetStatus(ctx context.Context, id, from, to string) (bool, error) {
|
||||
const q = `UPDATE attachments SET status = $3, updated_at = now() WHERE id = $1::uuid AND status = $2`
|
||||
tag, err := r.pool.Exec(ctx, q, id, from, to)
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// DeleteUnreferencedMissing удаляет запись карантина старше cutoff, если на неё
|
||||
// не ссылается ни одно сообщение. Блокировка строки (FOR UPDATE) конфликтует с
|
||||
// FOR SHARE при создании сообщения, поэтому гонки «удалили, пока прикрепляли» нет.
|
||||
func (r *AttachmentRepository) DeleteUnreferencedMissing(ctx context.Context, id string, cutoff time.Time) (bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT id FROM attachments WHERE id = $1::uuid AND status = 'missing' AND updated_at < $2 FOR UPDATE`, id, cutoff).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&referenced); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// IsReferenced — используется ли вложение каким-либо сообщением.
|
||||
func (r *AttachmentRepository) IsReferenced(ctx context.Context, id string) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid)`, id).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// TryLock — advisory lock, чтобы одновременно работал один reconciler.
|
||||
func (r *AttachmentRepository) TryLock(ctx context.Context) (func(), bool, error) {
|
||||
conn, err := r.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var ok bool
|
||||
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock(4242004)`).Scan(&ok); err != nil || !ok {
|
||||
conn.Release()
|
||||
return nil, false, err
|
||||
}
|
||||
return func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(4242004)`)
|
||||
conn.Release()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
const insertMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, insertMember, chat.ID, uid); err != nil {
|
||||
return fmt.Errorf("insert member %s: %w", uid, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
var c domain.Chat
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select chat: %w", err)
|
||||
}
|
||||
|
||||
const qMembers = `SELECT user_id FROM chat_members WHERE chat_id = $1::uuid ORDER BY user_id`
|
||||
rows, err := r.pool.Query(ctx, qMembers, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
c.MemberIDs = []string{}
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const q = `SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid`
|
||||
var one int
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&one)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
const qChat = `SELECT 1 FROM chats WHERE id = $1::uuid`
|
||||
err = r.pool.QueryRow(ctx, qChat, chatID).Scan(&one)
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, repository.ErrNotFound
|
||||
}
|
||||
return false, fmt.Errorf("check chat exists: %w", err)
|
||||
}
|
||||
|
||||
// MemberVersion одним запросом возвращает версию истории чата и признак членства.
|
||||
// Несуществующий чат — ErrNotFound.
|
||||
func (r *ChatRepository) MemberVersion(ctx context.Context, chatID, userID string) (int64, bool, error) {
|
||||
const q = `
|
||||
SELECT c.version,
|
||||
EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = $2::uuid)
|
||||
FROM chats c
|
||||
WHERE c.id = $1::uuid
|
||||
`
|
||||
var version int64
|
||||
var member bool
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&version, &member)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, false, repository.ErrNotFound
|
||||
}
|
||||
return 0, false, fmt.Errorf("select chat version: %w", err)
|
||||
}
|
||||
return version, member, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error) {
|
||||
const qChats = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, qChats, userID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := []*domain.Chat{}
|
||||
var chatIDs []string
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
c.MemberIDs = []string{}
|
||||
chats = append(chats, &c)
|
||||
chatIDs = append(chatIDs, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
if len(chats) == 0 {
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
const qMembers = `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[]) ORDER BY chat_id, user_id`
|
||||
memberRows, err := r.pool.Query(ctx, qMembers, chatIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list members: %w", err)
|
||||
}
|
||||
defer memberRows.Close()
|
||||
|
||||
byChat := make(map[string][]string)
|
||||
for memberRows.Next() {
|
||||
var chatID, uid string
|
||||
if err := memberRows.Scan(&chatID, &uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
byChat[chatID] = append(byChat[chatID], uid)
|
||||
}
|
||||
if err := memberRows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := byChat[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateIdempotent вставляет сообщение и ключ в одной транзакции.
|
||||
// Конкурентные запросы с одним ключом сериализуются уникальным индексом
|
||||
// idempotency_keys: второй INSERT ждёт завершения первой транзакции, после
|
||||
// COMMIT получает конфликт (DO NOTHING), откатывает своё сообщение и читает
|
||||
// уже сохранённое. Если первая транзакция откатилась (транзиентная ошибка),
|
||||
// вторая просто продолжает — неуспешный результат не фиксируется.
|
||||
func (r *MessageRepository) CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (*domain.Message, bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Ключ старше TTL больше не защищает от повтора — освобождаем его.
|
||||
const deleteExpired = `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND chat_id = $2::uuid AND key = $3
|
||||
AND created_at < now() - make_interval(secs => $4)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, deleteExpired, msg.SenderID, msg.ChatID, key, ttl.Seconds()); err != nil {
|
||||
return nil, false, fmt.Errorf("delete expired key: %w", err)
|
||||
}
|
||||
|
||||
const insertMsg = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := tx.Exec(ctx, insertMsg, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, false, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(msg.AttachmentIDs) > 0 {
|
||||
if err := attachToMessage(ctx, tx, msg); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
|
||||
const insertKey = `
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5::uuid)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
`
|
||||
tag, err := tx.Exec(ctx, insertKey, msg.SenderID, msg.ChatID, key, requestHash, msg.ID)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("insert idempotency key: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
// Версия истории растёт атомарно с сообщением: после COMMIT любое чтение
|
||||
// увидит новую версию и не попадёт в кэш, записанный до этого сообщения.
|
||||
const bumpVersion = `UPDATE chats SET version = version + 1 WHERE id = $1::uuid`
|
||||
if _, err := tx.Exec(ctx, bumpVersion, msg.ChatID); err != nil {
|
||||
return nil, false, fmt.Errorf("bump chat version: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, false, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return msg, true, nil
|
||||
}
|
||||
|
||||
// Ключ уже занят подтверждённой записью: наше сообщение не сохраняем.
|
||||
_ = tx.Rollback(ctx)
|
||||
|
||||
const selectStored = `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
` + attachmentIDsExpr + `
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1::uuid AND k.chat_id = $2::uuid AND k.key = $3
|
||||
`
|
||||
var storedHash string
|
||||
var m domain.Message
|
||||
err = r.pool.QueryRow(ctx, selectStored, msg.SenderID, msg.ChatID, key).
|
||||
Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("select stored message: %w", err)
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return nil, false, repository.ErrConflict
|
||||
}
|
||||
return &m, false, nil
|
||||
}
|
||||
|
||||
// DeleteExpiredKeys удаляет ключи старше TTL. Безопасно выполнять с любой реплики.
|
||||
func (r *MessageRepository) DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
const q = `DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`
|
||||
tag, err := r.pool.Exec(ctx, q, ttl.Seconds())
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete expired keys: %w", err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
|
||||
q := `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ` + attachmentIDsExpr + `
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1::uuid
|
||||
AND (m.created_at, m.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
msgs := []*domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
|
||||
return nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msgs = append(msgs, &m)
|
||||
}
|
||||
return msgs, rows.Err()
|
||||
}
|
||||
|
||||
// attachmentIDsExpr — id вложений сообщения m в порядке отправки (всегда массив).
|
||||
const attachmentIDsExpr = `ARRAY(SELECT ma.attachment_id::text FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id ORDER BY ma.position)`
|
||||
|
||||
// attachToMessage проверяет и привязывает вложения в транзакции сообщения.
|
||||
// FOR SHARE блокирует строки вложений до COMMIT: reconciler (FOR UPDATE) не
|
||||
// удалит вложение, которое сейчас прикрепляют. Вложение должно быть из того же
|
||||
// чата и в статусе ready; чужое, неизвестное и незавершённое — ErrNotFound.
|
||||
func attachToMessage(ctx context.Context, tx pgx.Tx, msg *domain.Message) error {
|
||||
const q = `
|
||||
SELECT id::text, status FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2::uuid
|
||||
FOR SHARE
|
||||
`
|
||||
rows, err := tx.Query(ctx, q, msg.AttachmentIDs, msg.ChatID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
status := map[string]string{}
|
||||
for rows.Next() {
|
||||
var id, st string
|
||||
if err := rows.Scan(&id, &st); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
status[id] = st
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("select attachments: %w", err)
|
||||
}
|
||||
for _, id := range msg.AttachmentIDs {
|
||||
switch status[id] {
|
||||
case domain.AttachmentReady, domain.AttachmentQueued, domain.AttachmentProcessing:
|
||||
// с lab5 можно ссылаться на ещё обрабатываемое вложение
|
||||
case domain.AttachmentFailed, domain.AttachmentMissing:
|
||||
return repository.ErrConflict
|
||||
default:
|
||||
return repository.ErrNotFound // чужое, неизвестное, не принятое (uploading)
|
||||
}
|
||||
}
|
||||
batch := &pgx.Batch{}
|
||||
for i, id := range msg.AttachmentIDs {
|
||||
batch.Queue(`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
msg.ID, id, i)
|
||||
}
|
||||
if err := tx.SendBatch(ctx, batch).Close(); err != nil {
|
||||
return fmt.Errorf("insert message attachments: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
// PipelineRepository — задания, outbox и фиксация результатов обработки.
|
||||
//
|
||||
// Все переходы job выполняются в транзакциях с блокировкой строки job (FOR UPDATE),
|
||||
// а фиксация результата защищена fencing-токеном (lease_owner + attempt): worker,
|
||||
// потерявший lease, не может опубликовать результат поверх новой попытки.
|
||||
type PipelineRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPipelineRepository(pool *pgxpool.Pool) *PipelineRepository {
|
||||
return &PipelineRepository{pool: pool}
|
||||
}
|
||||
|
||||
// JobRow — состояние логической работы.
|
||||
type JobRow struct {
|
||||
JobID string
|
||||
AttachmentID string
|
||||
PipelineVersion int
|
||||
State string
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
NextAttemptAt time.Time
|
||||
LeaseUntil *time.Time
|
||||
LeaseOwner string
|
||||
LastError string
|
||||
}
|
||||
|
||||
func jobPayload(jobID, attachmentID string, version, attempt int, created time.Time) ([]byte, error) {
|
||||
return json.Marshal(domain.Job{
|
||||
SchemaVersion: 1, JobID: jobID, Type: domain.JobType, AttachmentID: attachmentID,
|
||||
PipelineVersion: version, Attempt: attempt,
|
||||
CreatedAt: created.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
func event(ctx context.Context, tx pgx.Tx, jobID, ev, detail string) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO job_events (job_id, event, detail) VALUES ($1::uuid, $2, NULLIF($3, ''))`, jobID, ev, detail)
|
||||
return err
|
||||
}
|
||||
|
||||
func outboxTx(ctx context.Context, tx pgx.Tx, jobID, attachmentID string, version, attempt int, available time.Time) error {
|
||||
payload, err := jobPayload(jobID, attachmentID, version, attempt, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO outbox (job_id, payload, available_at) VALUES ($1::uuid, $2, $3)`, jobID, payload, available)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert outbox: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnqueueJobTx создаёт логическую работу (attachment, version) и её первое
|
||||
// сообщение в outbox. Если работа этой версии уже есть — ничего не создаёт и
|
||||
// возвращает существующий job_id (ключ эффекта не дублируется).
|
||||
func EnqueueJobTx(ctx context.Context, tx pgx.Tx, attachmentID string, version, maxAttempts int, reason string) (string, error) {
|
||||
jobID := uuid.NewString()
|
||||
var got string
|
||||
err := tx.QueryRow(ctx, `
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, state, max_attempts)
|
||||
VALUES ($1::uuid, $2::uuid, $3, 'queued', $4)
|
||||
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
|
||||
RETURNING job_id::text`, jobID, attachmentID, version, maxAttempts).Scan(&got)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = tx.QueryRow(ctx, `SELECT job_id::text FROM jobs WHERE attachment_id = $1::uuid AND pipeline_version = $2`,
|
||||
attachmentID, version).Scan(&got)
|
||||
return got, err
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("insert job: %w", err)
|
||||
}
|
||||
if err := outboxTx(ctx, tx, got, attachmentID, version, 1, time.Now()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return got, event(ctx, tx, got, "enqueued", reason)
|
||||
}
|
||||
|
||||
func lockJob(ctx context.Context, tx pgx.Tx, jobID string) (*JobRow, error) {
|
||||
var j JobRow
|
||||
var owner, lastErr *string
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT job_id::text, attachment_id::text, pipeline_version, state, attempt, max_attempts,
|
||||
next_attempt_at, lease_until, lease_owner, last_error
|
||||
FROM jobs WHERE job_id = $1::uuid FOR UPDATE`, jobID).
|
||||
Scan(&j.JobID, &j.AttachmentID, &j.PipelineVersion, &j.State, &j.Attempt, &j.MaxAttempts,
|
||||
&j.NextAttemptAt, &j.LeaseUntil, &owner, &lastErr)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lock job: %w", err)
|
||||
}
|
||||
if owner != nil {
|
||||
j.LeaseOwner = *owner
|
||||
}
|
||||
if lastErr != nil {
|
||||
j.LastError = *lastErr
|
||||
}
|
||||
return &j, nil
|
||||
}
|
||||
|
||||
// ClaimOutcome — решение worker по доставленному сообщению.
|
||||
type ClaimOutcome int
|
||||
|
||||
const (
|
||||
Claimed ClaimOutcome = iota // аренда получена — обрабатывать
|
||||
AlreadyDone // эффект уже опубликован — ack без работы
|
||||
Busy // валидная аренда у другого worker — ack (дубль)
|
||||
NotDue // ранняя доставка до next_attempt_at — ack, outbox доставит позже
|
||||
Terminal // failed / задания нет — ack
|
||||
ExhaustedNow // попытки исчерпаны при захвате — уже помечено failed
|
||||
)
|
||||
|
||||
// Claim захватывает работу: queued (и уже наступило next_attempt_at) или
|
||||
// processing с истёкшим lease. Номер попытки растёт при каждом захвате.
|
||||
func (r *PipelineRepository) Claim(ctx context.Context, jobID, owner string, lease time.Duration) (ClaimOutcome, *JobRow, *domain.Attachment, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return Terminal, nil, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
var now time.Time
|
||||
if err := tx.QueryRow(ctx, `SELECT now()`).Scan(&now); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
switch {
|
||||
case j.State == "done":
|
||||
return AlreadyDone, j, nil, nil
|
||||
case j.State == "failed":
|
||||
return Terminal, j, nil, nil
|
||||
case j.State == "processing" && j.LeaseUntil != nil && j.LeaseUntil.After(now):
|
||||
return Busy, j, nil, nil
|
||||
case j.State == "queued" && j.NextAttemptAt.After(now): // время relay и claim — одно (часы PostgreSQL)
|
||||
return NotDue, j, nil, nil
|
||||
}
|
||||
a, err := scanAttachment(tx.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id = $1::uuid FOR UPDATE`, j.AttachmentID))
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return Terminal, j, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
// Результат этой или более новой версии уже опубликован — повтор не нужен.
|
||||
if a.Status == domain.AttachmentReady && a.PipelineVersion >= j.PipelineVersion {
|
||||
if _, err := tx.Exec(ctx, `UPDATE jobs SET state = 'done', lease_until = NULL, updated_at = now() WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "noop_already_published", fmt.Sprintf("published_version=%d", a.PipelineVersion)); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
return AlreadyDone, j, a, tx.Commit(ctx)
|
||||
}
|
||||
takeover := j.State == "processing"
|
||||
j.Attempt++
|
||||
if j.Attempt > j.MaxAttempts {
|
||||
if err := failTx(ctx, tx, j, "retry_exhausted", "attempts exhausted at claim"); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
return ExhaustedNow, j, a, tx.Commit(ctx)
|
||||
}
|
||||
until := now.Add(lease)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'processing', attempt = $2, lease_until = $3, lease_owner = $4, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, jobID, j.Attempt, until, owner); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
if a.Status == domain.AttachmentQueued {
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = $1::uuid`, a.ID); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
}
|
||||
ev := "claimed"
|
||||
if takeover {
|
||||
ev = "claimed_after_lease_expiry"
|
||||
}
|
||||
if err := event(ctx, tx, jobID, ev, fmt.Sprintf("attempt=%d owner=%s", j.Attempt, owner)); err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
j.State, j.LeaseUntil, j.LeaseOwner = "processing", &until, owner
|
||||
return Claimed, j, a, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// ExtendLease продлевает аренду (heartbeat), пока worker действительно работает.
|
||||
// false — аренда потеряна (её забрал другой worker после истечения).
|
||||
func (r *PipelineRepository) ExtendLease(ctx context.Context, jobID, owner string, attempt int, lease time.Duration) (bool, error) {
|
||||
tag, err := r.pool.Exec(ctx, `
|
||||
UPDATE jobs SET lease_until = now() + make_interval(secs => $4), updated_at = now()
|
||||
WHERE job_id = $1::uuid AND state = 'processing' AND lease_owner = $2 AND attempt = $3`,
|
||||
jobID, owner, attempt, lease.Seconds())
|
||||
return tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// CompleteResult — что сделала фиксация.
|
||||
type CompleteResult struct {
|
||||
Applied bool // результат этой попытки зафиксирован
|
||||
Published bool // attachment переведён на эту версию
|
||||
LostLease bool // fencing: попытка уже не владеет job
|
||||
NewerPublished int // если опубликована более новая версия — её номер
|
||||
}
|
||||
|
||||
// Complete атомарно публикует результат: варианты (ON CONFLICT DO NOTHING по
|
||||
// ключу эффекта), attachment → ready на этой версии (только если опубликованная
|
||||
// версия меньше — старый результат не перезаписывает новый), job → done.
|
||||
func (r *PipelineRepository) Complete(ctx context.Context, jobID, owner string, attempt int, finalKey string, variants []domain.Variant) (CompleteResult, error) {
|
||||
var res CompleteResult
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if j.State != "processing" || j.LeaseOwner != owner || j.Attempt != attempt {
|
||||
res.LostLease = true
|
||||
return res, event(ctx, tx, jobID, "result_rejected_lost_lease", fmt.Sprintf("attempt=%d owner=%s", attempt, owner))
|
||||
}
|
||||
batch := &pgx.Batch{}
|
||||
for _, v := range variants {
|
||||
batch.Queue(`
|
||||
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING`,
|
||||
j.AttachmentID, j.PipelineVersion, v.Name, v.ObjectKey, v.ContentType, v.SizeBytes, v.Width, v.Height, v.SHA256)
|
||||
}
|
||||
if err := tx.SendBatch(ctx, batch).Close(); err != nil {
|
||||
return res, fmt.Errorf("insert variants: %w", err)
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', pipeline_version = $2, object_key = $3, error_code = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND pipeline_version < $2 AND status <> 'missing'`,
|
||||
j.AttachmentID, j.PipelineVersion, finalKey)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("publish attachment: %w", err)
|
||||
}
|
||||
res.Published = tag.RowsAffected() == 1
|
||||
if !res.Published {
|
||||
_ = tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id = $1::uuid`, j.AttachmentID).Scan(&res.NewerPublished)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE jobs SET state = 'done', lease_until = NULL, last_error = NULL, updated_at = now() WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return res, err
|
||||
}
|
||||
ev, detail := "done", fmt.Sprintf("attempt=%d", attempt)
|
||||
if !res.Published {
|
||||
ev, detail = "done_not_published_newer_exists", fmt.Sprintf("attempt=%d published_version=%d", attempt, res.NewerPublished)
|
||||
}
|
||||
if err := event(ctx, tx, jobID, ev, detail); err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Applied = true
|
||||
return res, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func failTx(ctx context.Context, tx pgx.Tx, j *JobRow, code, detail string) error {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'failed', lease_until = NULL, last_error = $2, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, j.JobID, code+": "+detail); err != nil {
|
||||
return err
|
||||
}
|
||||
// Ready-вложение (переобработка новой версии) не роняется в failed: старый
|
||||
// результат остаётся опубликованным.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now()
|
||||
WHERE id = $1::uuid AND status IN ('queued', 'processing')`, j.AttachmentID, code); err != nil {
|
||||
return err
|
||||
}
|
||||
return event(ctx, tx, j.JobID, "failed", code+": "+detail)
|
||||
}
|
||||
|
||||
// RetryOrFail: временная ошибка с оставшимися попытками → queued с backoff и
|
||||
// новым сообщением outbox (available_at в будущем); иначе → failed.
|
||||
func (r *PipelineRepository) RetryOrFail(ctx context.Context, jobID, owner string, attempt int, code, detail string, permanent bool, backoff time.Duration) (failed bool, err error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if j.State != "processing" || j.LeaseOwner != owner || j.Attempt != attempt {
|
||||
return false, event(ctx, tx, jobID, "error_ignored_lost_lease", code)
|
||||
}
|
||||
if permanent || j.Attempt >= j.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
if err := failTx(ctx, tx, j, code, detail); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
var next time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
UPDATE jobs SET state = 'queued', lease_until = NULL, lease_owner = NULL, last_error = $2,
|
||||
next_attempt_at = now() + make_interval(secs => $3), updated_at = now()
|
||||
WHERE job_id = $1::uuid RETURNING next_attempt_at`, jobID, code+": "+detail, backoff.Seconds()).Scan(&next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1::uuid AND status = 'processing'`, j.AttachmentID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, jobID, j.AttachmentID, j.PipelineVersion, j.Attempt+1, next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "retry_scheduled", fmt.Sprintf("%s; next_attempt=%d in %s", code, j.Attempt+1, backoff.Round(time.Millisecond))); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// SweepExpiredLeases возвращает в очередь работу, чей worker умер (lease истёк).
|
||||
func (r *PipelineRepository) SweepExpiredLeases(ctx context.Context) (int, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT job_id::text FROM jobs
|
||||
WHERE state = 'processing' AND lease_until < now()
|
||||
ORDER BY lease_until LIMIT 100 FOR UPDATE SKIP LOCKED`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
for _, id := range ids {
|
||||
j, err := lockJob(ctx, tx, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if j.Attempt >= j.MaxAttempts {
|
||||
if err := failTx(ctx, tx, j, "retry_exhausted", "lease expired on last attempt"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'queued', lease_until = NULL, lease_owner = NULL, next_attempt_at = now(),
|
||||
last_error = 'lease_expired', updated_at = now() WHERE job_id = $1::uuid`, id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1::uuid AND status = 'processing'`, j.AttachmentID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, id, j.AttachmentID, j.PipelineVersion, j.Attempt+1, time.Now()); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := event(ctx, tx, id, "lease_expired_requeued", fmt.Sprintf("owner=%s attempt=%d", j.LeaseOwner, j.Attempt)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return len(ids), tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// OutboxMessage — неопубликованное сообщение.
|
||||
type OutboxMessage struct {
|
||||
ID int64
|
||||
JobID string
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
// PublishDue публикует созревшие сообщения outbox. Строки блокируются
|
||||
// FOR UPDATE SKIP LOCKED (несколько relay не мешают друг другу); published_at
|
||||
// ставится только после publisher confirm. Падение между confirm и COMMIT даёт
|
||||
// повторную публикацию — это допустимо: consumer идемпотентен.
|
||||
func (r *PipelineRepository) PublishDue(ctx context.Context, limit int, publish func(context.Context, OutboxMessage) error, afterPublish func()) (int, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT id, job_id::text, payload FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED`, limit)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var msgs []OutboxMessage
|
||||
for rows.Next() {
|
||||
var m OutboxMessage
|
||||
if err := rows.Scan(&m.ID, &m.JobID, &m.Payload); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
rows.Close()
|
||||
sent := 0
|
||||
for _, m := range msgs {
|
||||
if err := publish(ctx, m); err != nil {
|
||||
_, _ = tx.Exec(ctx, `UPDATE outbox SET publish_attempts = publish_attempts + 1 WHERE id = $1`, m.ID)
|
||||
_ = tx.Commit(ctx)
|
||||
return sent, err
|
||||
}
|
||||
if afterPublish != nil {
|
||||
afterPublish() // точка внедрения сбоя «после confirm до COMMIT»
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE outbox SET published_at = now(), publish_attempts = publish_attempts + 1 WHERE id = $1`, m.ID); err != nil {
|
||||
return sent, err
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Replay — явный операторский повтор failed-работы (failed → queued) с аудитом.
|
||||
// Успешную работу повторить нельзя: «повторить» не означает исполнить дубль.
|
||||
func (r *PipelineRepository) Replay(ctx context.Context, attachmentID string, version int, actor string) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var jobID string
|
||||
if err := tx.QueryRow(ctx, `SELECT job_id::text FROM jobs WHERE attachment_id = $1::uuid AND pipeline_version = $2`,
|
||||
attachmentID, version).Scan(&jobID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
j, err := lockJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if j.State != "failed" {
|
||||
_ = event(ctx, tx, jobID, "replay_refused", "state="+j.State+" actor="+actor)
|
||||
_ = tx.Commit(ctx)
|
||||
return jobID, fmt.Errorf("%w: job is %s, only failed jobs can be replayed", repository.ErrConflict, j.State)
|
||||
}
|
||||
var staging *string
|
||||
if err := tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id = $1::uuid FOR UPDATE`, attachmentID).Scan(&staging); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if staging == nil {
|
||||
_ = event(ctx, tx, jobID, "replay_refused", "staging removed by retention, actor="+actor)
|
||||
_ = tx.Commit(ctx)
|
||||
return jobID, fmt.Errorf("%w: source removed by staging retention", repository.ErrConflict)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE jobs SET state = 'queued', attempt = 0, next_attempt_at = now(), last_error = NULL, updated_at = now()
|
||||
WHERE job_id = $1::uuid`, jobID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1::uuid AND status = 'failed'`, attachmentID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := outboxTx(ctx, tx, jobID, attachmentID, version, 1, time.Now()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := event(ctx, tx, jobID, "replay", "actor="+actor); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return jobID, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Reprocess ставит работу новой версии pipeline для уже обработанного вложения
|
||||
// (трек 2). Вложение остаётся ready со старыми вариантами до публикации новых.
|
||||
func (r *PipelineRepository) Reprocess(ctx context.Context, attachmentID string, version, maxAttempts int) (string, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
id, err := EnqueueJobTx(ctx, tx, attachmentID, version, maxAttempts, "reprocess")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// FailedJobs — реестр failed для оператора.
|
||||
func (r *PipelineRepository) FailedJobs(ctx context.Context, limit int) ([]JobRow, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT job_id::text, attachment_id::text, pipeline_version, state, attempt, max_attempts, COALESCE(last_error, '')
|
||||
FROM jobs WHERE state = 'failed' ORDER BY updated_at DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []JobRow
|
||||
for rows.Next() {
|
||||
var j JobRow
|
||||
if err := rows.Scan(&j.JobID, &j.AttachmentID, &j.PipelineVersion, &j.State, &j.Attempt, &j.MaxAttempts, &j.LastError); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, j)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// StagingCandidate — staging-объект, который можно удалить.
|
||||
type StagingCandidate struct {
|
||||
AttachmentID string
|
||||
Key string
|
||||
Status string
|
||||
}
|
||||
|
||||
// StagingToClean: ready с отдельным staging-объектом (результат уже опубликован
|
||||
// не менее readyGrace назад) и failed старше retention (replay больше невозможен).
|
||||
func (r *PipelineRepository) StagingToClean(ctx context.Context, readyGrace, failedRetention time.Duration, limit int) ([]StagingCandidate, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id::text, staging_key, status FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND (
|
||||
(status = 'ready' AND staging_key <> object_key AND updated_at < now() - make_interval(secs => $1))
|
||||
OR (status = 'failed' AND updated_at < now() - make_interval(secs => $2)))
|
||||
ORDER BY updated_at LIMIT $3`, readyGrace.Seconds(), failedRetention.Seconds(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StagingCandidate
|
||||
for rows.Next() {
|
||||
var c StagingCandidate
|
||||
if err := rows.Scan(&c.AttachmentID, &c.Key, &c.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ClearStaging отмечает, что staging-объект удалён (только если ключ не менялся).
|
||||
func (r *PipelineRepository) ClearStaging(ctx context.Context, attachmentID, key string) error {
|
||||
_, err := r.pool.Exec(ctx, `UPDATE attachments SET staging_key = NULL WHERE id = $1::uuid AND staging_key = $2`, attachmentID, key)
|
||||
return err
|
||||
}
|
||||
|
||||
// Attachment — доверенные метаданные для worker.
|
||||
func (r *PipelineRepository) Attachment(ctx context.Context, id string) (*domain.Attachment, error) {
|
||||
return scanAttachment(r.pool.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id = $1::uuid`, id))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool создаёт пул соединений с PostgreSQL.
|
||||
// Параметры ограничены, чтобы не перегрузить БД.
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = min(2, maxConns)
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
// Проверяем, что соединение работает.
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
|
||||
return &UserRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
return fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE id = $1::uuid`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `SELECT id, username, display_name, created_at FROM users WHERE username = $1`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by username: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
|
||||
const q = `SELECT password_hash FROM users WHERE id = $1::uuid`
|
||||
var hash string
|
||||
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", fmt.Errorf("select password hash: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
Reference in New Issue
Block a user