package kafka import ( "context" "errors" "fmt" "log/slog" "net" "testing" "time" "github.com/twmb/franz-go/pkg/kadm" "github.com/twmb/franz-go/pkg/kerr" "lincodex/backend/config" "lincodex/backend/internal/port/outbound" ) const ( unitProduceTimeout = time.Second // publishBoundSlack covers scheduling around the produce timeout. publishBoundSlack = 2 * time.Second ) // unreachableBroker returns the address of a closed local port, so every // connection attempt is refused. func unreachableBroker(t *testing.T) string { t.Helper() listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") if err != nil { t.Fatalf("listen: %v", err) } address := listener.Addr().String() if err := listener.Close(); err != nil { t.Fatalf("close listener: %v", err) } return address } func newUnitPublisher(t *testing.T, provision bool) *Publisher { t.Helper() publisher, cleanup, err := NewPublisher(config.Config{ KafkaBrokers: []string{unreachableBroker(t)}, KafkaEventsTopic: testTopic, KafkaEventsTopicPartitions: 1, KafkaEventsTopicReplicationFactor: 1, KafkaProvisionTopics: provision, RelayProduceTimeout: unitProduceTimeout, }, slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("NewPublisher() error = %v", err) } t.Cleanup(cleanup) return publisher } func TestPublishFailsEveryEventWithinTheProduceTimeoutWhenBrokersAreDown(t *testing.T) { publisher := newUnitPublisher(t, true) events := []outbound.OutboxEvent{testEvent(), testEvent()} events[1].AggregateVersion++ started := time.Now() results := publisher.Publish(context.Background(), events) if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack { t.Fatalf("Publish() took %s, want about the %s produce timeout", elapsed, unitProduceTimeout) } if len(results) != len(events) { t.Fatalf("Publish() returned %d results for %d events", len(results), len(events)) } for index, err := range results { if err == nil { t.Fatalf("event %d acknowledged without a broker", index) } } } func TestPublishReportsAnUnencodableEventWithoutDroppingOthers(t *testing.T) { publisher := newUnitPublisher(t, true) invalid := testEvent() invalid.Payload = []byte(`{`) results := publisher.Publish(context.Background(), []outbound.OutboxEvent{invalid, testEvent()}) if len(results) != 2 || results[0] == nil || results[1] == nil { t.Fatalf("Publish() results = %v, want two errors", results) } if errors.Is(results[0], errNotAcknowledged) { t.Fatalf("encoding failure reported as a timeout: %v", results[0]) } } func TestPublishWithoutEventsDoesNothing(t *testing.T) { publisher := newUnitPublisher(t, true) if results := publisher.Publish(context.Background(), nil); len(results) != 0 { t.Fatalf("Publish(nil) = %v, want no results", results) } } func TestPrepareSkipsProvisioningWhenDisabled(t *testing.T) { publisher := newUnitPublisher(t, false) if err := publisher.Prepare(context.Background()); err != nil { t.Fatalf("Prepare() error = %v, want nil without contacting the broker", err) } } func TestPrepareFailsWithinTheTimeoutWhenBrokersAreDown(t *testing.T) { publisher := newUnitPublisher(t, true) started := time.Now() if err := publisher.Prepare(context.Background()); err == nil { t.Fatal("Prepare() created a topic without a broker") } if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack { t.Fatalf("Prepare() took %s, want about the %s timeout", elapsed, unitProduceTimeout) } } func TestProduceErrorMarksAMissingTopic(t *testing.T) { event := testEvent() for _, cause := range []error{kerr.UnknownTopicOrPartition, fmt.Errorf("load metadata: %w", kerr.UnknownTopicID)} { if err := produceError(event, cause); !errors.Is(err, outbound.ErrEventDestinationMissing) || !errors.Is(err, cause) { t.Fatalf("produceError(%v) = %v, want ErrEventDestinationMissing and the cause", cause, err) } } if err := produceError(event, kerr.NotEnoughReplicas); errors.Is(err, outbound.ErrEventDestinationMissing) { t.Fatalf("produceError(NotEnoughReplicas) = %v, want no missing destination", err) } } func TestLayoutDiffersComparesPartitionsAndExplicitReplication(t *testing.T) { detail := kadm.TopicDetail{Partitions: kadm.PartitionDetails{ 0: {Partition: 0, Replicas: []int32{1, 2, 3}}, 1: {Partition: 1, Replicas: []int32{2, 3, 1}}, }} tests := []struct { name string partitions int32 replicationFactor int16 want bool }{ {name: "same layout", partitions: 2, replicationFactor: 3, want: false}, {name: "broker default replication", partitions: 2, replicationFactor: -1, want: false}, {name: "other partition count", partitions: 3, replicationFactor: -1, want: true}, {name: "other replication factor", partitions: 2, replicationFactor: 1, want: true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { partitions, replicas, differs := layoutDiffers(detail, test.partitions, test.replicationFactor) if differs != test.want || partitions != 2 || replicas != 3 { t.Fatalf("layoutDiffers() = %d, %d, %t; want 2, 3, %t", partitions, replicas, differs, test.want) } }) } }