Skip to content

Commit

Permalink
Add Timeout middleware (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
m110 authored Jun 1, 2019
1 parent ea9702a commit 1925b80
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions message/router/middleware/timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package middleware

import (
"context"
"time"

"github.com/ThreeDotsLabs/watermill/message"
)

func Timeout(timeout time.Duration) func(message.HandlerFunc) message.HandlerFunc {
return func(h message.HandlerFunc) message.HandlerFunc {
return func(msg *message.Message) ([]*message.Message, error) {
ctx, cancel := context.WithTimeout(msg.Context(), timeout)
defer func() {
cancel()
}()

msg.SetContext(ctx)
return h(msg)
}
}
}
30 changes: 30 additions & 0 deletions message/router/middleware/timeout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package middleware_test

import (
"errors"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/ThreeDotsLabs/watermill/message"
"github.com/ThreeDotsLabs/watermill/message/router/middleware"
)

func TestTimeout(t *testing.T) {
timeout := middleware.Timeout(time.Millisecond * 10)

h := timeout(func(msg *message.Message) ([]*message.Message, error) {
delay := time.After(time.Millisecond * 100)

select {
case <-msg.Context().Done():
return nil, nil
case <-delay:
return nil, errors.New("timeout did not occur")
}
})

_, err := h(message.NewMessage("any-uuid", nil))
require.NoError(t, err)
}

0 comments on commit 1925b80

Please # to comment.