-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
101 lines (81 loc) · 2.13 KB
/
main.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package commander
import (
"errors"
"github.com/jeroenrinzema/commander/internal/types"
"github.com/jeroenrinzema/commander/middleware"
)
const (
// DebugEnv os debug env key
DebugEnv = "DEBUG"
)
const (
// BeforeEvent gets called before a action gets taken.
BeforeEvent = "before"
// AfterEvent gets called after a action has been taken.
AfterEvent = "after"
)
var (
// ErrTimeout is returned when a timeout is reached when awaiting a responding event
ErrTimeout = errors.New("timeout reached")
)
// NewClient constructs a new commander client.
// A client is needed to control a collection of groups.
func NewClient(groups ...*Group) (*Client, error) {
middleware := middleware.NewClient()
client := &Client{
UseImpl: middleware,
Groups: groups,
}
appendMiddleware(middleware, groups)
topics := pullTopicsFromGroups(groups)
dialects := groupTopicsByDialect(topics)
for dialect, topics := range dialects {
err := dialect.Open(topics)
if err != nil {
return nil, err
}
}
return client, nil
}
// Client manages the consumers, producers and groups.
type Client struct {
middleware.UseImpl
Groups []*Group
}
// Close closes the consumer and producer
func (client *Client) Close() error {
dialects := make(map[types.Dialect]bool)
for _, group := range client.Groups {
for _, topic := range group.Topics {
if dialects[topic.Dialect()] {
continue
}
topic.Dialect().Close()
dialects[topic.Dialect()] = true
}
}
return nil
}
func pullTopicsFromGroups(groups []*Group) []types.Topic {
returned := []types.Topic{}
for _, group := range groups {
returned = append(returned, group.Topics...)
}
return returned
}
func appendMiddleware(middleware middleware.UseImpl, groups []*Group) {
for _, group := range groups {
group.Middleware = middleware
}
}
func groupTopicsByDialect(topics []types.Topic) map[types.Dialect][]types.Topic {
returned := map[types.Dialect][]types.Topic{}
for _, topic := range topics {
_, has := returned[topic.Dialect()]
if !has {
returned[topic.Dialect()] = []types.Topic{}
}
returned[topic.Dialect()] = append(returned[topic.Dialect()], topic)
}
return returned
}