diff --git a/backend/internal/domain/repository.go b/backend/internal/domain/repository.go index 3343e20..7caba8a 100644 --- a/backend/internal/domain/repository.go +++ b/backend/internal/domain/repository.go @@ -49,4 +49,6 @@ type AttachmentRepository interface { type OutboxRepository interface { Enqueue(ctx context.Context, tx Tx, e *OutboxEntry) error + ClaimBatch(ctx context.Context, limit int) ([]OutboxEntry, error) + MarkPublished(ctx context.Context, ids []string) error } diff --git a/backend/internal/storage/postgres/outbox.go b/backend/internal/storage/postgres/outbox.go index 7d666e0..af78d77 100644 --- a/backend/internal/storage/postgres/outbox.go +++ b/backend/internal/storage/postgres/outbox.go @@ -53,4 +53,48 @@ func (r *OutboxRepo) Enqueue(ctx context.Context, tx domain.Tx, e *domain.Outbox return nil } +func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.OutboxEntry, error) { + const q = ` + WITH claimed AS ( + SELECT id FROM outbox + WHERE published_at IS NULL + ORDER BY created_at + LIMIT $1 + FOR UPDATE SKIP LOCKED + ) + UPDATE outbox o + SET attempts = attempts + 1 + FROM claimed c + WHERE o.id = c.id + RETURNING o.id, o.aggregate_type, o.aggregate_id, o.event_type, o.payload, o.attempts, o.created_at, o.published_at + ` + rows, err := r.pool.Query(ctx, q, limit) + if err != nil { + return nil, mapError(err) + } + defer rows.Close() + + var entries []domain.OutboxEntry + for rows.Next() { + var e domain.OutboxEntry + if err := rows.Scan( + &e.ID, &e.AggregateType, &e.AggregateID, &e.EventType, + &e.Payload, &e.Attempts, &e.CreatedAt, &e.PublishedAt, + ); err != nil { + return nil, mapError(err) + } + entries = append(entries, e) + } + return entries, mapError(rows.Err()) +} + +func (r *OutboxRepo) MarkPublished(ctx context.Context, ids []string) error { + if len(ids) == 0 { + return nil + } + const q = `UPDATE outbox SET published_at = now() WHERE id = ANY($1::uuid[])` + _, err := r.pool.Exec(ctx, q, ids) + return mapError(err) +} + var _ domain.OutboxRepository = (*OutboxRepo)(nil)