github.com/streamdal/segmentio-kafka-go@v0.4.47-streamdal/findcoordinator_test.go (about) 1 package kafka 2 3 import ( 4 "bufio" 5 "bytes" 6 "context" 7 "errors" 8 "reflect" 9 "strings" 10 "testing" 11 "time" 12 ) 13 14 func TestFindCoordinatorResponseV0(t *testing.T) { 15 item := findCoordinatorResponseV0{ 16 ErrorCode: 2, 17 Coordinator: findCoordinatorResponseCoordinatorV0{ 18 NodeID: 3, 19 Host: "b", 20 Port: 4, 21 }, 22 } 23 24 b := bytes.NewBuffer(nil) 25 w := &writeBuffer{w: b} 26 item.writeTo(w) 27 28 var found findCoordinatorResponseV0 29 remain, err := (&found).readFrom(bufio.NewReader(b), b.Len()) 30 if err != nil { 31 t.Error(err) 32 t.FailNow() 33 } 34 if remain != 0 { 35 t.Errorf("expected 0 remain, got %v", remain) 36 t.FailNow() 37 } 38 if !reflect.DeepEqual(item, found) { 39 t.Error("expected item and found to be the same") 40 t.FailNow() 41 } 42 } 43 44 func TestClientFindCoordinator(t *testing.T) { 45 client, shutdown := newLocalClient() 46 defer shutdown() 47 48 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) 49 defer cancel() 50 resp, err := waitForCoordinatorIndefinitely(ctx, client, &FindCoordinatorRequest{ 51 Addr: client.Addr, 52 Key: "TransactionalID-1", 53 KeyType: CoordinatorKeyTypeTransaction, 54 }) 55 if err != nil { 56 t.Fatal(err) 57 } 58 59 if resp.Coordinator.Host != "localhost" { 60 t.Fatal("Coordinator should be found @ localhost") 61 } 62 } 63 64 // WaitForCoordinatorIndefinitely is a blocking call till a coordinator is found. 65 func waitForCoordinatorIndefinitely(ctx context.Context, c *Client, req *FindCoordinatorRequest) (*FindCoordinatorResponse, error) { 66 resp, err := c.FindCoordinator(ctx, req) 67 68 for shouldRetryfindingCoordinator(resp, err) && ctx.Err() == nil { 69 time.Sleep(1 * time.Second) 70 resp, err = c.FindCoordinator(ctx, req) 71 } 72 return resp, err 73 } 74 75 // Should retry looking for coordinator 76 // Returns true when the test Kafka broker is still setting up. 77 func shouldRetryfindingCoordinator(resp *FindCoordinatorResponse, err error) bool { 78 brokerSetupIncomplete := err != nil && 79 strings.Contains( 80 strings.ToLower(err.Error()), 81 strings.ToLower("unexpected EOF")) 82 coordinatorNotFound := resp != nil && 83 resp.Error != nil && 84 errors.Is(resp.Error, GroupCoordinatorNotAvailable) 85 return brokerSetupIncomplete || coordinatorNotFound 86 }