forked from cloudfoundry-attic/go_cfmessagebus
/
nats.go
187 lines (150 loc) · 4.1 KB
/
nats.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package cfmessagebus
import (
"errors"
"fmt"
nats "github.com/cloudfoundry/yagnats"
"github.com/nu7hatch/gouuid"
"math/rand"
"time"
)
type NatsAdapter struct {
client *nats.Client
host string
user string
port int
password string
subscriptions []*Subscription
rand *rand.Rand
connectedCallback func()
logger Logger
}
type Subscription struct {
subject string
callback func([]byte)
reply func([]byte) []byte
id int
}
func NewNatsAdapter() *NatsAdapter {
return &NatsAdapter{}
}
func (adapter *NatsAdapter) Configure(host string, port int, user string, password string) {
adapter.host = host
adapter.port = port
adapter.user = user
adapter.password = password
}
func (adapter *NatsAdapter) Connect() error {
return adapter.connect()
}
func (adapter *NatsAdapter) OnConnect(callback func()) {
adapter.connectedCallback = callback
}
func (adapter *NatsAdapter) SetLogger(logger Logger) {
adapter.logger = logger
}
func (adapter *NatsAdapter) connect() error {
addr := fmt.Sprintf("%s:%d", adapter.host, adapter.port)
client := nats.NewClient()
client.ConnectedCallback = func() {
if adapter.connectedCallback != nil {
adapter.connectedCallback()
}
}
if adapter.logger != nil {
client.Logger = adapter.logger
}
err := client.Connect(&nats.ConnectionInfo{
Addr: addr,
Username: adapter.user,
Password: adapter.password,
})
if err != nil {
return err
}
adapter.client = client
adapter.rand = rand.New(rand.NewSource(time.Now().UnixNano()))
for _, sub := range adapter.subscriptions {
subscribeInNats(adapter, sub)
}
return nil
}
func (adapter *NatsAdapter) createInbox() (string, error) {
uuid, err := uuid.NewV4()
if err != nil {
return "", err
}
return fmt.Sprintf("_INBOX.%s", uuid), nil
}
func (adapter *NatsAdapter) Subscribe(subject string, callback func(payload []byte)) error {
sub := &Subscription{subject: subject, callback: callback}
adapter.subscriptions = append(adapter.subscriptions, sub)
if adapter.client != nil {
subscribeInNats(adapter, sub)
} else {
return errors.New("No connection to Nats. Caching subscription...")
}
return nil
}
func (adapter *NatsAdapter) UnsubscribeAll() error {
return withConnectionCheck(adapter.client, func() error {
for _, sub := range adapter.subscriptions {
adapter.client.UnsubscribeAll(sub.subject)
}
adapter.subscriptions = []*Subscription{}
return nil
})
}
func (adapter *NatsAdapter) Publish(subject string, message []byte) error {
return withConnectionCheck(adapter.client, func() error {
return adapter.client.Publish(subject, message)
})
}
func (adapter *NatsAdapter) Request(subject string, message []byte, callback func(payload []byte)) error {
return withConnectionCheck(adapter.client, func() error {
inbox, err := adapter.createInbox()
if err != nil {
return err
}
adapter.Subscribe(inbox, callback)
return adapter.client.PublishWithReplyTo(subject, inbox, message)
})
}
func (adapter *NatsAdapter) RespondToChannel(subject string, replyCallback func([]byte) []byte) error {
sub := &Subscription{subject: subject, reply: replyCallback}
adapter.subscriptions = append(adapter.subscriptions, sub)
if adapter.client != nil {
subscribeInNats(adapter, sub)
} else {
return errors.New("No connection to Nats. Caching subscription...")
}
return nil
}
func (adapter *NatsAdapter) Ping() bool {
if adapter.client == nil {
return false
} else {
return adapter.client.Ping()
}
}
func withConnectionCheck(connection *nats.Client, callback func() error) error {
if connection == nil {
return errors.New("No connection to Nats")
}
return callback()
}
func subscribeInNats(adapter *NatsAdapter, sub *Subscription) {
sid, _ := adapter.client.Subscribe(sub.subject, func(msg *nats.Message) {
if sub.reply != nil {
adapter.replyToMessage(msg, sub.reply)
} else {
sub.callback([]byte(msg.Payload))
}
})
sub.id = sid
}
func (a *NatsAdapter) replyToMessage(msg *nats.Message, callback func([]byte) []byte) {
if msg.ReplyTo == "" {
return
}
a.client.Publish(msg.ReplyTo, callback([]byte(msg.Payload)))
}