forked from openware/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomms_relayer.go
95 lines (82 loc) · 2.23 KB
/
comms_relayer.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
package engine
import (
"errors"
"fmt"
"sync/atomic"
"github.com/thrasher-corp/gocryptotrader/communications"
"github.com/thrasher-corp/gocryptotrader/communications/base"
"github.com/thrasher-corp/gocryptotrader/engine/subsystem"
"github.com/thrasher-corp/gocryptotrader/log"
)
// commsManager starts the NTP manager
type commsManager struct {
started int32
shutdown chan struct{}
relayMsg chan base.Event
comms *communications.Communications
}
func (c *commsManager) Started() bool {
return atomic.LoadInt32(&c.started) == 1
}
func (c *commsManager) Start() (err error) {
if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
return fmt.Errorf("communications manager %w", subsystem.ErrSubSystemAlreadyStarted)
}
defer func() {
if err != nil {
atomic.CompareAndSwapInt32(&c.started, 1, 0)
}
}()
log.Debugln(log.CommunicationMgr, "Communications manager starting...")
commsCfg := Bot.Config.GetCommunicationsConfig()
c.comms, err = communications.NewComm(&commsCfg)
if err != nil {
return err
}
c.shutdown = make(chan struct{})
c.relayMsg = make(chan base.Event)
go c.run()
log.Debugln(log.CommunicationMgr, "Communications manager started.")
return nil
}
func (c *commsManager) GetStatus() (map[string]base.CommsStatus, error) {
if !c.Started() {
return nil, errors.New("communications manager not started")
}
return c.comms.GetStatus(), nil
}
func (c *commsManager) Stop() error {
if atomic.LoadInt32(&c.started) == 0 {
return fmt.Errorf("communications manager %w", subsystem.ErrSubSystemNotStarted)
}
defer func() {
atomic.CompareAndSwapInt32(&c.started, 1, 0)
}()
close(c.shutdown)
log.Debugln(log.CommunicationMgr, "Communications manager shutting down...")
return nil
}
func (c *commsManager) PushEvent(evt base.Event) {
if !c.Started() {
return
}
select {
case c.relayMsg <- evt:
default:
log.Errorf(log.CommunicationMgr, "Failed to send, no receiver when pushing event [%v]", evt)
}
}
func (c *commsManager) run() {
defer func() {
// TO-DO shutdown comms connections for connected services (Slack etc)
log.Debugln(log.CommunicationMgr, "Communications manager shutdown.")
}()
for {
select {
case msg := <-c.relayMsg:
c.comms.PushEvent(msg)
case <-c.shutdown:
return
}
}
}