Skip to content
Open
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
157 changes: 157 additions & 0 deletions connectors/kafka/dest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package kafka

import (
"context"
"errors"
"fmt"
"log/slog"

"connectrpc.com/connect"
"github.com/IBM/sarama"
adiomv1 "github.com/adiom-data/dsync/gen/adiom/v1"
"github.com/adiom-data/dsync/gen/adiom/v1/adiomv1connect"
"google.golang.org/protobuf/proto"
)

func DsyncMessageToNamespace(m *sarama.ConsumerMessage, _ map[string]struct{}) (string, error) {
for _, h := range m.Headers {
if string(h.Key) == "ns" {
return string(h.Value), nil
}
}
return "", fmt.Errorf("missing namespace header")
}

func DsyncMessageToUpdate(m *sarama.ConsumerMessage, _ map[string]struct{}) (*adiomv1.Update, string, error) {
update := &adiomv1.Update{}
if err := proto.Unmarshal(m.Value, update); err != nil {
return nil, "", fmt.Errorf("err unmarshalling proto: %w", err)
}
for _, h := range m.Headers {
if string(h.Key) == "ns" {
return update, string(h.Value), nil
}
}

return nil, "", fmt.Errorf("missing namespace header")
}

type destConn struct {
adiomv1connect.UnimplementedConnectorServiceHandler
producer sarama.SyncProducer
namespaceToTopic map[string]string
defaultTopic string
dataType adiomv1.DataType
}

func NewDestKafka(brokers []string, defaultTopic string, namespacesToTopic map[string]string, user string, password string, dataType adiomv1.DataType) (*destConn, error) {
cfg := sarama.NewConfig()
if user != "" {
cfg.Net.TLS.Enable = true
cfg.Net.SASL.Enable = true
cfg.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypePlaintext)
cfg.Net.SASL.User = user
cfg.Net.SASL.Password = password
}
cfg.Producer.RequiredAcks = sarama.WaitForAll
cfg.Producer.Return.Successes = true
cfg.Producer.Partitioner = sarama.NewHashPartitioner
producer, err := sarama.NewSyncProducer(brokers, cfg)
if err != nil {
return nil, fmt.Errorf("err creating kafka producer: %w", err)
}
return &destConn{
producer: producer,
namespaceToTopic: namespacesToTopic,
defaultTopic: defaultTopic,
dataType: dataType,
}, nil
}

func (d *destConn) Teardown() {
_ = d.producer.Close()
}

// GeneratePlan implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) GeneratePlan(context.Context, *connect.Request[adiomv1.GeneratePlanRequest]) (*connect.Response[adiomv1.GeneratePlanResponse], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.ErrUnsupported)
}

// GetInfo implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) GetInfo(context.Context, *connect.Request[adiomv1.GetInfoRequest]) (*connect.Response[adiomv1.GetInfoResponse], error) {
supported := []adiomv1.DataType{d.dataType}
return connect.NewResponse(&adiomv1.GetInfoResponse{
Id: "kafka-dest",
DbType: "kafka-dest",
Capabilities: &adiomv1.Capabilities{
Sink: &adiomv1.Capabilities_Sink{
SupportedDataTypes: supported,
},
},
}), nil
}

// GetNamespaceMetadata implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) GetNamespaceMetadata(context.Context, *connect.Request[adiomv1.GetNamespaceMetadataRequest]) (*connect.Response[adiomv1.GetNamespaceMetadataResponse], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.ErrUnsupported)
}

// ListData implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) ListData(context.Context, *connect.Request[adiomv1.ListDataRequest]) (*connect.Response[adiomv1.ListDataResponse], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.ErrUnsupported)
}

// StreamLSN implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) StreamLSN(context.Context, *connect.Request[adiomv1.StreamLSNRequest], *connect.ServerStream[adiomv1.StreamLSNResponse]) error {
return connect.NewError(connect.CodeUnimplemented, errors.ErrUnsupported)
}

// StreamUpdates implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) StreamUpdates(context.Context, *connect.Request[adiomv1.StreamUpdatesRequest], *connect.ServerStream[adiomv1.StreamUpdatesResponse]) error {
return connect.NewError(connect.CodeUnimplemented, errors.ErrUnsupported)
}

// WriteData implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) WriteData(context.Context, *connect.Request[adiomv1.WriteDataRequest]) (*connect.Response[adiomv1.WriteDataResponse], error) {
slog.Warn("kafka connector does not support initial sync, ignoring")
return connect.NewResponse(&adiomv1.WriteDataResponse{}), nil
}

func key(id []*adiomv1.BsonValue) []byte {
var res []byte
for _, part := range id {
res = append(res, part.GetData()...)
}
return res
}

// WriteUpdates implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) WriteUpdates(ctx context.Context, r *connect.Request[adiomv1.WriteUpdatesRequest]) (*connect.Response[adiomv1.WriteUpdatesResponse], error) {
topic := d.defaultTopic
ns := r.Msg.GetNamespace()
header := []sarama.RecordHeader{{Key: []byte("ns"), Value: []byte(ns)}}
if namespaceTopic, ok := d.namespaceToTopic[ns]; ok {
topic = namespaceTopic
}
var messages []*sarama.ProducerMessage
for _, update := range r.Msg.GetUpdates() {
b, err := proto.Marshal(update)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err marshalling proto: %w", err))
}
msg := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.ByteEncoder(key(update.GetId())),
Value: sarama.ByteEncoder(b),
Headers: header,
Partition: -1,
}
messages = append(messages, msg)
}
if err := d.producer.SendMessages(messages); err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err sending message: %w", err))
}
return connect.NewResponse(&adiomv1.WriteUpdatesResponse{}), nil
}
Comment on lines +120 to +155
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Sarama ProducerMessage Topic empty string requirement error

