Files
mtusi2026lab5/internal/outbox/publisher.go
T

120 lines
2.4 KiB
Go

package outbox
import (
"context"
"encoding/json"
"log/slog"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/model"
"mtusi2026-messenger/internal/rabbitmq"
)
const (
pollInterval = time.Second
retryInterval = 2 * time.Second
publishTimeout = 5 * time.Second
)
type Publisher struct {
pool *pgxpool.Pool
url string
log *slog.Logger
}
func NewPublisher(pool *pgxpool.Pool, url string, log *slog.Logger) *Publisher {
return &Publisher{
pool: pool,
url: url,
log: log,
}
}
func (p *Publisher) Run(ctx context.Context) {
for ctx.Err() == nil {
client, err := rabbitmq.New(p.url)
if err == nil {
p.log.Info("outbox publisher connected")
err = p.publish(ctx, client)
_ = client.Close()
}
if ctx.Err() != nil {
return
}
p.log.Error("outbox publisher retry", "error", err)
if !wait(ctx, retryInterval) {
return
}
}
}
func (p *Publisher) publish(ctx context.Context, client *rabbitmq.Client) error {
for ctx.Err() == nil {
published, err := p.publishOne(ctx, client)
if err != nil {
return err
}
if !published && !wait(ctx, pollInterval) {
return ctx.Err()
}
}
return ctx.Err()
}
func (p *Publisher) publishOne(ctx context.Context, client *rabbitmq.Client) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, publishTimeout)
defer cancel()
tx, err := p.pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx)
q := db.New(tx)
rows, err := q.LockPendingOutboxEntries(ctx, 1)
if err != nil {
return false, err
}
if len(rows) == 0 {
return false, nil
}
row := rows[0]
body, err := json.Marshal(model.AttachmentJob{
SchemaVersion: 1,
JobID: row.JobID,
Type: "attachment.process.v1",
AttachmentID: row.AttachmentID,
PipelineVersion: row.PipelineVersion,
Attempt: row.Attempt,
CreatedAt: row.CreatedAt.UTC(),
})
if err != nil {
return false, err
}
if err := client.Publish(ctx, row.JobID.String(), body); err != nil {
return false, err
}
if _, err := q.MarkOutboxPublished(ctx, row.ID); err != nil {
return false, err
}
if err := tx.Commit(ctx); err != nil {
return false, err
}
return true, nil
}
func wait(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}