Message Router

The Magic Glue of Watermill.

Publishers and Subscribers are rather low-level parts of Watermill.In production use, you’d usually want to use a high-level interface and features like correlation, metrics, poison queue, retrying, throttling, etc..

You also might not want to send an Ack when processing was successful. Sometimes, you’d like to send a message after processing of another message finishes.

To handle these requirements, there is a component named Router.

Watermill Router

Configuration

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. type RouterConfig struct {
  3. // CloseTimeout determines how long router should work for handlers when closing.
  4. CloseTimeout time.Duration
  5. }
  6. func (c *RouterConfig) setDefaults() {
  7. if c.CloseTimeout == 0 {
  8. c.CloseTimeout = time.Second * 30
  9. }
  10. }
  11. func (c RouterConfig) Validate() error {
  12. return nil
  13. }
  14. // ...

Handler

At the beginning you need to implement HandlerFunc:

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // HandlerFunc is function called when message is received.
  3. //
  4. // msg.Ack() is called automatically when HandlerFunc doesn't return error.
  5. // When HandlerFunc returns error, msg.Nack() is called.
  6. // When msg.Ack() was called in handler and HandlerFunc returns error,
  7. // msg.Nack() will be not sent because Ack was already sent.
  8. //
  9. // HandlerFunc's are executed parallel when multiple messages was received
  10. // (because msg.Ack() was sent in HandlerFunc or Subscriber supports multiple consumers).
  11. type HandlerFunc func(msg *Message) ([]*Message, error)
  12. // ...

Next, you have to add a new handler with Router.AddHandler:

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // AddHandler adds a new handler.
  3. //
  4. // handlerName must be unique. For now, it is used only for debugging.
  5. //
  6. // subscribeTopic is a topic from which handler will receive messages.
  7. //
  8. // publishTopic is a topic to which router will produce messages returned by handlerFunc.
  9. // When handler needs to publish to multiple topics,
  10. // it is recommended to just inject Publisher to Handler or implement middleware
  11. // which will catch messages and publish to topic based on metadata for example.
  12. func (r *Router) AddHandler(
  13. handlerName string,
  14. subscribeTopic string,
  15. subscriber Subscriber,
  16. publishTopic string,
  17. publisher Publisher,
  18. handlerFunc HandlerFunc,
  19. ) {
  20. // ...

See an example usage from Getting Started:

Full source: github.com/ThreeDotsLabs/watermill/_examples/basic/3-router/main.go

  1. // ...
  2. router.AddHandler(
  3. "struct_handler", // handler name, must be unique
  4. "incoming_messages_topic", // topic from which we will read events
  5. pubSub,
  6. "outgoing_messages_topic", // topic to which we will publish events
  7. pubSub,
  8. structHandler{}.Handler,
  9. )
  10. // ...

No publisher handler

Not every handler will produce new messages. You can add this kind of handler by using Router.AddNoPublisherHandler:

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // AddNoPublisherHandler adds a new handler.
  3. // This handler cannot return messages.
  4. // When message is returned it will occur an error and Nack will be sent.
  5. //
  6. // handlerName must be unique. For now, it is used only for debugging.
  7. //
  8. // subscribeTopic is a topic from which handler will receive messages.
  9. //
  10. // subscriber is Subscriber from which messages will be consumed.
  11. func (r *Router) AddNoPublisherHandler(
  12. handlerName string,
  13. subscribeTopic string,
  14. subscriber Subscriber,
  15. handlerFunc NoPublishHandlerFunc,
  16. ) {
  17. // ...

Ack

By default, msg.Ack() is called when HanderFunc doesn’t return an error. If an error is returned, msg.Nack() will be called.Because of this, you don’t have to call msg.Ack() or msg.Nack() after a message is processed (you can if you want, of course).

Producing messages

When returning multiple messages from a handler, be aware that most Publisher implementations don’t support atomic publishing of messages. It may end up producing only some of messages and sending msg.Nack() if the broker or the storage are not available.

If it is an issue, consider publishing just one message with each handler.

Running the Router

To run the Router, you need to call Run().

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // Run runs all plugins and handlers and starts subscribing to provided topics.
  3. // This call is blocking while the router is running.
  4. //
  5. // When all handlers have stopped (for example, because subscriptions were closed), the router will also stop.
  6. //
  7. // To stop Run() you should call Close() on the router.
  8. //
  9. // ctx will be propagated to all subscribers.
  10. //
  11. // When all handlers are stopped (for example: because of closed connection), Run() will be also stopped.
  12. func (r *Router) Run(ctx context.Context) (err error) {
  13. // ...

Ensuring that the Router is running

It can be useful to know if the router is running. You can use the Running() method for this.

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // Running is closed when router is running.
  3. // In other words: you can wait till router is running using
  4. // fmt.Println("Starting router")
  5. // go r.Run(ctx)
  6. // <- r.Running()
  7. // fmt.Println("Router is running")
  8. func (r *Router) Running() chan struct{} {
  9. // ...

Execution models

Subscribers can consume either one message at a time or multiple messages in parallel.

  • Single stream of messages is the simplest approach and it means that until a msg.Ack() is called, the subscriberwill not receive any new messages.
  • Multiple message streams are supported only by some subscribers. By subscribing to multiple topic partitions at once,several messages can be consumed in parallel, even previous messages that were not acked (for example, the Kafka subscriberworks like this). Router handles this model by running concurrent HandlerFuncs, one for each partition.See the chosen Pub/Sub documentation for supported execution models.

Middleware

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // HandlerMiddleware allows us to write something like decorators to HandlerFunc.
  3. // It can execute something before handler (for example: modify consumed message)
  4. // or after (modify produced messages, ack/nack on consumed message, handle errors, logging, etc.).
  5. //
  6. // It can be attached to the router by using `AddMiddleware` method.
  7. //
  8. // Example:
  9. // func ExampleMiddleware(h message.HandlerFunc) message.HandlerFunc {
  10. // return func(message *message.Message) ([]*message.Message, error) {
  11. // fmt.Println("executed before handler")
  12. // producedMessages, err := h(message)
  13. // fmt.Println("executed after handler")
  14. //
  15. // return producedMessages, err
  16. // }
  17. // }
  18. type HandlerMiddleware func(h HandlerFunc) HandlerFunc
  19. // ...

A full list of standard middlewares can be found in Middlewares.

Plugin

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

  1. // ...
  2. // RouterPlugin is function which is executed on Router start.
  3. type RouterPlugin func(*Router) error
  4. // ...

A full list of standard plugins can be found in message/router/plugin.