feat(events): add idempotent Kafka event consumer runtime
This commit is contained in:
1 parent
565ef8d4f5
commit
3adb0ef9e4
47 files changed
+5018
-105
No files matched your search
@@ -0,0 +1,290 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/pkg/kmsg"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// leaveGroupMargin is added to CONSUMER_COMMIT_TIMEOUT to bound leaving the
|
||||
// group at close: the leave revokes the partitions, and the revocation may
|
||||
// commit finished records whose earlier commit failed. A broker that does not
|
||||
// answer in time cannot hold shutdown; a member that could not leave is
|
||||
// removed by the broker after the session timeout.
|
||||
const leaveGroupMargin = 2 * time.Second
|
||||
|
||||
// EventSource implements outbound.EventSource with a franz-go consumer group
|
||||
// member. Autocommit is off and rebalancing is blocked from a poll until
|
||||
// Release, so an offset is committed only for records the consumer finished
|
||||
// and only while this member still owns their partitions.
|
||||
type EventSource struct {
|
||||
client *kgo.Client
|
||||
logger *slog.Logger
|
||||
maxPollRecords int
|
||||
commitTimeout time.Duration
|
||||
leaveTimeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
// epochs holds the leader epoch of every record of the last poll, which
|
||||
// the commit carries for log truncation detection.
|
||||
epochs map[recordPosition]int32
|
||||
// polled holds the offsets of the last poll per partition in order, so
|
||||
// Commit can refuse finished records that skip one.
|
||||
polled map[topicPartition][]int64
|
||||
// pending holds, per partition, the position after the last finished
|
||||
// record that is not committed yet: a commit failed, and a later commit
|
||||
// or the revocation of the partition retries it.
|
||||
pending map[string]map[int32]kgo.EpochOffset
|
||||
}
|
||||
|
||||
type topicPartition struct {
|
||||
topic string
|
||||
partition int32
|
||||
}
|
||||
|
||||
type recordPosition struct {
|
||||
topic string
|
||||
partition int32
|
||||
offset int64
|
||||
}
|
||||
|
||||
var _ outbound.EventSource = (*EventSource)(nil)
|
||||
|
||||
// NewEventSource creates a member of group that consumes KAFKA_EVENTS_TOPIC
|
||||
// without connecting; franz-go dials brokers on first poll. A group without
|
||||
// a committed offset starts at the earliest retained record, so a new
|
||||
// consumer never skips an event. The returned cleanup leaves the group and
|
||||
// closes the client; call it only after the consumer stopped polling.
|
||||
func NewEventSource(settings config.Config, group string, logger *slog.Logger) (*EventSource, func(), error) {
|
||||
source := &EventSource{
|
||||
logger: logger,
|
||||
maxPollRecords: settings.ConsumerMaxPollRecords,
|
||||
commitTimeout: settings.ConsumerCommitTimeout,
|
||||
leaveTimeout: settings.ConsumerCommitTimeout + leaveGroupMargin,
|
||||
epochs: make(map[recordPosition]int32),
|
||||
polled: make(map[topicPartition][]int64),
|
||||
pending: make(map[string]map[int32]kgo.EpochOffset),
|
||||
}
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(settings.KafkaBrokers...),
|
||||
kgo.ConsumerGroup(group),
|
||||
kgo.ConsumeTopics(settings.KafkaEventsTopic),
|
||||
kgo.DisableAutoCommit(),
|
||||
kgo.BlockRebalanceOnPoll(),
|
||||
// Set explicitly: config checks that the slowest record fits in it.
|
||||
kgo.RebalanceTimeout(settings.ConsumerRebalanceTimeout),
|
||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||
kgo.OnPartitionsRevoked(source.onRevoked),
|
||||
kgo.OnPartitionsLost(source.onLost),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("kafka.NewEventSource - create Kafka client: %w", err)
|
||||
}
|
||||
source.client = client
|
||||
return source, source.close, nil
|
||||
}
|
||||
|
||||
// Poll returns the records of the next fetch in partition order. Fetch
|
||||
// errors of single partitions are joined into the error; records of other
|
||||
// partitions are still returned.
|
||||
func (source *EventSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
|
||||
fetches := source.client.PollRecords(ctx, source.maxPollRecords)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fetches.IsClientClosed() {
|
||||
return nil, errors.New("EventSource.Poll - Kafka client is closed")
|
||||
}
|
||||
var fetchErr error
|
||||
fetches.EachError(func(topic string, partition int32, err error) {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("EventSource.Poll - fetch %s partition %d: %w", topic, partition, err))
|
||||
})
|
||||
records := make([]outbound.ConsumedRecord, 0, fetches.NumRecords())
|
||||
source.mu.Lock()
|
||||
clear(source.epochs)
|
||||
clear(source.polled)
|
||||
fetches.EachRecord(func(record *kgo.Record) {
|
||||
source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}] = record.LeaderEpoch
|
||||
partition := topicPartition{topic: record.Topic, partition: record.Partition}
|
||||
source.polled[partition] = append(source.polled[partition], record.Offset)
|
||||
records = append(records, decodeRecord(record))
|
||||
})
|
||||
source.mu.Unlock()
|
||||
return records, fetchErr
|
||||
}
|
||||
|
||||
// Commit commits the position after the last finished record of each
|
||||
// partition, together with any earlier position whose commit failed.
|
||||
func (source *EventSource) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error {
|
||||
source.mu.Lock()
|
||||
if err := source.checkPrefix(finished); err != nil {
|
||||
source.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
for _, record := range finished {
|
||||
epoch := source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}]
|
||||
partitions := source.pending[record.Topic]
|
||||
if partitions == nil {
|
||||
partitions = make(map[int32]kgo.EpochOffset)
|
||||
source.pending[record.Topic] = partitions
|
||||
}
|
||||
next := kgo.EpochOffset{Epoch: epoch, Offset: record.Offset + 1}
|
||||
if current, ok := partitions[record.Partition]; !ok || current.Less(next) {
|
||||
partitions[record.Partition] = next
|
||||
}
|
||||
}
|
||||
offsets := clonePending(source.pending, nil)
|
||||
source.mu.Unlock()
|
||||
|
||||
if err := source.commitOffsets(ctx, offsets); err != nil {
|
||||
return err
|
||||
}
|
||||
source.forgetCommitted(offsets)
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkPrefix verifies that, for every partition, the finished records are
|
||||
// the first records of the last poll in order without a gap, so a commit can
|
||||
// never move a partition past a record that was not finished. The caller
|
||||
// holds mu.
|
||||
func (source *EventSource) checkPrefix(finished []outbound.ConsumedRecord) error {
|
||||
seen := make(map[topicPartition]int, len(source.polled))
|
||||
for _, record := range finished {
|
||||
partition := topicPartition{topic: record.Topic, partition: record.Partition}
|
||||
polled, index := source.polled[partition], seen[partition]
|
||||
if index >= len(polled) || polled[index] != record.Offset {
|
||||
return fmt.Errorf("EventSource.Commit - record at %s partition %d offset %d is not the next record of the last poll", record.Topic, record.Partition, record.Offset)
|
||||
}
|
||||
seen[partition] = index + 1
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release allows the group to rebalance until the next poll.
|
||||
func (source *EventSource) Release() {
|
||||
source.client.AllowRebalance()
|
||||
}
|
||||
|
||||
// onRevoked commits finished records of the revoked partitions whose
|
||||
// earlier commit failed. Unfinished records were never marked finished, so
|
||||
// they are not committed and the next owner processes them.
|
||||
func (source *EventSource) onRevoked(ctx context.Context, _ *kgo.Client, revoked map[string][]int32) {
|
||||
source.mu.Lock()
|
||||
offsets := clonePending(source.pending, revoked)
|
||||
source.dropPending(revoked)
|
||||
source.mu.Unlock()
|
||||
if len(offsets) == 0 {
|
||||
return
|
||||
}
|
||||
commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), source.commitTimeout)
|
||||
defer cancel()
|
||||
if err := source.commitOffsets(commitCtx, offsets); err != nil {
|
||||
source.logger.Warn("event consumer could not commit finished records of revoked partitions; the next owner processes them again",
|
||||
slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
// onLost drops pending positions: the member no longer belongs to the group
|
||||
// generation, so a commit would fail, and the next owner starts from the
|
||||
// last committed offset.
|
||||
func (source *EventSource) onLost(_ context.Context, _ *kgo.Client, lost map[string][]int32) {
|
||||
source.mu.Lock()
|
||||
source.dropPending(lost)
|
||||
source.mu.Unlock()
|
||||
if len(lost) > 0 {
|
||||
source.logger.Warn("event consumer lost its partitions; uncommitted records will be processed again")
|
||||
}
|
||||
}
|
||||
|
||||
func (source *EventSource) commitOffsets(ctx context.Context, offsets map[string]map[int32]kgo.EpochOffset) error {
|
||||
if len(offsets) == 0 {
|
||||
return nil
|
||||
}
|
||||
var commitErr error
|
||||
source.client.CommitOffsetsSync(ctx, offsets, func(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, response *kmsg.OffsetCommitResponse, err error) {
|
||||
if err != nil {
|
||||
commitErr = err
|
||||
return
|
||||
}
|
||||
for _, topic := range response.Topics {
|
||||
for _, partition := range topic.Partitions {
|
||||
if err := kerr.ErrorForCode(partition.ErrorCode); err != nil {
|
||||
commitErr = errors.Join(commitErr, fmt.Errorf("partition %d: %w", partition.Partition, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
if commitErr != nil {
|
||||
return fmt.Errorf("EventSource.commitOffsets - commit offsets: %w", commitErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// forgetCommitted removes pending positions that the commit covered and that
|
||||
// did not advance meanwhile.
|
||||
func (source *EventSource) forgetCommitted(committed map[string]map[int32]kgo.EpochOffset) {
|
||||
source.mu.Lock()
|
||||
defer source.mu.Unlock()
|
||||
for topic, partitions := range committed {
|
||||
for partition, offset := range partitions {
|
||||
if source.pending[topic][partition] == offset {
|
||||
delete(source.pending[topic], partition)
|
||||
}
|
||||
}
|
||||
if len(source.pending[topic]) == 0 {
|
||||
delete(source.pending, topic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (source *EventSource) dropPending(partitions map[string][]int32) {
|
||||
for topic, numbers := range partitions {
|
||||
for _, partition := range numbers {
|
||||
delete(source.pending[topic], partition)
|
||||
}
|
||||
if len(source.pending[topic]) == 0 {
|
||||
delete(source.pending, topic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// close leaves the group, which revokes the partitions and commits finished
|
||||
// records whose commit failed, and closes the client.
|
||||
func (source *EventSource) close() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), source.leaveTimeout)
|
||||
defer cancel()
|
||||
if err := source.client.LeaveGroupContext(ctx); err != nil {
|
||||
source.logger.Warn("event consumer could not leave its group; the broker removes it after the session timeout",
|
||||
slog.Any("error", err))
|
||||
}
|
||||
source.client.CloseAllowingRebalance()
|
||||
}
|
||||
|
||||
// clonePending copies the pending positions, limited to the partitions in
|
||||
// only when only is not nil.
|
||||
func clonePending(pending map[string]map[int32]kgo.EpochOffset, only map[string][]int32) map[string]map[int32]kgo.EpochOffset {
|
||||
result := make(map[string]map[int32]kgo.EpochOffset)
|
||||
for topic, partitions := range pending {
|
||||
for partition, offset := range partitions {
|
||||
if only != nil && !slices.Contains(only[topic], partition) {
|
||||
continue
|
||||
}
|
||||
if result[topic] == nil {
|
||||
result[topic] = make(map[int32]kgo.EpochOffset)
|
||||
}
|
||||
result[topic][partition] = offset
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestEventSourceCommitAcceptsOnlyAPrefixOfTheLastPollPerPartition(t *testing.T) {
|
||||
newSource := func() *EventSource {
|
||||
source := &EventSource{
|
||||
epochs: make(map[recordPosition]int32),
|
||||
polled: make(map[topicPartition][]int64),
|
||||
pending: make(map[string]map[int32]kgo.EpochOffset),
|
||||
}
|
||||
// The last poll returned offsets 4, 5, 6 of partition 0 and 9 of
|
||||
// partition 1.
|
||||
for partition, offsets := range map[int32][]int64{0: {4, 5, 6}, 1: {9}} {
|
||||
for _, offset := range offsets {
|
||||
source.epochs[recordPosition{topic: testTopic, partition: partition, offset: offset}] = 1
|
||||
key := topicPartition{topic: testTopic, partition: partition}
|
||||
source.polled[key] = append(source.polled[key], offset)
|
||||
}
|
||||
}
|
||||
return source
|
||||
}
|
||||
record := func(partition int32, offset int64) outbound.ConsumedRecord {
|
||||
return outbound.ConsumedRecord{Topic: testTopic, Partition: partition, Offset: offset}
|
||||
}
|
||||
rejected := map[string][]outbound.ConsumedRecord{
|
||||
"not from the last poll": {record(0, 7)},
|
||||
"gap": {record(0, 4), record(0, 6)},
|
||||
"skips the first record": {record(0, 5)},
|
||||
"out of order": {record(0, 5), record(0, 4)},
|
||||
"repeated record": {record(0, 4), record(0, 4)},
|
||||
"another topic": {{Topic: "other", Partition: 0, Offset: 4}},
|
||||
}
|
||||
for name, finished := range rejected {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
source := newSource()
|
||||
if err := source.Commit(t.Context(), finished); err == nil {
|
||||
t.Fatal("Commit() accepted records that are not a prefix of the last poll")
|
||||
}
|
||||
if len(source.pending) != 0 {
|
||||
t.Fatalf("Commit() kept a pending position for rejected records: %v", source.pending)
|
||||
}
|
||||
})
|
||||
}
|
||||
// Interleaved partitions are fine as long as each one is a prefix.
|
||||
source := newSource()
|
||||
if err := source.checkPrefix([]outbound.ConsumedRecord{record(0, 4), record(1, 9), record(0, 5)}); err != nil {
|
||||
t.Fatalf("checkPrefix() rejected a valid prefix: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingPositionsAreLimitedAndForgottenPerPartition(t *testing.T) {
|
||||
source := &EventSource{pending: map[string]map[int32]kgo.EpochOffset{
|
||||
testTopic: {0: {Epoch: 1, Offset: 10}, 1: {Epoch: 1, Offset: 20}},
|
||||
}}
|
||||
revoked := clonePending(source.pending, map[string][]int32{testTopic: {1}})
|
||||
if len(revoked[testTopic]) != 1 || revoked[testTopic][1].Offset != 20 {
|
||||
t.Fatalf("clonePending() = %v, want only partition 1", revoked)
|
||||
}
|
||||
|
||||
committed := clonePending(source.pending, nil)
|
||||
// Partition 0 advanced while the commit was in flight, so it stays.
|
||||
source.pending[testTopic][0] = kgo.EpochOffset{Epoch: 1, Offset: 11}
|
||||
source.forgetCommitted(committed)
|
||||
if len(source.pending[testTopic]) != 1 || source.pending[testTopic][0].Offset != 11 {
|
||||
t.Fatalf("pending after forgetCommitted() = %v, want only the advanced partition 0", source.pending)
|
||||
}
|
||||
source.dropPending(map[string][]int32{testTopic: {0}})
|
||||
if len(source.pending) != 0 {
|
||||
t.Fatalf("pending after dropPending() = %v, want none", source.pending)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
@@ -9,6 +10,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
@@ -74,3 +76,96 @@ func newRecord(topic string, event outbound.OutboxEvent) (*kgo.Record, error) {
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// decodeRecord turns a consumed record into an event. A value that is not a
|
||||
// valid envelope yields a record whose Invalid error matches
|
||||
// outbound.ErrInvalidEventRecord; the error names the broken rule and never
|
||||
// quotes the value. EventID then comes from the event_id header when it holds
|
||||
// a UUID, so an operator can still find the event.
|
||||
func decodeRecord(record *kgo.Record) outbound.ConsumedRecord {
|
||||
consumed := outbound.ConsumedRecord{
|
||||
Topic: record.Topic,
|
||||
Partition: record.Partition,
|
||||
Offset: record.Offset,
|
||||
Value: record.Value,
|
||||
}
|
||||
headerID, headerErr := uuid.Parse(recordHeader(record, headerEventID))
|
||||
if headerErr == nil {
|
||||
consumed.EventID = headerID
|
||||
}
|
||||
event, err := decodeEnvelope(record.Value)
|
||||
if err == nil && headerErr == nil && headerID != event.EventID {
|
||||
// A consumer that deduplicated by the header would disagree with one
|
||||
// that reads the value, so the record is not trusted.
|
||||
err = invalidRecord("event_id header differs from the envelope")
|
||||
}
|
||||
if err != nil {
|
||||
consumed.Invalid = err
|
||||
return consumed
|
||||
}
|
||||
consumed.Event = event
|
||||
consumed.EventID = event.EventID
|
||||
return consumed
|
||||
}
|
||||
|
||||
func decodeEnvelope(value []byte) (outbound.ConsumedEvent, error) {
|
||||
var decoded envelope
|
||||
// The json error is dropped: its text can quote part of the value.
|
||||
if err := json.Unmarshal(value, &decoded); err != nil {
|
||||
return outbound.ConsumedEvent{}, invalidRecord("value is not a JSON event envelope")
|
||||
}
|
||||
if decoded.EnvelopeVersion != EnvelopeVersion {
|
||||
return outbound.ConsumedEvent{}, invalidRecord("unsupported envelope_version")
|
||||
}
|
||||
if decoded.EventID == uuid.Nil {
|
||||
return outbound.ConsumedEvent{}, invalidRecord("event_id is missing")
|
||||
}
|
||||
identity := domain.DomainEventInput{
|
||||
EventType: decoded.EventType,
|
||||
SchemaVersion: decoded.SchemaVersion,
|
||||
AggregateType: decoded.AggregateType,
|
||||
AggregateID: decoded.AggregateID,
|
||||
AggregateVersion: decoded.AggregateVersion,
|
||||
}
|
||||
if err := identity.ValidateIdentity(); err != nil {
|
||||
return outbound.ConsumedEvent{}, fmt.Errorf("kafka.decodeEnvelope - %w: %w", outbound.ErrInvalidEventRecord, err)
|
||||
}
|
||||
if decoded.OccurredAt.IsZero() {
|
||||
return outbound.ConsumedEvent{}, invalidRecord("occurred_at is missing")
|
||||
}
|
||||
if !isJSONObject(decoded.Payload) {
|
||||
return outbound.ConsumedEvent{}, invalidRecord("payload is not a JSON object")
|
||||
}
|
||||
return outbound.ConsumedEvent{
|
||||
EventID: decoded.EventID,
|
||||
EventType: decoded.EventType,
|
||||
SchemaVersion: decoded.SchemaVersion,
|
||||
AggregateType: decoded.AggregateType,
|
||||
AggregateID: decoded.AggregateID,
|
||||
AggregateVersion: decoded.AggregateVersion,
|
||||
OccurredAt: decoded.OccurredAt,
|
||||
Payload: decoded.Payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// isJSONObject reports whether raw, which json.Unmarshal already checked, is
|
||||
// an object rather than another value or null.
|
||||
func isJSONObject(raw json.RawMessage) bool {
|
||||
trimmed := bytes.TrimLeft(raw, " \t\r\n")
|
||||
return len(trimmed) > 0 && trimmed[0] == '{'
|
||||
}
|
||||
|
||||
func invalidRecord(reason string) error {
|
||||
return fmt.Errorf("kafka.decodeEnvelope - %s: %w", reason, outbound.ErrInvalidEventRecord)
|
||||
}
|
||||
|
||||
// recordHeader returns the last value of the header key, or "" without one.
|
||||
func recordHeader(record *kgo.Record, key string) string {
|
||||
value := ""
|
||||
for _, header := range record.Headers {
|
||||
if header.Key == key {
|
||||
value = string(header.Value)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -2,11 +2,13 @@ package kafka
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
@@ -103,3 +105,106 @@ func TestNewRecordRejectsAnInvalidPayloadWithoutQuotingIt(t *testing.T) {
|
||||
t.Fatalf("newRecord() error = %v, want the event ID", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRecordReadsWhatNewRecordWrites(t *testing.T) {
|
||||
want := testEvent()
|
||||
record, err := newRecord(testTopic, want)
|
||||
if err != nil {
|
||||
t.Fatalf("newRecord() error = %v", err)
|
||||
}
|
||||
record.Partition, record.Offset = 2, 41
|
||||
|
||||
consumed := decodeRecord(record)
|
||||
if consumed.Invalid != nil {
|
||||
t.Fatalf("decodeRecord() Invalid = %v", consumed.Invalid)
|
||||
}
|
||||
got := consumed.Event
|
||||
if consumed.Topic != testTopic || consumed.Partition != 2 || consumed.Offset != 41 || consumed.EventID != want.EventID ||
|
||||
got.EventID != want.EventID || got.EventType != want.EventType || got.SchemaVersion != want.SchemaVersion ||
|
||||
got.AggregateType != want.AggregateType || got.AggregateID != want.AggregateID ||
|
||||
got.AggregateVersion != want.AggregateVersion || !got.OccurredAt.Equal(want.OccurredAt) {
|
||||
t.Fatalf("decodeRecord() = %+v, want the fields of %+v", consumed, want)
|
||||
}
|
||||
if string(got.Payload) != `{"user_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","nested":{"n":1}}` {
|
||||
t.Fatalf("payload = %s", got.Payload)
|
||||
}
|
||||
if string(consumed.Value) != string(record.Value) {
|
||||
t.Fatal("decodeRecord() did not keep the raw value")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRecordRejectsInvalidEnvelopesWithoutQuotingThem(t *testing.T) {
|
||||
valid, err := newRecord(testTopic, testEvent())
|
||||
if err != nil {
|
||||
t.Fatalf("newRecord() error = %v", err)
|
||||
}
|
||||
headerID := testEvent().EventID
|
||||
withField := func(field string, value any) []byte {
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(valid.Value, &fields); err != nil {
|
||||
t.Fatalf("decode test envelope: %v", err)
|
||||
}
|
||||
if value == nil {
|
||||
delete(fields, field)
|
||||
} else {
|
||||
fields[field] = value
|
||||
}
|
||||
encoded, err := json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatalf("encode test envelope: %v", err)
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
value []byte
|
||||
headers []kgo.RecordHeader
|
||||
want string
|
||||
}{
|
||||
{name: "not JSON", value: []byte("secret-value"), want: "value is not a JSON event envelope"},
|
||||
{name: "wrong type", value: withField("event_id", "secret-value"), want: "value is not a JSON event envelope"},
|
||||
{name: "future envelope", value: withField("envelope_version", 2), want: "unsupported envelope_version"},
|
||||
{name: "no event ID", value: withField("event_id", nil), want: "event_id is missing"},
|
||||
{name: "bad event type", value: withField("event_type", "Secret Value"), want: "event type must be"},
|
||||
{name: "zero schema", value: withField("schema_version", 0), want: "schema version must be positive"},
|
||||
{name: "no aggregate", value: withField("aggregate_id", nil), want: "aggregate ID must not be nil"},
|
||||
{name: "zero version", value: withField("aggregate_version", 0), want: "aggregate version must be positive"},
|
||||
{name: "no time", value: withField("occurred_at", nil), want: "occurred_at is missing"},
|
||||
{name: "array payload", value: withField("payload", []string{"secret-value"}), want: "payload is not a JSON object"},
|
||||
{name: "null payload", value: withField("payload", nil), want: "payload is not a JSON object"},
|
||||
{
|
||||
name: "header mismatch",
|
||||
value: valid.Value,
|
||||
headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(uuid.NewString())}},
|
||||
want: "event_id header differs from the envelope",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
headers := test.headers
|
||||
if headers == nil {
|
||||
headers = []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}}
|
||||
}
|
||||
consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: test.value, Headers: headers})
|
||||
if !errors.Is(consumed.Invalid, outbound.ErrInvalidEventRecord) {
|
||||
t.Fatalf("Invalid = %v, want ErrInvalidEventRecord", consumed.Invalid)
|
||||
}
|
||||
if !strings.Contains(consumed.Invalid.Error(), test.want) {
|
||||
t.Fatalf("Invalid = %v, want %q", consumed.Invalid, test.want)
|
||||
}
|
||||
if strings.Contains(consumed.Invalid.Error(), "secret") || strings.Contains(consumed.Invalid.Error(), "Secret") {
|
||||
t.Fatalf("Invalid quotes the value: %v", consumed.Invalid)
|
||||
}
|
||||
if test.headers == nil && consumed.EventID != headerID {
|
||||
t.Fatalf("EventID = %s, want the header event ID", consumed.EventID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRecordWithoutAnEventIDHeaderLeavesItNil(t *testing.T) {
|
||||
consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: []byte("{}"), Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte("not-a-uuid")}}})
|
||||
if consumed.Invalid == nil || consumed.EventID != uuid.Nil {
|
||||
t.Fatalf("decodeRecord() = %+v, want an invalid record without an event ID", consumed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// SQLSTATE classes that classifyCommitError separates.
|
||||
const (
|
||||
sqlStateClassLength = 2
|
||||
integrityConstraintClass = "23"
|
||||
transactionRollbackClass = "40"
|
||||
)
|
||||
|
||||
// EventConsumerStore implements outbound.EventConsumerStore with a pgx pool
|
||||
// owned by the caller. Each ApplyOnce holds one connection and one
|
||||
// transaction for the duration of the handler.
|
||||
type EventConsumerStore struct {
|
||||
pool *pgxpool.Pool
|
||||
// transactionTimeout is set as statement_timeout and
|
||||
// idle_in_transaction_session_timeout of every ApplyOnce transaction.
|
||||
transactionTimeout time.Duration
|
||||
}
|
||||
|
||||
var _ outbound.EventConsumerStore = (*EventConsumerStore)(nil)
|
||||
|
||||
// NewEventConsumerStore bounds each transaction on the server by
|
||||
// transactionTimeout, the consumer's handler timeout. The caller's context
|
||||
// already cancels the work of a live process; the server-side limits also
|
||||
// end the transaction of a process that froze or lost the network, so the
|
||||
// marker it holds does not block a concurrent duplicate indefinitely.
|
||||
func NewEventConsumerStore(pool *pgxpool.Pool, transactionTimeout time.Duration) *EventConsumerStore {
|
||||
return &EventConsumerStore{pool: pool, transactionTimeout: transactionTimeout}
|
||||
}
|
||||
|
||||
// ApplyOnce inserts the marker first and runs apply only when the insert
|
||||
// added it. INSERT ... ON CONFLICT DO NOTHING is used rather than a plain
|
||||
// INSERT that fails on the unique key: it waits for a concurrent transaction
|
||||
// holding the same key exactly as the plain insert would, but a duplicate
|
||||
// then reports zero rows instead of aborting the transaction with SQLSTATE
|
||||
// 23505, so no error decides control flow and PostgreSQL logs no error for
|
||||
// an expected duplicate.
|
||||
func (store *EventConsumerStore) ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply outbound.ApplyEvent) (bool, error) {
|
||||
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
|
||||
// silently remove the bound.
|
||||
if store.transactionTimeout < time.Millisecond {
|
||||
return false, errors.New("EventConsumerStore.ApplyOnce - transaction timeout must be at least 1ms")
|
||||
}
|
||||
if ctx.Value(transactionContextKey{}) != nil {
|
||||
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", outbound.ErrNestedTransaction)
|
||||
}
|
||||
tx, err := store.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
// Runs only when apply panics; the panic keeps its stack and the
|
||||
// rollback error cannot change that outcome.
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
applied, applyErr := store.applyInTransaction(ctx, tx, consumer, eventID, apply)
|
||||
finished = true
|
||||
if applyErr != nil || !applied {
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return false, errors.Join(applyErr, fmt.Errorf("EventConsumerStore.ApplyOnce - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return false, applyErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - commit transaction: %w", classifyCommitError(err))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// classifyCommitError separates a commit that PostgreSQL refused from one
|
||||
// that failed in transport. A refusal is deterministic or caused by
|
||||
// concurrent writers, so the consumer counts it as a handler attempt instead
|
||||
// of retrying it as a database outage forever:
|
||||
//
|
||||
// - pgx.ErrTxCommitRollback: a statement of the handler failed and the
|
||||
// handler returned nil anyway, so PostgreSQL rolled the aborted
|
||||
// transaction back;
|
||||
// - SQLSTATE class 23: a deferred integrity constraint failed at commit;
|
||||
// - SQLSTATE class 40: a serialization failure or deadlock, which a retry
|
||||
// usually resolves, so it matches outbound.ErrTransactionConflict.
|
||||
//
|
||||
// Connection and network errors pass through as store failures.
|
||||
func classifyCommitError(err error) error {
|
||||
if errors.Is(err, pgx.ErrTxCommitRollback) {
|
||||
return fmt.Errorf("postgres.classifyCommitError - transaction was aborted by a failed statement: %w", outbound.ErrEventEffectRejected)
|
||||
}
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && len(pgError.Code) == len(deadlockDetectedCode) {
|
||||
safe := &databaseError{code: pgError.Code, constraint: pgError.ConstraintName}
|
||||
switch pgError.Code[:sqlStateClassLength] {
|
||||
case integrityConstraintClass:
|
||||
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrEventEffectRejected, safe)
|
||||
case transactionRollbackClass:
|
||||
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrTransactionConflict, safe)
|
||||
}
|
||||
}
|
||||
return sanitizedDatabaseError(err)
|
||||
}
|
||||
|
||||
// sanitizedApplyError keeps the identity of a handler error for errors.Is
|
||||
// and errors.As but replaces the text of a PostgreSQL error inside it, whose
|
||||
// message can quote row values, with its SQLSTATE and constraint. The
|
||||
// consumer logs this text and stores it with a dead letter.
|
||||
type sanitizedApplyError struct {
|
||||
text string
|
||||
cause error
|
||||
}
|
||||
|
||||
func (err *sanitizedApplyError) Error() string { return err.text }
|
||||
|
||||
func (err *sanitizedApplyError) Unwrap() error { return err.cause }
|
||||
|
||||
func sanitizeApplyError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return err
|
||||
}
|
||||
safe := (&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}).Error()
|
||||
text := strings.ReplaceAll(err.Error(), pgError.Error(), safe)
|
||||
// A handler that formatted the message itself may still carry it.
|
||||
if pgError.Message != "" && strings.Contains(text, pgError.Message) {
|
||||
text = "handler failed: " + safe
|
||||
}
|
||||
return &sanitizedApplyError{text: text, cause: err}
|
||||
}
|
||||
|
||||
func (store *EventConsumerStore) applyInTransaction(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
consumer string,
|
||||
eventID uuid.UUID,
|
||||
apply outbound.ApplyEvent,
|
||||
) (bool, error) {
|
||||
queries := sqlc.New(tx)
|
||||
timeout := milliseconds(store.transactionTimeout)
|
||||
err := queries.SetConsumerTransactionTimeouts(ctx, sqlc.SetConsumerTransactionTimeoutsParams{
|
||||
StatementTimeoutMs: timeout,
|
||||
IdleTimeoutMs: timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("postgres.applyInTransaction - set transaction timeouts: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
inserted, err := queries.InsertProcessedEventMarker(ctx, sqlc.InsertProcessedEventMarkerParams{
|
||||
ConsumerName: consumer,
|
||||
EventID: pgtype.UUID{Bytes: eventID, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("postgres.applyInTransaction - insert processed event marker: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if inserted == 0 {
|
||||
return false, nil
|
||||
}
|
||||
unit := &UnitOfWork{tx: tx, queries: queries}
|
||||
// The error of apply is returned without a store location, so the caller
|
||||
// keeps its identity; only PostgreSQL text inside it is replaced.
|
||||
if err := apply(context.WithValue(ctx, transactionContextKey{}, true), unit); err != nil {
|
||||
return false, sanitizeApplyError(markTransactionConflict(err))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RecordDeadLetter stores letter outside any consumer transaction.
|
||||
func (store *EventConsumerStore) RecordDeadLetter(ctx context.Context, letter outbound.DeadLetter) error {
|
||||
if letter.Attempts < 0 || letter.Attempts > math.MaxInt32 || letter.ValueSize < 0 || letter.ValueSize > math.MaxInt32 {
|
||||
return errors.New("EventConsumerStore.RecordDeadLetter - attempts and value size must fit a non-negative int32")
|
||||
}
|
||||
params := sqlc.InsertConsumerDeadLetterParams{
|
||||
ConsumerName: letter.Consumer,
|
||||
Topic: letter.Topic,
|
||||
KafkaPartition: letter.Partition,
|
||||
KafkaOffset: letter.Offset,
|
||||
EventID: pgtype.UUID{Bytes: letter.EventID, Valid: letter.EventID != uuid.Nil},
|
||||
EventType: pgtype.Text{String: letter.EventType, Valid: letter.EventType != ""},
|
||||
ErrorClass: string(letter.ErrorClass),
|
||||
Reason: letter.Reason,
|
||||
Attempts: int32(letter.Attempts),
|
||||
ValueSize: int32(letter.ValueSize),
|
||||
ValueSha256: letter.ValueSHA256[:],
|
||||
}
|
||||
if err := sqlc.New(store.pool).InsertConsumerDeadLetter(ctx, params); err != nil {
|
||||
return fmt.Errorf("EventConsumerStore.RecordDeadLetter - insert dead letter: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestClassifyCommitErrorSeparatesRefusalsFromTransportFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
rejected bool
|
||||
conflict bool
|
||||
forbidText string
|
||||
}{
|
||||
{name: "aborted transaction", err: pgx.ErrTxCommitRollback, rejected: true},
|
||||
{
|
||||
name: "deferred unique violation",
|
||||
err: &pgconn.PgError{Code: "23505", ConstraintName: "effects_key", Message: "duplicate key secret-value"},
|
||||
rejected: true,
|
||||
forbidText: "secret-value",
|
||||
},
|
||||
{name: "serialization failure", err: &pgconn.PgError{Code: "40001", Message: "could not serialize"}, conflict: true},
|
||||
{name: "deadlock", err: &pgconn.PgError{Code: "40P01"}, conflict: true},
|
||||
{name: "network", err: &net.OpError{Op: "read", Err: errors.New("connection reset")}},
|
||||
{name: "server shutdown", err: &pgconn.PgError{Code: "57P01", Message: "terminating connection secret-value"}, forbidText: "secret-value"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := classifyCommitError(test.err)
|
||||
if got := errors.Is(err, outbound.ErrEventEffectRejected); got != test.rejected {
|
||||
t.Fatalf("classifyCommitError() = %v, rejected = %t, want %t", err, got, test.rejected)
|
||||
}
|
||||
if got := errors.Is(err, outbound.ErrTransactionConflict); got != test.conflict {
|
||||
t.Fatalf("classifyCommitError() = %v, conflict = %t, want %t", err, got, test.conflict)
|
||||
}
|
||||
if test.forbidText != "" && strings.Contains(err.Error(), test.forbidText) {
|
||||
t.Fatalf("classifyCommitError() kept the PostgreSQL message: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeApplyErrorKeepsIdentityButDropsThePostgreSQLMessage(t *testing.T) {
|
||||
pgError := &pgconn.PgError{Severity: "ERROR", Code: "22P02", Message: `invalid input syntax for type uuid: "secret-value"`}
|
||||
wrapped := fmt.Errorf("apply effect: %w: %w", inbound.ErrEventRejected, pgError)
|
||||
|
||||
err := sanitizeApplyError(wrapped)
|
||||
if strings.Contains(err.Error(), "secret-value") {
|
||||
t.Fatalf("sanitizeApplyError() kept the message: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "apply effect") || !strings.Contains(err.Error(), "22P02") {
|
||||
t.Fatalf("sanitizeApplyError() = %q, want the handler context and the SQLSTATE", err)
|
||||
}
|
||||
var found *pgconn.PgError
|
||||
if !errors.Is(err, inbound.ErrEventRejected) || !errors.As(err, &found) {
|
||||
t.Fatalf("sanitizeApplyError() lost the error identity: %v", err)
|
||||
}
|
||||
|
||||
// A handler that copied only the message into its own text.
|
||||
copied := fmt.Errorf("apply effect failed with %s: %w", pgError.Message, errors.New("cause"))
|
||||
copied = fmt.Errorf("%w (%w)", copied, pgError)
|
||||
if err := sanitizeApplyError(copied); strings.Contains(err.Error(), "secret-value") {
|
||||
t.Fatalf("sanitizeApplyError() kept a copied message: %v", err)
|
||||
}
|
||||
|
||||
plain := errors.New("plain handler failure")
|
||||
if err := sanitizeApplyError(plain); err != plain { //nolint:errorlint // The same value proves the pass-through.
|
||||
t.Fatalf("sanitizeApplyError() changed an error without PostgreSQL text: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publ
|
||||
return claimErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err))
|
||||
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -93,11 +93,11 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
|
||||
IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err))
|
||||
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err))
|
||||
return fmt.Errorf("postgres.claimPending - lock pending events: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
@@ -130,7 +130,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
|
||||
}
|
||||
count, err := queries.MarkOutboxEventsPublished(ctx, marked)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err))
|
||||
return fmt.Errorf("postgres.claimPending - mark published events: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if count != int64(len(marked)) {
|
||||
return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked))
|
||||
@@ -142,7 +142,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
|
||||
func (store *OutboxRelayStore) Backlog(ctx context.Context) (outbound.OutboxBacklog, error) {
|
||||
row, err := sqlc.New(store.pool).GetOutboxBacklog(ctx)
|
||||
if err != nil {
|
||||
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", relayDatabaseError(err))
|
||||
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return outbound.OutboxBacklog{
|
||||
Pending: row.PendingEvents,
|
||||
@@ -169,10 +169,11 @@ func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEven
|
||||
}
|
||||
}
|
||||
|
||||
// relayDatabaseError keeps only the SQLSTATE of a PostgreSQL error, whose
|
||||
// message or detail could quote an event payload, and drops the connection
|
||||
// prefix of a connect error.
|
||||
func relayDatabaseError(err error) error {
|
||||
// sanitizedDatabaseError keeps only the SQLSTATE and constraint of a
|
||||
// PostgreSQL error, whose message or detail could quote an event payload, and
|
||||
// drops the connection prefix of a connect error. The relay and the event
|
||||
// consumers use it.
|
||||
func sanitizedDatabaseError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) {
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
|
||||
@@ -43,15 +43,15 @@ func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) {
|
||||
Message: `invalid input syntax for type json: "secret-payload"`,
|
||||
Detail: `Token "secret-payload" is invalid.`,
|
||||
}
|
||||
err := relayDatabaseError(original)
|
||||
err := sanitizedDatabaseError(original)
|
||||
if strings.Contains(err.Error(), "secret-payload") {
|
||||
t.Fatalf("relayDatabaseError() kept the message: %v", err)
|
||||
t.Fatalf("sanitizedDatabaseError() kept the message: %v", err)
|
||||
}
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" {
|
||||
t.Fatalf("relayDatabaseError() = %v, want SQLSTATE 22P02", err)
|
||||
t.Fatalf("sanitizedDatabaseError() = %v, want SQLSTATE 22P02", err)
|
||||
}
|
||||
if conflict := relayDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("relayDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
|
||||
if conflict := sanitizedDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("sanitizedDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: event_consumer.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const insertConsumerDeadLetter = `-- name: InsertConsumerDeadLetter :exec
|
||||
INSERT INTO consumer_dead_letters (
|
||||
consumer_name,
|
||||
topic,
|
||||
kafka_partition,
|
||||
kafka_offset,
|
||||
event_id,
|
||||
event_type,
|
||||
error_class,
|
||||
reason,
|
||||
attempts,
|
||||
value_size,
|
||||
value_sha256
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11
|
||||
)
|
||||
ON CONFLICT (
|
||||
consumer_name, topic, kafka_partition, kafka_offset, value_sha256
|
||||
) DO UPDATE SET
|
||||
event_id = excluded.event_id,
|
||||
event_type = excluded.event_type,
|
||||
error_class = excluded.error_class,
|
||||
reason = excluded.reason,
|
||||
attempts = excluded.attempts,
|
||||
dead_lettered_at = clock_timestamp()
|
||||
`
|
||||
|
||||
type InsertConsumerDeadLetterParams struct {
|
||||
ConsumerName string
|
||||
Topic string
|
||||
KafkaPartition int32
|
||||
KafkaOffset int64
|
||||
EventID pgtype.UUID
|
||||
EventType pgtype.Text
|
||||
ErrorClass string
|
||||
Reason string
|
||||
Attempts int32
|
||||
ValueSize int32
|
||||
ValueSha256 []byte
|
||||
}
|
||||
|
||||
// Stores a record that a consumer could not apply. A second delivery of the
|
||||
// same record (same position and value) refreshes the outcome of its row:
|
||||
// after a rewind the handler may fail differently. A different value at a
|
||||
// reused position, after the topic was recreated, gets its own row.
|
||||
func (q *Queries) InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error {
|
||||
_, err := q.db.Exec(ctx, insertConsumerDeadLetter,
|
||||
arg.ConsumerName,
|
||||
arg.Topic,
|
||||
arg.KafkaPartition,
|
||||
arg.KafkaOffset,
|
||||
arg.EventID,
|
||||
arg.EventType,
|
||||
arg.ErrorClass,
|
||||
arg.Reason,
|
||||
arg.Attempts,
|
||||
arg.ValueSize,
|
||||
arg.ValueSha256,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertProcessedEventMarker = `-- name: InsertProcessedEventMarker :execrows
|
||||
INSERT INTO consumer_processed_events (consumer_name, event_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (consumer_name, event_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertProcessedEventMarkerParams struct {
|
||||
ConsumerName string
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Records that a consumer applies an event, in the transaction of the effect.
|
||||
// It returns 0 rows when the marker exists. While another transaction holds
|
||||
// an uncommitted marker for the same key, the insert waits for it: after a
|
||||
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
|
||||
// never runs the effect at the same time as the first delivery.
|
||||
func (q *Queries) InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertProcessedEventMarker, arg.ConsumerName, arg.EventID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const setConsumerTransactionTimeouts = `-- name: SetConsumerTransactionTimeouts :exec
|
||||
SELECT
|
||||
set_config('statement_timeout', $1::text, true),
|
||||
set_config(
|
||||
'idle_in_transaction_session_timeout',
|
||||
$2::text,
|
||||
true
|
||||
)
|
||||
`
|
||||
|
||||
type SetConsumerTransactionTimeoutsParams struct {
|
||||
StatementTimeoutMs string
|
||||
IdleTimeoutMs string
|
||||
}
|
||||
|
||||
// Bounds a consumer transaction on the server, local to the transaction.
|
||||
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
// ends the session of a process that froze or lost the network inside the
|
||||
// handler, which releases the processed-event marker that a concurrent
|
||||
// duplicate waits for.
|
||||
func (q *Queries) SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) error {
|
||||
_, err := q.db.Exec(ctx, setConsumerTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
|
||||
return err
|
||||
}
|
||||
@@ -8,6 +8,28 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type ConsumerDeadLetter struct {
|
||||
ID int64
|
||||
ConsumerName string
|
||||
Topic string
|
||||
KafkaPartition int32
|
||||
KafkaOffset int64
|
||||
EventID pgtype.UUID
|
||||
EventType pgtype.Text
|
||||
ErrorClass string
|
||||
Reason string
|
||||
Attempts int32
|
||||
ValueSize int32
|
||||
ValueSha256 []byte
|
||||
DeadLetteredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ConsumerProcessedEvent struct {
|
||||
ConsumerName string
|
||||
EventID pgtype.UUID
|
||||
ProcessedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type EmailToken struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -49,6 +49,11 @@ type Querier interface {
|
||||
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
// Stores a record that a consumer could not apply. A second delivery of the
|
||||
// same record (same position and value) refreshes the outcome of its row:
|
||||
// after a rewind the handler may fail differently. A different value at a
|
||||
// reused position, after the topic was recreated, gets its own row.
|
||||
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
|
||||
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
|
||||
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
|
||||
// Stores a version and returns the stored row with the publication time and
|
||||
@@ -57,6 +62,12 @@ type Querier interface {
|
||||
// surrounding transaction. created_at is never taken from the caller, and a
|
||||
// NULL effective_at means "at publication".
|
||||
InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error)
|
||||
// Records that a consumer applies an event, in the transaction of the effect.
|
||||
// It returns 0 rows when the marker exists. While another transaction holds
|
||||
// an uncommitted marker for the same key, the insert waits for it: after a
|
||||
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
|
||||
// never runs the effect at the same time as the first delivery.
|
||||
InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error)
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
@@ -82,6 +93,12 @@ type Querier interface {
|
||||
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Bounds a consumer transaction on the server, local to the transaction.
|
||||
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
// ends the session of a process that froze or lost the network inside the
|
||||
// handler, which releases the processed-event marker that a concurrent
|
||||
// duplicate waits for.
|
||||
SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) error
|
||||
// Bounds the claim transaction on the server. statement_timeout stops a
|
||||
// statement that runs too long; idle_in_transaction_session_timeout ends the
|
||||
// session, and with it the transaction and its row locks, when the client
|
||||
|
||||
@@ -25,6 +25,12 @@ type Metrics struct {
|
||||
// so dashboards aggregate them with max, not sum.
|
||||
relayPending client.Gauge
|
||||
relayOldestAge client.Gauge
|
||||
// consumerRecords counts consumed records by consumer and final
|
||||
// outcome; every record ends with exactly one outcome.
|
||||
consumerRecords *client.CounterVec
|
||||
// consumerFailures counts every failed consumer operation, including the
|
||||
// last handler attempt before a dead letter, by the stage that failed.
|
||||
consumerFailures *client.CounterVec
|
||||
}
|
||||
|
||||
// Outbox relay outcome label values.
|
||||
@@ -33,6 +39,13 @@ const (
|
||||
relayOutcomeFailed = "failed"
|
||||
)
|
||||
|
||||
// Event consumer label values. They mirror the eventconsumer constants, which
|
||||
// this adapter does not import; PrepareEventConsumer creates these series.
|
||||
var (
|
||||
consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"}
|
||||
consumerStages = []string{"handler", "store", "poll", "commit"}
|
||||
)
|
||||
|
||||
func New() *Metrics {
|
||||
registry := client.NewRegistry()
|
||||
requests := client.NewCounterVec(client.CounterOpts{
|
||||
@@ -56,10 +69,19 @@ func New() *Metrics {
|
||||
Name: "lincodex_outbox_relay_oldest_pending_age_seconds",
|
||||
Help: "Age of the earliest unpublished outbox event at the last backlog read by the relay; 0 without pending events.",
|
||||
})
|
||||
consumerRecords := client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_event_consumer_records_total",
|
||||
Help: "Event bus records finished by a consumer, by outcome: applied, duplicate, ignored, or dead_lettered.",
|
||||
}, []string{"consumer", "outcome"})
|
||||
consumerFailures := client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_event_consumer_failures_total",
|
||||
Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.",
|
||||
}, []string{"consumer", "stage"})
|
||||
registry.MustRegister(
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
requests, latency, relayEvents, relayPending, relayOldestAge,
|
||||
consumerRecords, consumerFailures,
|
||||
)
|
||||
// Expose both series from the start so rate queries see zero, not absence.
|
||||
relayEvents.WithLabelValues(relayOutcomePublished)
|
||||
@@ -71,9 +93,34 @@ func New() *Metrics {
|
||||
relayEvents: relayEvents,
|
||||
relayPending: relayPending,
|
||||
relayOldestAge: relayOldestAge,
|
||||
|
||||
consumerRecords: consumerRecords,
|
||||
consumerFailures: consumerFailures,
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareEventConsumer exposes every series of consumer at zero, so an alert
|
||||
// on the first dead letter sees an increase instead of a new series.
|
||||
func (metrics *Metrics) PrepareEventConsumer(consumer string) {
|
||||
for _, outcome := range consumerOutcomes {
|
||||
metrics.consumerRecords.WithLabelValues(consumer, outcome)
|
||||
}
|
||||
for _, stage := range consumerStages {
|
||||
metrics.consumerFailures.WithLabelValues(consumer, stage)
|
||||
}
|
||||
}
|
||||
|
||||
// ObserveConsumedRecord counts one finished record.
|
||||
func (metrics *Metrics) ObserveConsumedRecord(consumer, outcome string) {
|
||||
metrics.consumerRecords.WithLabelValues(consumer, outcome).Inc()
|
||||
}
|
||||
|
||||
// ObserveConsumerFailure counts one failed handler attempt, store
|
||||
// operation, poll, or offset commit.
|
||||
func (metrics *Metrics) ObserveConsumerFailure(consumer, stage string) {
|
||||
metrics.consumerFailures.WithLabelValues(consumer, stage).Inc()
|
||||
}
|
||||
|
||||
// ObserveOutboxBacklog records the latest backlog read.
|
||||
func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
|
||||
metrics.relayPending.Set(float64(backlog.Pending))
|
||||
|
||||
@@ -58,3 +58,31 @@ func TestMetricsHandlerExposesTheOutboxBacklog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesEventConsumerOutcomes(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.PrepareEventConsumer("audit_log")
|
||||
metrics.ObserveConsumedRecord("audit_log", "applied")
|
||||
metrics.ObserveConsumedRecord("audit_log", "applied")
|
||||
metrics.ObserveConsumedRecord("audit_log", "dead_lettered")
|
||||
metrics.ObserveConsumerFailure("audit_log", "handler")
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := response.Body.String()
|
||||
for _, want := range []string{
|
||||
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="applied"} 2`,
|
||||
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="dead_lettered"} 1`,
|
||||
// Prepared series are exposed at zero before the first observation.
|
||||
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="duplicate"} 0`,
|
||||
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="ignored"} 0`,
|
||||
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="handler"} 1`,
|
||||
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="store"} 0`,
|
||||
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="poll"} 0`,
|
||||
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="commit"} 0`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user