Files
mtusi2026lab5/app/internal/pipeline/pipeline.go
T

92 lines
2.3 KiB
Go

package pipeline
import (
"context"
"encoding/json"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"os"
"time"
)
const Pending = "attachments:pending"
const Active = "attachments:active"
type Job struct {
SchemaVersion int `json:"schema_version"`
JobID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
func Client() *redis.Client {
addr := os.Getenv("BROKER_ADDR")
if addr == "" {
addr = "broker:6379"
}
return redis.NewClient(&redis.Options{Addr: addr})
}
func Publish(ctx context.Context, id string, attempt int, created time.Time) error {
c := Client()
defer c.Close()
b, err := json.Marshal(Job{1, id, "attachment.process.v1", id, 1, attempt, created.UTC()})
if err != nil {
return err
}
return c.LPush(ctx, Pending, string(b)).Err()
}
// Dispatch republishes unfinished intentions. Duplicate messages are expected.
func Dispatch(ctx context.Context, p *pgxpool.Pool) {
for ctx.Err() == nil {
func() {
tx, err := p.Begin(ctx)
if err != nil {
return
}
defer tx.Rollback(ctx)
rows, err := tx.Query(ctx, `SELECT o.attachment_id::text,a.attempts+1,a.created_at FROM attachment_outbox o JOIN attachments a ON a.id=o.attachment_id
WHERE o.next_publish_at<=now() AND ((a.status='queued' AND a.next_attempt_at<=now()) OR (a.status='processing' AND a.lease_until<now()))
ORDER BY o.next_publish_at LIMIT 16 FOR UPDATE OF o SKIP LOCKED`)
if err != nil {
return
}
type intent struct {
id string
attempt int
created time.Time
}
var ids []intent
for rows.Next() {
var id intent
if rows.Scan(&id.id, &id.attempt, &id.created) != nil {
rows.Close()
return
}
ids = append(ids, id)
}
rows.Close()
if rows.Err() != nil {
return
}
for _, id := range ids {
if Publish(ctx, id.id, id.attempt, id.created) != nil {
return
}
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET next_publish_at=now()+interval '30 seconds' WHERE attachment_id=$1`, id.id); err != nil {
return
}
}
_ = tx.Commit(ctx)
}()
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
}
}