feat(events): add idempotent Kafka event consumer runtime

This commit is contained in:
shira committed 2026-10-06 03:59:57 +03:00
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)
}
}