File size: 4,916 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
package event
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/riverqueue/river"
"github.com/riverqueue/river/rivertype"
)
type Bus struct {
l *slog.Logger
river *river.Client[pgx.Tx]
riverDBSQL *river.Client[*sql.Tx]
b []any
}
// NewBus creates a new event bus.
func NewBus(l *slog.Logger) *Bus {
return &Bus{l: l.With("component", "EventBus")}
}
// SetRiver sets the river client for the bus.
func (b *Bus) SetRiver(r *river.Client[pgx.Tx]) { b.river = r }
// SetRiverDBSQL sets the river client for the bus.
func (b *Bus) SetRiverDBSQL(r *river.Client[*sql.Tx]) { b.riverDBSQL = r }
type (
subBus[T, TTx comparable] struct {
onBatch []func(ctx context.Context, data []T) error
onBatchTx []func(ctx context.Context, tx TTx, data []T) error
l *slog.Logger
}
nilTx any
)
func findBus[T, TTx comparable](b *Bus) *subBus[T, TTx] {
for _, b := range b.b {
s, ok := b.(*subBus[T, TTx])
if ok {
return s
}
}
sub := subBus[T, TTx]{l: b.l}
b.b = append(b.b, &sub)
return &sub
}
func (s *subBus[T, TTx]) send(ctx context.Context, data []T) error {
if len(s.onBatch) == 0 {
var dataType T
s.l.WarnContext(ctx, "no handlers for event",
slog.Group("event",
slog.String("dataType", fmt.Sprintf("%T", dataType))))
return nil
}
var errs []error
for _, fn := range s.onBatch {
err := fn(ctx, data)
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func (s *subBus[T, TTx]) sendTx(ctx context.Context, tx TTx, data []T) error {
if len(s.onBatchTx) == 0 {
var dataType T
s.l.WarnContext(ctx, "no handlers for transactional event",
slog.Group("event",
slog.String("txType", fmt.Sprintf("%T", tx)),
slog.String("dataType", fmt.Sprintf("%T", dataType))))
return nil
}
var errs []error
for _, fn := range s.onBatchTx {
err := fn(ctx, tx, data)
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// Send sends an event to the bus.
func Send[T comparable](ctx context.Context, b *Bus, event T) { SendMany(ctx, b, []T{event}) }
// Send sends an event to the bus.
func SendMany[T comparable](ctx context.Context, b *Bus, events []T) {
SendManyTx[T, nilTx](ctx, b, nil, events)
}
// SendTx sends an event to the bus that is contingent on a transaction.
func SendTx[T, TTx comparable](ctx context.Context, b *Bus, tx TTx, event T) {
SendManyTx(ctx, b, tx, []T{event})
}
// SendTx sends an event to the bus that is contingent on a transaction.
func SendManyTx[T, TTx comparable](ctx context.Context, b *Bus, tx TTx, events []T) {
for _, e := range events {
b.l.DebugContext(ctx, "send event", "event", e)
}
isNilTx := (any)(tx) == nil
var err error
sub := findBus[T, TTx](b)
if isNilTx {
err = sub.send(ctx, events)
} else {
err = sub.sendTx(ctx, tx, events)
}
if err != nil {
b.l.ErrorContext(ctx, "send event failed", "error", err)
}
}
// OnEachBatch registers a handler for a specific event type.
func OnEachBatch[T comparable](b *Bus, fn func(ctx context.Context, data []T) error) {
sub := findBus[T, nilTx](b)
sub.onBatch = append(sub.onBatch, fn)
}
// OnEachBatchTx registers a handler for a specific event type that is contingent on a transaction.
func OnEachBatchTx[T, TTx comparable](b *Bus, fn func(ctx context.Context, tx TTx, data []T) error) {
sub := findBus[T, TTx](b)
sub.onBatchTx = append(sub.onBatchTx, fn)
}
func insertJobsTx[T, TTx any](ctx context.Context, rv *river.Client[TTx], tx TTx, data []T, newJobFn func(data T) (river.JobArgs, *river.InsertOpts)) error {
args := make([]river.InsertManyParams, len(data))
for i, d := range data {
a, o := newJobFn(d)
args[i] = river.InsertManyParams{
Args: a,
InsertOpts: o,
}
}
var err error
var res []*rivertype.JobInsertResult
isNilTx := (any)(tx) == nil
if isNilTx {
res, err = rv.InsertMany(ctx, args)
} else {
res, err = rv.InsertManyTx(ctx, tx, args)
}
if err != nil {
return fmt.Errorf("insert many: %w", err)
}
for _, r := range res {
if !r.UniqueSkippedAsDuplicate {
continue
}
if isNilTx {
_, err = rv.JobRetry(ctx, r.Job.ID)
} else {
_, err = rv.JobRetryTx(ctx, tx, r.Job.ID)
}
if err != nil {
return fmt.Errorf("retry job: %w", err)
}
}
return nil
}
// RegisterJobSource registers a handler for a specific event type that creates jobs.
func RegisterJobSource[T comparable](b *Bus, newJobFn func(data T) (river.JobArgs, *river.InsertOpts)) {
OnEachBatch(b, func(ctx context.Context, data []T) error {
return insertJobsTx(ctx, b.river, nil, data, newJobFn)
})
OnEachBatchTx(b, func(ctx context.Context, tx pgx.Tx, data []T) error {
return insertJobsTx(ctx, b.river, tx, data, newJobFn)
})
OnEachBatchTx(b, func(ctx context.Context, tx *sql.Tx, data []T) error {
return insertJobsTx(ctx, b.riverDBSQL, tx, data, newJobFn)
})
}
|