File size: 2,205 Bytes
811af7f
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
Fix the following issue:

I want the `github.com/8treenet/freedom/infra/kafka` package to provide a stateful Kafka producer API for Freedom applications. The entry point should be `kafka.GetProducer() kafka.Producer`, where `Producer` exposes `Start(addrs []string, config *sarama.Config)`, `NewMsg(topic string, content []byte) *kafka.Msg`, and `Restart() error`; the concrete `*kafka.ProducerImpl` should also support `Close() error` for lifecycle cleanup.

Calling `Start([]string{"127.0.0.1:9092"}, cfg)` should remember the broker addresses and Sarama config for the producer lifecycle, and it should force `cfg.Producer.Return.Errors` and `cfg.Producer.Return.Successes` to `true` so synchronous sends can report their result. After the Freedom application boots with configured broker addresses, publishing `kafka.GetProducer().NewMsg("orders", []byte("paid")).SetMessageKey("order-1").SetHeader(map[string]interface{}{"x-request-id":"r1", "attempt": 2}).Publish()` should send one Sarama producer message to topic `orders`, with value `paid`, key `order-1`, and headers `x-request-id: r1` and `attempt: 2`. If no message key is set, `Publish` should generate a non-empty uppercase UUID-style key with dashes removed before sending.

`Msg.SetHeader` should be chainable and should merge additional header maps into any existing headers. `Msg.GetHeader`, `Msg.SetMessageKey`, and `Msg.GetMessageKey` should expose the current message headers and key consistently before publish. If `Publish` is called before the producer has an initialized Sarama sync producer, it should return an error equivalent to `producer is not initialized` instead of panicking.

I also need producer middleware support through `kafka.InstallMiddleware(...kafka.ProducerHandler)`, where `ProducerHandler` is `func(*kafka.Msg)`. Installed handlers should run in order when `Msg.Publish` calls `Msg.Next`; a handler can call `Next` to continue, call `Stop` to prevent the send, and inspect `IsStopped` or `GetExecution` for message state. `Restart()` should close the current producer connection and then dial again using the stored addresses and config, and `Close()` should be a no-op when no producer connection is active.