feat:level4
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
StreamName = "attachment.jobs"
|
||||
ConsumerGroup = "workers"
|
||||
)
|
||||
|
||||
type JobMessage 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 string `json:"created_at"`
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
}
|
||||
|
||||
type Broker struct{ rdb *redis.Client }
|
||||
|
||||
func NewBroker(ctx context.Context, url string) (*Broker, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rdb := redis.NewClient(opt)
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Группа создаётся идемпотентно.
|
||||
err = rdb.XGroupCreateMkStream(ctx, StreamName, ConsumerGroup, "0").Err()
|
||||
if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
|
||||
return nil, err
|
||||
}
|
||||
return &Broker{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
func (b *Broker) Publish(ctx context.Context, m JobMessage) (string, error) {
|
||||
buf, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return b.rdb.XAdd(ctx, &redis.XAddArgs{
|
||||
Stream: StreamName,
|
||||
Values: map[string]any{"payload": buf},
|
||||
}).Result()
|
||||
}
|
||||
|
||||
// Consume — блокирующее чтение из consumer group; ack делает вызывающий.
|
||||
func (b *Broker) Consume(ctx context.Context, consumer string) ([]redis.XMessage, error) {
|
||||
res, err := b.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
|
||||
Group: ConsumerGroup, Consumer: consumer,
|
||||
Streams: []string{StreamName, ">"},
|
||||
Count: 1, Block: 5 * time.Second,
|
||||
}).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(res) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return res[0].Messages, nil
|
||||
}
|
||||
|
||||
func (b *Broker) Ack(ctx context.Context, id string) error {
|
||||
return b.rdb.XAck(ctx, StreamName, ConsumerGroup, id).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user