-
Notifications
You must be signed in to change notification settings - Fork 11
Add kafka connectors (advanced users only) #363
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
Open
adiom-mark
wants to merge
1
commit into
main
Choose a base branch
from
kafka
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
|
|
||
| var _ adiomv1connect.ConnectorServiceHandler = &destConn{} | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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
ProducerMessagewithTopic: ""(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.Topicto a real topic name (Sarama does not infer a default topic for you):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
SyncProducerexample usingProducerMessage{Topic: "my_topic", ...}(Go package docs) (pkg.go.dev)[2] Sarama
RefreshMetadatarejects empty topic and returnsErrInvalidTopic(Sarama client code) (gerrit.opencord.org)Citations:
🏁 Script executed:
Repository: adiom-data/dsync
Length of output: 1865
🏁 Script executed:
Repository: adiom-data/dsync
Length of output: 42
🏁 Script executed:
Repository: adiom-data/dsync
Length of output: 1234
Add validation to ensure topic is configured before publishing.
Sarama's
ProducerMessagerequires a non-emptyTopicfield. IfdefaultTopicis empty and the namespace is not mapped innamespaceToTopic, thetopicvariable remains empty, causing a runtime error whenSendMessages()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
🤖 Prompt for AI Agents