github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/components/forwarder/publisher.go (about) 1 package forwarder 2 3 import ( 4 "context" 5 6 "github.com/pkg/errors" 7 8 "github.com/wfusion/gofusion/common/infra/watermill/message" 9 ) 10 11 type PublisherConfig struct { 12 // ForwarderTopic is a topic which the forwarder is listening to. Publisher will send enveloped messages to this topic. 13 // Defaults to `forwarder_topic`. 14 ForwarderTopic string 15 } 16 17 func (c *PublisherConfig) setDefaults() { 18 if c.ForwarderTopic == "" { 19 c.ForwarderTopic = defaultForwarderTopic 20 } 21 } 22 23 func (c *PublisherConfig) Validate() error { 24 if c.ForwarderTopic == "" { 25 return errors.New("empty forwarder topic") 26 } 27 28 return nil 29 } 30 31 // Publisher changes `Publish` method behavior so it wraps a sent message in an envelope 32 // and sends it to the forwarder topic provided in the config. 33 type Publisher struct { 34 wrappedPublisher message.Publisher 35 config PublisherConfig 36 } 37 38 func NewPublisher(publisher message.Publisher, config PublisherConfig) *Publisher { 39 config.setDefaults() 40 41 return &Publisher{ 42 wrappedPublisher: publisher, 43 config: config, 44 } 45 } 46 47 func (p *Publisher) Publish(ctx context.Context, topic string, messages ...*message.Message) error { 48 envelopedMessages := make([]*message.Message, 0, len(messages)) 49 for _, msg := range messages { 50 envelopedMsg, err := wrapMessageInEnvelope(topic, msg) 51 if err != nil { 52 return errors.Wrapf(err, "cannot wrap message, target topic: '%s', uuid: '%s'", topic, msg.UUID) 53 } 54 55 envelopedMessages = append(envelopedMessages, envelopedMsg) 56 } 57 58 if err := p.wrappedPublisher.Publish(ctx, p.config.ForwarderTopic, envelopedMessages...); err != nil { 59 return errors.Wrapf(err, "cannot publish messages to forwarder topic: '%s'", p.config.ForwarderTopic) 60 } 61 62 return nil 63 } 64 65 func (p *Publisher) Close() error { 66 return p.wrappedPublisher.Close() 67 }