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 }