feat(storage): lab5 add outbox claim batch and mark published
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user