1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
|
package kafka
import (
"context"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/segmentio/kafka-go/sasl/plain"
)
func TestBatchQueue(t *testing.T) {
tests := []struct {
scenario string
function func(*testing.T)
}{
{
scenario: "the remaining items in a queue can be gotten after closing",
function: testBatchQueueGetWorksAfterClose,
},
{
scenario: "putting into a closed queue fails",
function: testBatchQueuePutAfterCloseFails,
},
{
scenario: "putting into a queue awakes a goroutine in a get call",
function: testBatchQueuePutWakesSleepingGetter,
},
}
for _, test := range tests {
testFunc := test.function
t.Run(test.scenario, func(t *testing.T) {
t.Parallel()
testFunc(t)
})
}
}
func testBatchQueuePutWakesSleepingGetter(t *testing.T) {
bq := newBatchQueue(10)
var wg sync.WaitGroup
ready := make(chan struct{})
var batch *writeBatch
wg.Add(1)
go func() {
defer wg.Done()
close(ready)
batch = bq.Get()
}()
<-ready
bq.Put(newWriteBatch(time.Now(), time.Hour*100))
wg.Wait()
if batch == nil {
t.Fatal("got nil batch")
}
}
func testBatchQueuePutAfterCloseFails(t *testing.T) {
bq := newBatchQueue(10)
bq.Close()
if put := bq.Put(newWriteBatch(time.Now(), time.Hour*100)); put {
t.Fatal("put batch into closed queue")
}
}
func testBatchQueueGetWorksAfterClose(t *testing.T) {
bq := newBatchQueue(10)
enqueueBatches := []*writeBatch{
newWriteBatch(time.Now(), time.Hour*100),
newWriteBatch(time.Now(), time.Hour*100),
}
for _, batch := range enqueueBatches {
put := bq.Put(batch)
if !put {
t.Fatal("failed to put batch into queue")
}
}
bq.Close()
batchesGotten := 0
for batchesGotten != 2 {
dequeueBatch := bq.Get()
if dequeueBatch == nil {
t.Fatalf("no batch returned from get")
}
batchesGotten++
}
}
func TestWriter(t *testing.T) {
tests := []struct {
scenario string
function func(*testing.T)
}{
{
scenario: "closing a writer right after creating it returns promptly with no error",
function: testWriterClose,
},
{
scenario: "writing 1 message through a writer using round-robin balancing produces 1 message to the first partition",
function: testWriterRoundRobin1,
},
{
scenario: "running out of max attempts should return an error",
function: testWriterMaxAttemptsErr,
},
{
scenario: "writing a message larger then the max bytes should return an error",
function: testWriterMaxBytes,
},
{
scenario: "writing a batch of message based on batch byte size",
function: testWriterBatchBytes,
},
{
scenario: "writing a batch of messages",
function: testWriterBatchSize,
},
{
scenario: "writing messages with a small batch byte size",
function: testWriterSmallBatchBytes,
},
{
scenario: "writing messages with headers",
function: testWriterBatchBytesHeaders,
},
{
scenario: "setting a non default balancer on the writer",
function: testWriterSetsRightBalancer,
},
{
scenario: "setting RequiredAcks to None in Writer does not cause a panic",
function: testWriterRequiredAcksNone,
},
{
scenario: "writing messages to multiple topics",
function: testWriterMultipleTopics,
},
{
scenario: "writing messages without specifying a topic",
function: testWriterMissingTopic,
},
{
scenario: "specifying topic for message when already set for writer",
function: testWriterUnexpectedMessageTopic,
},
{
scenario: "writing a message to an invalid partition",
function: testWriterInvalidPartition,
},
{
scenario: "writing a message to a non-existent topic creates the topic",
function: testWriterAutoCreateTopic,
},
{
scenario: "terminates on an attempt to write a message to a nonexistent topic",
function: testWriterTerminateMissingTopic,
},
{
scenario: "writing a message with SASL Plain authentication",
function: testWriterSasl,
},
{
scenario: "test default configuration values",
function: testWriterDefaults,
},
{
scenario: "test default stats values",
function: testWriterDefaultStats,
},
{
scenario: "test stats values with override config",
function: testWriterOverrideConfigStats,
},
{
scenario: "test write message with writer data",
function: testWriteMessageWithWriterData,
},
}
for _, test := range tests {
testFunc := test.function
t.Run(test.scenario, func(t *testing.T) {
t.Parallel()
testFunc(t)
})
}
}
func newTestWriter(config WriterConfig) *Writer {
if len(config.Brokers) == 0 {
config.Brokers = []string{"localhost:9092"}
}
return NewWriter(config)
}
func testWriterClose(t *testing.T) {
const topic = "test-writer-0"
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
})
if err := w.Close(); err != nil {
t.Error(err)
}
}
func testWriterRequiredAcksNone(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
transport := &Transport{}
defer transport.CloseIdleConnections()
writer := &Writer{
Addr: TCP("localhost:9092"),
Topic: topic,
Balancer: &RoundRobin{},
RequiredAcks: RequireNone,
Transport: transport,
}
defer writer.Close()
msg := Message{
Key: []byte("ThisIsAKey"),
Value: []byte("Test message for required acks test"),
}
err := writer.WriteMessages(context.Background(), msg)
if err != nil {
t.Fatal(err)
}
}
func testWriterSetsRightBalancer(t *testing.T) {
const topic = "test-writer-1"
balancer := &CRC32Balancer{}
w := newTestWriter(WriterConfig{
Topic: topic,
Balancer: balancer,
})
defer w.Close()
if w.Balancer != balancer {
t.Errorf("Balancer not set correctly")
}
}
func testWriterRoundRobin1(t *testing.T) {
const topic = "test-writer-1"
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
offset, err := readOffset(topic, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Topic: topic,
Balancer: &RoundRobin{},
})
defer w.Close()
if err := w.WriteMessages(context.Background(), Message{
Value: []byte("Hello World!"),
}); err != nil {
t.Error(err)
return
}
msgs, err := readPartition(topic, 0, offset)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs) != 1 {
t.Error("bad messages in partition", msgs)
return
}
for _, m := range msgs {
if string(m.Value) != "Hello World!" {
t.Error("bad messages in partition", msgs)
break
}
}
}
func TestValidateWriter(t *testing.T) {
tests := []struct {
config WriterConfig
errorOccured bool
}{
{config: WriterConfig{}, errorOccured: true},
{config: WriterConfig{Brokers: []string{"broker1", "broker2"}}, errorOccured: false},
{config: WriterConfig{Brokers: []string{"broker1"}, Topic: "topic1"}, errorOccured: false},
}
for _, test := range tests {
err := test.config.Validate()
if test.errorOccured && err == nil {
t.Fail()
}
if !test.errorOccured && err != nil {
t.Fail()
}
}
}
func testWriterMaxAttemptsErr(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Brokers: []string{"localhost:9999"}, // nothing is listening here
Topic: topic,
MaxAttempts: 3,
Balancer: &RoundRobin{},
})
defer w.Close()
if err := w.WriteMessages(context.Background(), Message{
Value: []byte("Hello World!"),
}); err == nil {
t.Error("expected error")
return
}
}
func testWriterMaxBytes(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
BatchBytes: 25,
})
defer w.Close()
if err := w.WriteMessages(context.Background(), Message{
Value: []byte("Hi"),
}); err != nil {
t.Error(err)
return
}
firstMsg := []byte("Hello World!")
secondMsg := []byte("LeftOver!")
msgs := []Message{
{
Value: firstMsg,
},
{
Value: secondMsg,
},
}
if err := w.WriteMessages(context.Background(), msgs...); err == nil {
t.Error("expected error")
return
} else if err != nil {
var e MessageTooLargeError
switch {
case errors.As(err, &e):
if string(e.Message.Value) != string(firstMsg) {
t.Errorf("unxpected returned message. Expected: %s, Got %s", firstMsg, e.Message.Value)
return
}
if len(e.Remaining) != 1 {
t.Error("expected remaining errors; found none")
return
}
if string(e.Remaining[0].Value) != string(secondMsg) {
t.Errorf("unxpected returned message. Expected: %s, Got %s", secondMsg, e.Message.Value)
return
}
default:
t.Errorf("unexpected error: %s", err)
return
}
}
}
// readOffset gets the latest offset for the given topic/partition.
func readOffset(topic string, partition int) (offset int64, err error) {
var conn *Conn
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if conn, err = DialLeader(ctx, "tcp", "localhost:9092", topic, partition); err != nil {
err = fmt.Errorf("readOffset, DialLeader: %w", err)
return
}
defer conn.Close()
offset, err = conn.ReadLastOffset()
if err != nil {
err = fmt.Errorf("readOffset, conn.ReadLastOffset: %w", err)
}
return
}
func readPartition(topic string, partition int, offset int64) (msgs []Message, err error) {
var conn *Conn
if conn, err = DialLeader(context.Background(), "tcp", "localhost:9092", topic, partition); err != nil {
return
}
defer conn.Close()
conn.Seek(offset, SeekAbsolute)
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
batch := conn.ReadBatch(0, 1000000000)
defer batch.Close()
for {
var msg Message
if msg, err = batch.ReadMessage(); err != nil {
if errors.Is(err, io.EOF) {
err = nil
}
return
}
msgs = append(msgs, msg)
}
}
func testWriterBatchBytes(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
offset, err := readOffset(topic, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Topic: topic,
BatchBytes: 50,
BatchTimeout: math.MaxInt32 * time.Second,
Balancer: &RoundRobin{},
})
defer w.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := w.WriteMessages(ctx, []Message{
{Value: []byte("M0")}, // 25 Bytes
{Value: []byte("M1")}, // 25 Bytes
{Value: []byte("M2")}, // 25 Bytes
{Value: []byte("M3")}, // 25 Bytes
}...); err != nil {
t.Error(err)
return
}
if w.Stats().Writes != 2 {
t.Error("didn't create expected batches")
return
}
msgs, err := readPartition(topic, 0, offset)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs) != 4 {
t.Error("bad messages in partition", msgs)
return
}
for i, m := range msgs {
if string(m.Value) == "M"+strconv.Itoa(i) {
continue
}
t.Error("bad messages in partition", string(m.Value))
}
}
func testWriterBatchSize(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
offset, err := readOffset(topic, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Topic: topic,
BatchSize: 2,
BatchTimeout: math.MaxInt32 * time.Second,
Balancer: &RoundRobin{},
})
defer w.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := w.WriteMessages(ctx, []Message{
{Value: []byte("Hi")}, // 24 Bytes
{Value: []byte("By")}, // 24 Bytes
}...); err != nil {
t.Error(err)
return
}
if w.Stats().Writes > 1 {
t.Error("didn't batch messages")
return
}
msgs, err := readPartition(topic, 0, offset)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs) != 2 {
t.Error("bad messages in partition", msgs)
return
}
for _, m := range msgs {
if string(m.Value) == "Hi" || string(m.Value) == "By" {
continue
}
t.Error("bad messages in partition", msgs)
}
}
func testWriterSmallBatchBytes(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
offset, err := readOffset(topic, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Topic: topic,
BatchBytes: 25,
BatchTimeout: 50 * time.Millisecond,
Balancer: &RoundRobin{},
})
defer w.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := w.WriteMessages(ctx, []Message{
{Value: []byte("Hi")}, // 24 Bytes
{Value: []byte("By")}, // 24 Bytes
}...); err != nil {
t.Error(err)
return
}
ws := w.Stats()
if ws.Writes != 2 {
t.Error("didn't batch messages; Writes: ", ws.Writes)
return
}
msgs, err := readPartition(topic, 0, offset)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs) != 2 {
t.Error("bad messages in partition", msgs)
return
}
for _, m := range msgs {
if string(m.Value) == "Hi" || string(m.Value) == "By" {
continue
}
t.Error("bad messages in partition", msgs)
}
}
func testWriterBatchBytesHeaders(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
offset, err := readOffset(topic, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Topic: topic,
BatchBytes: 100,
BatchTimeout: 50 * time.Millisecond,
Balancer: &RoundRobin{},
})
defer w.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := w.WriteMessages(ctx, []Message{
{
Value: []byte("Hello World 1"),
Headers: []Header{
{Key: "User-Agent", Value: []byte("abc/xyz")},
},
},
{
Value: []byte("Hello World 2"),
Headers: []Header{
{Key: "User-Agent", Value: []byte("abc/xyz")},
},
},
}...); err != nil {
t.Error(err)
return
}
ws := w.Stats()
if ws.Writes != 2 {
t.Error("didn't batch messages; Writes: ", ws.Writes)
return
}
msgs, err := readPartition(topic, 0, offset)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs) != 2 {
t.Error("bad messages in partition", msgs)
return
}
for _, m := range msgs {
if strings.HasPrefix(string(m.Value), "Hello World") {
continue
}
t.Error("bad messages in partition", msgs)
}
}
func testWriterMultipleTopics(t *testing.T) {
topic1 := makeTopic()
createTopic(t, topic1, 1)
defer deleteTopic(t, topic1)
offset1, err := readOffset(topic1, 0)
if err != nil {
t.Fatal(err)
}
topic2 := makeTopic()
createTopic(t, topic2, 1)
defer deleteTopic(t, topic2)
offset2, err := readOffset(topic2, 0)
if err != nil {
t.Fatal(err)
}
w := newTestWriter(WriterConfig{
Balancer: &RoundRobin{},
})
defer w.Close()
msg1 := Message{Topic: topic1, Value: []byte("Hello")}
msg2 := Message{Topic: topic2, Value: []byte("World")}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := w.WriteMessages(ctx, msg1, msg2); err != nil {
t.Error(err)
return
}
ws := w.Stats()
if ws.Writes != 2 {
t.Error("didn't batch messages; Writes: ", ws.Writes)
return
}
msgs1, err := readPartition(topic1, 0, offset1)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs1) != 1 {
t.Error("bad messages in partition", msgs1)
return
}
if string(msgs1[0].Value) != "Hello" {
t.Error("bad message in partition", msgs1)
}
msgs2, err := readPartition(topic2, 0, offset2)
if err != nil {
t.Error("error reading partition", err)
return
}
if len(msgs2) != 1 {
t.Error("bad messages in partition", msgs2)
return
}
if string(msgs2[0].Value) != "World" {
t.Error("bad message in partition", msgs2)
}
}
func testWriterMissingTopic(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
w := newTestWriter(WriterConfig{
// no topic
Balancer: &RoundRobin{},
})
defer w.Close()
msg := Message{Value: []byte("Hello World")} // no topic
if err := w.WriteMessages(ctx, msg); err == nil {
t.Error("expected error")
return
}
}
func testWriterInvalidPartition(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
MaxAttempts: 1, // only try once to get the error back immediately
Balancer: &staticBalancer{partition: -1}, // intentionally invalid partition
})
defer w.Close()
msg := Message{
Value: []byte("Hello World!"),
}
// this call should return an error and not panic (see issue #517)
if err := w.WriteMessages(ctx, msg); err == nil {
t.Fatal("expected error attempting to write message")
}
}
func testWriterUnexpectedMessageTopic(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
Balancer: &RoundRobin{},
})
defer w.Close()
msg := Message{Topic: "should-fail", Value: []byte("Hello World")}
if err := w.WriteMessages(ctx, msg); err == nil {
t.Error("expected error")
return
}
}
func testWriteMessageWithWriterData(t *testing.T) {
topic := makeTopic()
createTopic(t, topic, 1)
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
Balancer: &RoundRobin{},
})
defer w.Close()
index := 0
w.Completion = func(messages []Message, err error) {
if err != nil {
t.Errorf("unexpected error %v", err)
}
for _, msg := range messages {
meta := msg.WriterData.(int)
if index != meta {
t.Errorf("metadata is not correct, index = %d, writerData = %d", index, meta)
}
index += 1
}
}
msg := Message{Key: []byte("key"), Value: []byte("Hello World")}
for i := 0; i < 5; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
msg.WriterData = i
err := w.WriteMessages(ctx, msg)
if err != nil {
t.Errorf("unexpected error %v", err)
}
}
}
func testWriterAutoCreateTopic(t *testing.T) {
topic := makeTopic()
// Assume it's going to get created.
defer deleteTopic(t, topic)
w := newTestWriter(WriterConfig{
Topic: topic,
Balancer: &RoundRobin{},
})
w.AllowAutoTopicCreation = true
defer w.Close()
msg := Message{Key: []byte("key"), Value: []byte("Hello World")}
var err error
const retries = 5
for i := 0; i < retries; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = w.WriteMessages(ctx, msg)
if errors.Is(err, LeaderNotAvailable) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, UnknownTopicOrPartition) {
time.Sleep(time.Millisecond * 250)
continue
}
if err != nil {
t.Errorf("unexpected error %v", err)
return
}
}
if err != nil {
t.Errorf("unable to create topic %v", err)
}
}
func testWriterTerminateMissingTopic(t *testing.T) {
topic := makeTopic()
transport := &Transport{}
defer transport.CloseIdleConnections()
writer := &Writer{
Addr: TCP("localhost:9092"),
Topic: topic,
Balancer: &RoundRobin{},
RequiredAcks: RequireNone,
AllowAutoTopicCreation: false,
Transport: transport,
}
defer writer.Close()
msg := Message{Value: []byte("FooBar")}
if err := writer.WriteMessages(context.Background(), msg); err == nil {
t.Fatal("Kafka error [3] UNKNOWN_TOPIC_OR_PARTITION is expected")
return
}
}
func testWriterSasl(t *testing.T) {
topic := makeTopic()
defer deleteTopic(t, topic)
dialer := &Dialer{
Timeout: 10 * time.Second,
SASLMechanism: plain.Mechanism{
Username: "adminplain",
Password: "admin-secret",
},
}
w := newTestWriter(WriterConfig{
Dialer: dialer,
Topic: topic,
Brokers: []string{"localhost:9093"},
})
w.AllowAutoTopicCreation = true
defer w.Close()
msg := Message{Key: []byte("key"), Value: []byte("Hello World")}
var err error
const retries = 5
for i := 0; i < retries; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = w.WriteMessages(ctx, msg)
if errors.Is(err, LeaderNotAvailable) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, UnknownTopicOrPartition) {
time.Sleep(time.Millisecond * 250)
continue
}
if err != nil {
t.Errorf("unexpected error %v", err)
return
}
}
if err != nil {
t.Errorf("unable to create topic %v", err)
}
}
func testWriterDefaults(t *testing.T) {
w := &Writer{}
defer w.Close()
if w.writeBackoffMin() != 100*time.Millisecond {
t.Error("Incorrect default min write backoff delay")
}
if w.writeBackoffMax() != 1*time.Second {
t.Error("Incorrect default max write backoff delay")
}
}
func testWriterDefaultStats(t *testing.T) {
w := &Writer{}
defer w.Close()
stats := w.Stats()
if stats.MaxAttempts == 0 {
t.Error("Incorrect default MaxAttempts value")
}
if stats.WriteBackoffMin == 0 {
t.Error("Incorrect default WriteBackoffMin value")
}
if stats.WriteBackoffMax == 0 {
t.Error("Incorrect default WriteBackoffMax value")
}
if stats.MaxBatchSize == 0 {
t.Error("Incorrect default MaxBatchSize value")
}
if stats.BatchTimeout == 0 {
t.Error("Incorrect default BatchTimeout value")
}
if stats.ReadTimeout == 0 {
t.Error("Incorrect default ReadTimeout value")
}
if stats.WriteTimeout == 0 {
t.Error("Incorrect default WriteTimeout value")
}
}
func testWriterOverrideConfigStats(t *testing.T) {
w := &Writer{
MaxAttempts: 6,
WriteBackoffMin: 2,
WriteBackoffMax: 4,
BatchSize: 1024,
BatchTimeout: 16,
ReadTimeout: 24,
WriteTimeout: 32,
}
defer w.Close()
stats := w.Stats()
if stats.MaxAttempts != 6 {
t.Error("Incorrect MaxAttempts value")
}
if stats.WriteBackoffMin != 2 {
t.Error("Incorrect WriteBackoffMin value")
}
if stats.WriteBackoffMax != 4 {
t.Error("Incorrect WriteBackoffMax value")
}
if stats.MaxBatchSize != 1024 {
t.Error("Incorrect MaxBatchSize value")
}
if stats.BatchTimeout != 16 {
t.Error("Incorrect BatchTimeout value")
}
if stats.ReadTimeout != 24 {
t.Error("Incorrect ReadTimeout value")
}
if stats.WriteTimeout != 32 {
t.Error("Incorrect WriteTimeout value")
}
}
type staticBalancer struct {
partition int
}
func (b *staticBalancer) Balance(_ Message, partitions ...int) int {
return b.partition
}
|