Skip to content

add WriterData field to the message struct #1059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Feb 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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