💡 Result:

In Sarama (Go Kafka client), a producer message must have a non-empty topic name. If you send a ProducerMessage with Topic: "" (or you end up calling internal metadata refresh with an empty topic), Sarama will fail with an “empty topic” / ErrInvalidTopic-style error because it explicitly rejects empty topic strings. [1], [2]

Fix: ensure every produced message sets ProducerMessage.Topic to a real topic name (Sarama does not infer a default topic for you):

msg := &sarama.ProducerMessage{
    Topic: "my_topic",
    Value: sarama.StringEncoder("hello"),
}
_, _, err := producer.SendMessage(msg)

Also verify any config/env/templating you use to build the topic isn’t producing "" at runtime (e.g., missing env var, empty string after trim, etc.). [1]

Sources:
[1] Sarama SyncProducer example using ProducerMessage{Topic: "my_topic", ...} (Go package docs) (pkg.go.dev)
[2] Sarama RefreshMetadata rejects empty topic and returns ErrInvalidTopic (Sarama client code) (gerrit.opencord.org)

Citations:


🏁 Script executed:

# Search for how defaultTopic and namespaceToTopic are initialized
rg -A 3 -B 3 "defaultTopic|namespaceToTopic" connectors/kafka/

Repository: adiom-data/dsync

Length of output: 1865


🏁 Script executed:

# Look for other topic validation patterns in the codebase
rg "topic.*=.*\"\"" connectors/kafka/ -A 3

Repository: adiom-data/dsync

Length of output: 42


🏁 Script executed:

# Check if there's any topic validation or initialization code
rg "Topic" connectors/kafka/dest.go -B 2 -A 2

Repository: adiom-data/dsync

Length of output: 1234


Add validation to ensure topic is configured before publishing.

Sarama's ProducerMessage requires a non-empty Topic field. If defaultTopic is empty and the namespace is not mapped in namespaceToTopic, the topic variable remains empty, causing a runtime error when SendMessages() is called. Add a guard to fail fast with a clear error message.

Proposed fix
 	topic := d.defaultTopic
 	ns := r.Msg.GetNamespace()
 	header := []sarama.RecordHeader{{Key: []byte("ns"), Value: []byte(ns)}}
 	if namespaceTopic, ok := d.namespaceToTopic[ns]; ok {
 		topic = namespaceTopic
 	}
+	if topic == "" {
+		return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("kafka topic is required"))
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func key(id []*adiomv1.BsonValue) []byte {
var res []byte
for _, part := range id {
res = append(res, part.GetData()...)
}
return res
}
// WriteUpdates implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) WriteUpdates(ctx context.Context, r *connect.Request[adiomv1.WriteUpdatesRequest]) (*connect.Response[adiomv1.WriteUpdatesResponse], error) {
topic := d.defaultTopic
ns := r.Msg.GetNamespace()
header := []sarama.RecordHeader{{Key: []byte("ns"), Value: []byte(ns)}}
if namespaceTopic, ok := d.namespaceToTopic[ns]; ok {
topic = namespaceTopic
}
var messages []*sarama.ProducerMessage
for _, update := range r.Msg.GetUpdates() {
b, err := proto.Marshal(update)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err marshalling proto: %w", err))
}
msg := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.ByteEncoder(key(update.GetId())),
Value: sarama.ByteEncoder(b),
Headers: header,
Partition: -1,
}
messages = append(messages, msg)
}
if err := d.producer.SendMessages(messages); err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err sending message: %w", err))
}
return connect.NewResponse(&adiomv1.WriteUpdatesResponse{}), nil
}
func key(id []*adiomv1.BsonValue) []byte {
var res []byte
for _, part := range id {
res = append(res, part.GetData()...)
}
return res
}
// WriteUpdates implements [adiomv1connect.ConnectorServiceHandler].
func (d *destConn) WriteUpdates(ctx context.Context, r *connect.Request[adiomv1.WriteUpdatesRequest]) (*connect.Response[adiomv1.WriteUpdatesResponse], error) {
topic := d.defaultTopic
ns := r.Msg.GetNamespace()
header := []sarama.RecordHeader{{Key: []byte("ns"), Value: []byte(ns)}}
if namespaceTopic, ok := d.namespaceToTopic[ns]; ok {
topic = namespaceTopic
}
if topic == "" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("kafka topic is required"))
}
var messages []*sarama.ProducerMessage
for _, update := range r.Msg.GetUpdates() {
b, err := proto.Marshal(update)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err marshalling proto: %w", err))
}
msg := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.ByteEncoder(key(update.GetId())),
Value: sarama.ByteEncoder(b),
Headers: header,
Partition: -1,
}
messages = append(messages, msg)
}
if err := d.producer.SendMessages(messages); err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("err sending message: %w", err))
}
return connect.NewResponse(&adiomv1.WriteUpdatesResponse{}), nil
}
🤖 Prompt for AI Agents
In `@connectors/kafka/dest.go` around lines 119 - 154, The WriteUpdates handler
(destConn.WriteUpdates) currently may construct sarama.ProducerMessage with an
empty Topic when d.defaultTopic is empty and ns isn't in d.namespaceToTopic; add
validation before creating messages to ensure topic is non-empty (check the
resolved topic variable after choosing namespaceToTopic or defaultTopic) and
return a clear connect.NewError(connect.CodeInvalidArgument or CodeInternal) if
it's empty so SendMessages is never called with a ProducerMessage lacking Topic;
update any error branches to include context (e.g., mentioning namespace and
that no topic was configured) to help debugging.


var _ adiomv1connect.ConnectorServiceHandler = &destConn{}
Loading