Skip to content

Commit

Permalink
add WriterData field to the message struct (#1059)
Browse files Browse the repository at this point in the history
  • Loading branch information
3AceShowHand committed Feb 17, 2023
1 parent 172fe75 commit bf8775e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
5 changes: 5 additions & 0 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ type Message struct {
Value []byte
Headers []Header

// This field is used to hold arbitrary data you wish to include, so it
// will be available when handle it on the Writer's `Completion` method,
// this support the application can do any post operation on each message.
WriterData interface{}

// If not set at the creation, Time will be automatically set when
// writing the message.
Time time.Time
Expand Down
43 changes: 43 additions & 0 deletions writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ func TestWriter(t *testing.T) {
scenario: "test default configuration values",
function: testWriterDefaults,
},
{
scenario: "test write message with writer data",
function: testWriteMessageWithWriterData,
},
}

for _, test := range tests {
Expand Down Expand Up @@ -719,6 +723,45 @@ func testWriterUnexpectedMessageTopic(t *testing.T) {
}
}

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.
Expand Down

0 comments on commit bf8775e

Please sign in to comment.