feat(outbox): lab5 run outbox background publisher in api server

This commit is contained in:
Голиков Maximillian Антон
2026-11-09 09:12:48 +03:00
parent af9e94080e
commit 872406773f
2 changed files with 87 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
package outbox
import (
"context"
"log"
"time"
"high-loud-apps-labs/internal/broker"
"high-loud-apps-labs/internal/domain"
)
type Publisher struct {
repo domain.OutboxRepository
broker broker.Publisher
batch int
}
func NewPublisher(repo domain.OutboxRepository, b broker.Publisher, batch int) *Publisher {
if batch <= 0 {
batch = 50
}
return &Publisher{repo: repo, broker: b, batch: batch}
}
func (p *Publisher) Run(ctx context.Context, interval time.Duration) {
if interval <= 0 {
interval = 1 * time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
log.Printf("outbox: publisher запущен (interval=%s)", interval)
for {
select {
case <-ctx.Done():
log.Println("outbox: publisher остановлен")
return
case <-ticker.C:
p.tick(ctx)
}
}
}
func (p *Publisher) tick(ctx context.Context) {
entries, err := p.repo.ClaimBatch(ctx, p.batch)
if err != nil {
log.Printf("outbox: ошибка ClaimBatch: %v", err)
return
}
if len(entries) == 0 {
return
}
var successIDs []string
for _, e := range entries {
err := p.broker.Publish(ctx, "process", e.Payload)
if err != nil {
log.Printf("outbox: ошибка публикации %s: %v", e.ID, err)
break // Прерываем пачку
}
successIDs = append(successIDs, e.ID)
}
if len(successIDs) > 0 {
if err := p.repo.MarkPublished(ctx, successIDs); err != nil {
log.Printf("outbox: ошибка MarkPublished: %v", err)
} else {
log.Printf("outbox: успешно опубликовано %d сообщений", len(successIDs))
}
}
}