-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiplex.go
67 lines (58 loc) · 1.71 KB
/
multiplex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package pubsub
import (
"strings"
"time"
"github.com/pkg/errors"
"github.com/spoke-d/task"
)
// Sub defines a type that the multiplexer can run.
type Sub interface {
// Run creates a task and a schedule to perform the consumption of messages
// sent to the subscriber from the origin.
Run(interval time.Duration) (task.Func, task.Schedule)
}
// Multiplexer forwards multiple subscribers to one singular hub.
func Multiplexer(hub *Hub, subs ...Sub) func(time.Duration) error {
cleanups := make([]func(time.Duration) error, len(subs))
for i, sub := range subs {
cleanups[i], _ = task.Start(sub.Run(Interval))
}
return func(dur time.Duration) error {
var errs []string
for _, cancel := range cleanups {
if err := cancel(dur); err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) == 0 {
return nil
}
return errors.Errorf(strings.Join(errs, ", "))
}
}
// Forward all messages from one hub to another.
// Useful to cross boundaries.
func Forward(hub *Hub, other *Hub) func(time.Duration) error {
sub := hub.SubscribeMatch(Any(), func(topic string, data interface{}) {
done := other.Publish(topic, data)
select {
case <-done:
case <-time.After(time.Millisecond * 10):
}
})
cleanup, _ := task.Start(sub.Run(Interval))
return cleanup
}
// ForwardMatcher all messages that match the matcher from one hub to another.
// Useful to cross boundaries.
func ForwardMatcher(matcher TopicMatcher, hub *Hub, other *Hub) func(time.Duration) error {
sub := hub.SubscribeMatch(matcher, func(topic string, data interface{}) {
done := other.Publish(topic, data)
select {
case <-done:
case <-time.After(time.Millisecond * 10):
}
})
cleanup, _ := task.Start(sub.Run(Interval))
return cleanup
}