-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.go
66 lines (57 loc) · 1.81 KB
/
module.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
// Package pubsub is a pubsub module for package Core build upon
// watermill(https://github.com/ThreeDotsLabs/watermill). It allows other modules
// to register pub sub handlers easily via an interface. See example for usage.
package pubsub
import (
"context"
"github.com/DoNewsCode/core/contract"
"github.com/DoNewsCode/core/di"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/go-kit/kit/log"
"github.com/oklog/run"
)
// Provider is an interface that all modules supporting watermill pubsub should
// implement. The router is passed into the ProvidePubSub(), and downstream
// modules should register their handlers to the router.
type Provider interface {
ProvidePubSub(*message.Router)
}
// Module is the base struct for pubsub module.
type Module struct {
container contract.Container
router *message.Router
logger Logger
}
// ModuleIn is the parameters for New.
type ModuleIn struct {
di.In
Container contract.Container
Router *message.Router `optional:"true"`
Logger log.Logger
}
// New constructs a pubsub module.
func New(in ModuleIn) (module Module, err error) {
logger := NewLogger(in.Logger)
if in.Router == nil {
if in.Router, err = message.NewRouter(message.RouterConfig{}, logger); err != nil {
return Module{}, err
}
}
return Module{container: in.Container, router: in.Router, logger: logger}, nil
}
// ProvideRunGroup scans modules from container and collect all pubsubs. It
// starts the pub/sub using the runner mechanism.
func (m Module) ProvideRunGroup(group *run.Group) {
for _, module := range m.container.Modules() {
if provider, ok := module.(Provider); ok {
provider.ProvidePubSub(m.router)
}
}
ctx, cancel := context.WithCancel(context.Background())
group.Add(func() error {
return m.router.Run(ctx)
}, func(err error) {
cancel()
_ = m.router.Close()
})
}