forked from mtusi2026/mtusi2026lab6
53 lines
2.4 KiB
Go
53 lines
2.4 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"time"
|
|
)
|
|
|
|
type OutboxRepo struct{ Pool *pgxpool.Pool }
|
|
|
|
func (r *OutboxRepo) CreateTx(ctx context.Context, tx pgx.Tx, q outbox.CreateMessageReq) (outbox.CreateMessageRes, error) {
|
|
_, e := tx.Exec(ctx, `INSERT INTO outbox(id,job_id,payload,status,max_attempts,token,next_attempt_at,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$7,$7)`, q.ID, q.AggregateID, q.Payload, q.Status, q.MaxAttempts, uuid.New(), q.CreatedAt)
|
|
return outbox.CreateMessageRes{ID: q.ID, CreatedAt: q.CreatedAt}, e
|
|
}
|
|
func scanOutbox(rows pgx.Rows) (out []outbox.AcquiredMessage, err error) {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var m outbox.AcquiredMessage
|
|
if err = rows.Scan(&m.ID, &m.AggregateID, &m.Payload, &m.Attempts, &m.MaxAttempts, &m.Token); err != nil {
|
|
return
|
|
}
|
|
out = append(out, m)
|
|
}
|
|
err = rows.Err()
|
|
return
|
|
}
|
|
func (r *OutboxRepo) AcquireManyForProcessing(ctx context.Context, q outbox.AcquireMessagesForProcessingReq) ([]outbox.AcquiredMessage, error) {
|
|
rows, e := r.Pool.Query(ctx, `WITH picked AS (SELECT id FROM outbox WHERE status IN ('pending','failed') AND next_attempt_at<=clock_timestamp() ORDER BY next_attempt_at,id LIMIT $1 FOR UPDATE SKIP LOCKED)
|
|
UPDATE outbox o SET status='processing',attempts=attempts+1,token=$2,locked_until=clock_timestamp()+$3::interval,updated_at=clock_timestamp() FROM picked p WHERE o.id=p.id RETURNING o.id,o.job_id,o.payload,o.attempts,o.max_attempts,o.token`, q.Limit, uuid.New(), q.LockDuration.String())
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
return scanOutbox(rows)
|
|
}
|
|
func (r *OutboxRepo) Expired(ctx context.Context) ([]outbox.AcquiredMessage, error) {
|
|
rows, e := r.Pool.Query(ctx, `SELECT id,job_id,payload,attempts,max_attempts,token FROM outbox WHERE status='processing' AND locked_until<clock_timestamp() LIMIT 100`)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
return scanOutbox(rows)
|
|
}
|
|
func (r *OutboxRepo) Update(ctx context.Context, m outbox.AcquiredMessage, status outbox.Status, next time.Time, code string) error {
|
|
tag, e := r.Pool.Exec(ctx, `UPDATE outbox SET status=$3,next_attempt_at=$4,last_error=NULLIF($5,''),locked_until=NULL,updated_at=clock_timestamp() WHERE id=$1 AND token=$2 AND status='processing'`, m.ID, m.Token, status, next, code)
|
|
if e == nil && tag.RowsAffected() != 1 {
|
|
return errors.New("outbox lease lost")
|
|
}
|
|
return e
|
|
}
|