-
Notifications
You must be signed in to change notification settings - Fork 8
/
nats.go
323 lines (287 loc) · 7.78 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package nats
import (
"context"
"sync"
"github.com/aperturerobotics/bifrost/link"
"github.com/aperturerobotics/bifrost/peer"
"github.com/aperturerobotics/bifrost/protocol"
"github.com/aperturerobotics/bifrost/pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
nats_server "github.com/nats-io/nats-server/v2/server"
nats_client "github.com/nats-io/nats.go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
NatsRouterID = protocol.ID("nats.io/2/router") // nats 2.0 router
NatsClientID = protocol.ID("nats.io/2/client") // nats 2.0 client API
)
// ProtocolIDToStreamType converts a protocol ID to a conn type.
func ProtocolIDToStreamType(id protocol.ID) NatsConnType {
switch id {
case NatsRouterID:
return NatsConnType_NatsConnType_ROUTER
case NatsClientID:
return NatsConnType_NatsConnType_CLIENT
default:
return NatsConnType_NatsConnType_UNKNOWN
}
}
// Nats implements the nats router.
type Nats struct {
// conf is the config
conf *Config
// le is the logger
le *logrus.Entry
// peer contains the peer we are using
peer peer.Peer
// handler is the pubsub handler
handler pubsub.PubSubHandler
// wakeCh wakes the execute loop
wakeCh chan struct{}
// natsServer is the embedded nats server.
natsServer *nats_server.Server
mtx sync.Mutex
incSessions []*streamHandler
// natsClients contains all active nats clients keyed by peer id
natsClients map[string]*natsClient
}
// NewNats constructs a new Nats PubSub router.
func NewNats(
ctx context.Context,
le *logrus.Entry,
handler pubsub.PubSubHandler,
cc *Config,
peer peer.Peer,
) (pubsub.PubSub, error) {
if peer == nil {
return nil, errors.New("nats server requires a peer with a private key")
}
peerPrivKey, err := peer.GetPrivKey(ctx)
if err != nil {
return nil, err
}
kpair, err := NewKeyPair(peerPrivKey, peer.GetPubKey())
if err != nil {
return nil, err
}
peerID := peer.GetPeerID()
serverName := peerID.Pretty()
clusterName := cc.GetClusterName()
if clusterName == "" {
clusterName = string(NatsRouterID)
}
serverOpts := &nats_server.Options{
Cluster: nats_server.ClusterOpts{Name: clusterName},
Logger: le.WithField("peer-id", serverName),
ServerName: serverName,
CustomClientAuthentication: newClientAuth(),
CustomRouterAuthentication: newRouterAuth(),
}
if err := cc.ApplyOptions(serverOpts); err != nil {
return nil, err
}
// Create nats server with Aperture fork
natsServer, err := nats_server.NewServer(
serverOpts,
kpair,
)
if err != nil {
return nil, err
}
return &Nats{
le: le,
conf: cc,
handler: handler,
peer: peer,
natsServer: natsServer,
wakeCh: make(chan struct{}, 1),
natsClients: make(map[string]*natsClient),
}, nil
}
// Execute executes the PubSub routines.
func (m *Nats) Execute(ctx context.Context) error {
m.le.Debug("nats router starting")
go m.natsServer.Start()
defer m.natsServer.WaitForShutdown()
defer m.natsServer.Shutdown()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-m.wakeCh:
}
m.mtx.Lock()
incSess := m.incSessions
m.incSessions = nil
for _, sess := range incSess {
sess.ctx, sess.ctxCancel = context.WithCancel(ctx)
go sess.executeSession()
}
m.mtx.Unlock()
}
}
// AddPeerStream adds a negotiated peer stream.
// Two streams will be negotiated, one outgoing, one incoming.
// The pubsub should communicate over the stream.
func (m *Nats) AddPeerStream(tpl pubsub.PeerLinkTuple, initiator bool, mstrm link.MountedStream) {
le := m.le.WithField("peer", tpl.PeerID.Pretty())
if !mstrm.GetOpenOpts().Encrypted || !mstrm.GetOpenOpts().Reliable {
le.Warn("rejecting unencrypted or unreliable pubsub stream")
mstrm.GetStream().Close()
return
}
protocolID := mstrm.GetProtocolID()
streamType := ProtocolIDToStreamType(protocolID)
if streamType == NatsConnType_NatsConnType_UNKNOWN {
le.
WithField("protocol-id", protocolID).
WithField("stream-type", streamType.String()).
Warn("rejecting unknown protocol id")
mstrm.GetStream().Close()
return
}
sh := &streamHandler{
m: m,
le: le,
tpl: tpl,
peerID: mstrm.GetPeerID(),
mstrm: mstrm,
initiator: initiator,
strmType: streamType,
}
m.mtx.Lock()
m.incSessions = append(m.incSessions, sh)
m.mtx.Unlock()
m.wake()
}
// BuildClient builds a client for the nats server, creating a client connection.
//
// Note: the servers list & dialer will be overwritten.
func (n *Nats) BuildClient(ctx context.Context, privKey crypto.PrivKey, opts ...nats_client.Option) (*nats_client.Conn, error) {
nk, err := NewKeyPair(privKey, privKey.GetPublic())
if err != nil {
return nil, err
}
nkPub, err := nk.PublicKey()
if err != nil {
return nil, err
}
copts := nats_client.GetDefaultOptions()
for _, opt := range opts {
if err := opt(&copts); err != nil {
return nil, err
}
}
copts.CustomDialer = newLocalNatsDialer(n, nk)
copts.Servers = []string{localNatsAddress}
if err := nats_client.Nkey(nkPub, nats_client.SignatureHandler(nk.Sign))(&copts); err != nil {
return nil, err
}
return copts.Connect()
}
// AddSubscription adds a channel subscription, returning a subscription handle.
//
// Uses the router peer private key.
//
// An alternate approach is to use a client connection.
func (n *Nats) AddSubscription(ctx context.Context, privKey crypto.PrivKey, channelID string) (pubsub.Subscription, error) {
n.mtx.Lock()
nc, ncRel, err := n.getOrBuildClient(ctx, privKey)
n.mtx.Unlock()
if err != nil {
return nil, err
}
nsub, err := nc.Conn.SubscribeSync(channelID)
if err != nil {
ncRel()
return nil, err
}
return newSubscription(ctx, n, nc, ncRel, nsub, privKey, channelID), nil
}
// GetOrBuildCommonClient returns the common nats client.
func (n *Nats) GetOrBuildCommonClient(ctx context.Context) (*nats_client.Conn, error) {
npeerID := n.peer.GetPeerID()
npeerPriv, err := n.peer.GetPrivKey(ctx)
if err != nil {
return nil, err
}
npeerPretty := npeerID.Pretty()
n.mtx.Lock()
defer n.mtx.Unlock()
// we create the common client with 1 ref that is never released.
nc, ncOk := n.natsClients[npeerPretty]
if ncOk {
return nc.Conn, nil
}
nc, ncRel, err := n.getOrBuildClient(ctx, npeerPriv)
if err != nil {
return nil, err
}
_ = ncRel // never release the common client
return nc.Conn, nil
}
// getOrBuildClient gets or builds a client adding a reference.
// caller must lock mtx
func (n *Nats) getOrBuildClient(ctx context.Context, privKey crypto.PrivKey) (*natsClient, func(), error) {
npeer, err := peer.IDFromPrivateKey(privKey)
if err != nil {
return nil, nil, err
}
npeerPretty := npeer.Pretty()
nc := n.natsClients[npeerPretty]
if nc != nil {
if !nc.Conn.IsClosed() {
return nc, nc.addRef(), nil
}
nc = nil
delete(n.natsClients, npeerPretty)
}
nconn, err := n.BuildClient(ctx, privKey)
if err != nil {
return nil, nil, err
}
nc = newNatsClient(npeer, nconn)
n.natsClients[npeerPretty] = nc
return nc, nc.addRef(), nil
}
// SubscribeSync passes through to the nats client SubscribeSync call.
func (n *Nats) SubscribeSync(
ctx context.Context,
channelID string,
) (*nats_client.Subscription, *nats_client.Conn, error) {
// TODO: do we need to augment this?
nclient, err := n.GetOrBuildCommonClient(ctx)
if err != nil {
return nil, nil, err
}
sub, err := nclient.SubscribeSync(channelID)
if err != nil {
return nil, nclient, err
}
return sub, nclient, nil
}
// Close closes the pubsub.
func (m *Nats) Close() {
m.mtx.Lock()
for _, s := range m.incSessions {
if s.mstrm != nil {
s.mstrm.GetStream().Close()
}
}
m.incSessions = nil
for id, client := range m.natsClients {
client.Close()
delete(m.natsClients, id)
}
m.mtx.Unlock()
}
// wake wakes the controller
func (m *Nats) wake() {
select {
case m.wakeCh <- struct{}{}:
default:
}
}
// _ is a type assertion
var _ pubsub.PubSub = ((*Nats)(nil))