package kafka import ( "context" "errors" "fmt" "log/slog" "strconv" "sync/atomic" "time" "github.com/twmb/franz-go/pkg/kadm" "github.com/twmb/franz-go/pkg/kerr" "github.com/twmb/franz-go/pkg/kgo" "lincodex/backend/config" "lincodex/backend/internal/port/outbound" ) // maxRecordRetries bounds the client's own retries of one record within a // publish call. The relay retries unacknowledged events on later passes, so // the client does not need to retry indefinitely. const maxRecordRetries = 5 // errNotAcknowledged reports an event whose broker acknowledgement did not // arrive before the publish deadline. The broker may still have stored it. var errNotAcknowledged = errors.New("event not acknowledged before the publish deadline") // minInsyncReplicasConfig is the topic setting that acks=all writes need from // the in-sync replicas. const minInsyncReplicasConfig = "min.insync.replicas" // Publisher implements outbound.EventPublisher with a franz-go producer. All // events go to one topic; the record key keeps each aggregate's events in one // partition. type Publisher struct { client *kgo.Client admin *kadm.Client logger *slog.Logger topic string partitions int32 replicationFactor int16 minInsyncReplicas int16 provisionTopics bool produceTimeout time.Duration // layoutReported keeps the warning about an existing topic with another // layout to one log line per process. layoutReported atomic.Bool } var _ outbound.EventPublisher = (*Publisher)(nil) // NewPublisher creates the producer without connecting; franz-go dials brokers // on first use, so an unavailable broker does not block startup. The returned // cleanup closes the client and fails records that are still buffered. func NewPublisher(settings config.Config, logger *slog.Logger) (*Publisher, func(), error) { client, err := kgo.NewClient( kgo.SeedBrokers(settings.KafkaBrokers...), // Idempotent writes stay enabled (the franz-go default), which needs // acks from all in-sync replicas. kgo.RequiredAcks(kgo.AllISRAcks()), // Without this option an idempotent record that is already in flight // cannot be failed until the broker answers, so a hung broker would // hold the relay transaction open indefinitely. Failing it keeps the // publish deadline; a retried event may then be stored twice, which // the at-least-once contract already allows. kgo.AllowIdempotentProduceCancellation(), kgo.RecordDeliveryTimeout(settings.RelayProduceTimeout), kgo.RecordRetries(maxRecordRetries), // Linger would delay every pass by its full value, because a pass // produces its whole batch at once and then only waits. Without it the // first record leaves at once and franz-go batches the records produced // while that request is in flight (up to five idempotent requests per // broker), so a pass needs a few requests at most. kgo.ProducerLinger(0), ) if err != nil { return nil, nil, fmt.Errorf("kafka.NewPublisher - create Kafka client: %w", err) } publisher := &Publisher{ client: client, admin: kadm.NewClient(client), logger: logger, topic: settings.KafkaEventsTopic, partitions: settings.KafkaEventsTopicPartitions, replicationFactor: settings.KafkaEventsTopicReplicationFactor, minInsyncReplicas: settings.KafkaEventsTopicMinInsyncReplicas, provisionTopics: settings.KafkaProvisionTopics, produceTimeout: settings.RelayProduceTimeout, } return publisher, client.Close, nil } // Prepare creates the events topic with the configured partitions, // replication factor, and min.insync.replicas unless it already exists; -1 // and 0 leave the last two to the broker defaults. It does not change an // existing topic and warns once when that topic has another partition count // or replication factor. With topic provisioning disabled it does nothing, // and a missing topic makes every publish fail. func (publisher *Publisher) Prepare(ctx context.Context) error { if !publisher.provisionTopics { return nil } ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout) defer cancel() var topicConfigs map[string]*string if publisher.minInsyncReplicas > 0 { value := strconv.Itoa(int(publisher.minInsyncReplicas)) topicConfigs = map[string]*string{minInsyncReplicasConfig: &value} } responses, err := publisher.admin.CreateTopics(ctx, publisher.partitions, publisher.replicationFactor, topicConfigs, publisher.topic) if err != nil { return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, err) } response, err := responses.On(publisher.topic, nil) if err != nil { return fmt.Errorf("Publisher.Prepare - read create topic response for %s: %w", publisher.topic, err) } if response.Err != nil && !errors.Is(response.Err, kerr.TopicAlreadyExists) { return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, response.Err) } if response.Err != nil { publisher.reportExistingLayout(ctx) } return nil } // reportExistingLayout warns once when the existing topic differs from the // configured layout. The check is advisory: a failed metadata read leaves the // topic as it is and logs nothing. func (publisher *Publisher) reportExistingLayout(ctx context.Context) { if publisher.layoutReported.Load() { return } topics, err := publisher.admin.ListTopics(ctx, publisher.topic) if err != nil { return } detail, ok := topics[publisher.topic] if !ok || detail.Err != nil { return } partitions, replicas, differs := layoutDiffers(detail, publisher.partitions, publisher.replicationFactor) if differs && publisher.layoutReported.CompareAndSwap(false, true) { publisher.logger.Warn("existing events topic differs from the configured layout; the relay does not change it", slog.Int("partitions", partitions), slog.Int("configured_partitions", int(publisher.partitions)), slog.Int("replication_factor", replicas), slog.Int("configured_replication_factor", int(publisher.replicationFactor)), ) } } // layoutDiffers compares an existing topic with the configured partition // count and replication factor. A replication factor of -1 accepts any // broker default. func layoutDiffers(detail kadm.TopicDetail, partitions int32, replicationFactor int16) (actualPartitions, actualReplicas int, differs bool) { actualPartitions = len(detail.Partitions) actualReplicas = detail.Partitions.NumReplicas() differs = actualPartitions != int(partitions) || (replicationFactor > 0 && actualReplicas != int(replicationFactor)) return actualPartitions, actualReplicas, differs } // Publish produces every event and waits at most the produce timeout for the // acknowledgements. Results that do not arrive in time stay errors; the // promises of abandoned records write to a buffered channel and never block. func (publisher *Publisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error { results := make([]error, len(events)) if len(events) == 0 { return results } ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout) defer cancel() type outcome struct { index int err error } outcomes := make(chan outcome, len(events)) for index, event := range events { results[index] = errNotAcknowledged record, err := newRecord(publisher.topic, event) if err != nil { outcomes <- outcome{index: index, err: err} continue } publisher.client.Produce(ctx, record, func(_ *kgo.Record, err error) { outcomes <- outcome{index: index, err: err} }) } for range events { select { case result := <-outcomes: results[result.index] = nil if result.err != nil { results[result.index] = produceError(events[result.index], result.err) } case <-ctx.Done(): for index, err := range results { if errors.Is(err, errNotAcknowledged) { results[index] = fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", events[index].EventID, errNotAcknowledged, ctx.Err()) } } return results } } return results } // produceError wraps a failed record. A missing topic also matches // outbound.ErrEventDestinationMissing, so the relay provisions it again. func produceError(event outbound.OutboxEvent, err error) error { if errors.Is(err, kerr.UnknownTopicOrPartition) || errors.Is(err, kerr.UnknownTopicID) { return fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", event.EventID, outbound.ErrEventDestinationMissing, err) } return fmt.Errorf("Publisher.Publish - produce event %s: %w", event.EventID, err) }