-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmanager.go
422 lines (333 loc) · 9.58 KB
/
manager.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright 2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jsm
import (
"context"
"encoding/json"
"fmt"
"log"
"sort"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/jsm.go/api"
)
type Manager struct {
nc *nats.Conn
timeout time.Duration
trace bool
validator api.StructValidator
sync.Mutex
}
func New(nc *nats.Conn, opts ...Option) (*Manager, error) {
m := &Manager{
nc: nc,
timeout: 5 * time.Second,
}
for _, opt := range opts {
opt(m)
}
if m.nc == nil {
return nil, fmt.Errorf("nats connection not supplied")
}
if m.timeout < 500*time.Millisecond {
m.timeout = 500 * time.Millisecond
}
return m, nil
}
// IsJetStreamEnabled determines if JetStream is enabled for the current account
func (m *Manager) IsJetStreamEnabled() bool {
info, err := m.JetStreamAccountInfo()
if err != nil {
return false
}
if info == nil {
return false
}
return true
}
// JetStreamAccountInfo retrieves information about the current account limits and more
func (m *Manager) JetStreamAccountInfo() (info *api.JetStreamAccountStats, err error) {
var resp api.JSApiAccountInfoResponse
err = m.jsonRequest(api.JSApiAccountInfo, nil, &resp)
if err != nil {
return nil, err
}
return resp.JetStreamAccountStats, nil
}
func (m *Manager) jsonRequest(subj string, req interface{}, response interface{}) (err error) {
var body []byte
switch {
case req == nil:
body = []byte("")
default:
body, err = json.Marshal(req)
if err != nil {
return err
}
}
if m.trace {
log.Printf(">>> %s\n%s\n\n", subj, string(body))
}
msg, err := m.request(subj, body)
if err != nil {
return err
}
if m.trace {
log.Printf("<<< %s\n%s\n\n", subj, string(msg.Data))
}
err = json.Unmarshal(msg.Data, response)
if err != nil {
return err
}
jsr, ok := response.(jetStreamResponseError)
if !ok {
return nil
}
if jsr.ToError() != nil {
return jsr.ToError()
}
if m.validator == nil {
return nil
}
jv, ok := response.(apiValidatable)
if !ok {
return fmt.Errorf("invalid validator specified")
}
valid, errs := jv.Validate(m.validator)
if valid {
return nil
}
return fmt.Errorf("server response is not a valid %q message: %s", jv.SchemaType(), strings.Join(errs, "\n"))
}
// StreamNames is a sorted list of all known Streams
func (m *Manager) StreamNames() (names []string, err error) {
var resp api.JSApiStreamNamesResponse
err = m.iterableRequest(api.JSApiStreamNames, &api.JSApiStreamNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, &resp, func(page interface{}) error {
apiresp, ok := page.(*api.JSApiStreamNamesResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
names = append(names, apiresp.Streams...)
return nil
})
if err != nil {
return nil, err
}
sort.Strings(names)
return names, nil
}
func (m *Manager) iterableRequest(subj string, req apiIterableRequest, response apiIterableResponse, cb func(interface{}) error) (err error) {
offset := 0
for {
req.SetOffset(offset)
err = m.jsonRequest(subj, req, response)
if err != nil {
return err
}
err = cb(response)
if err != nil {
return err
}
if response.LastPage() {
break
}
offset += response.ItemsLimit()
}
return nil
}
func (m *Manager) request(subj string, data []byte) (res *nats.Msg, err error) {
return m.requestWithTimeout(subj, data, m.timeout)
}
func (m *Manager) requestWithTimeout(subj string, data []byte, timeout time.Duration) (res *nats.Msg, err error) {
if m == nil || m.nc == nil {
return nil, fmt.Errorf("nats connection is not set")
}
var ctx context.Context
var cancel func()
if timeout == 0 {
timeout = m.timeout
}
ctx, cancel = context.WithTimeout(context.Background(), timeout)
defer cancel()
return m.requestWithContext(ctx, subj, data)
}
func (m *Manager) requestWithContext(ctx context.Context, subj string, data []byte) (res *nats.Msg, err error) {
res, err = m.nc.RequestWithContext(ctx, subj, data)
if err != nil {
return nil, err
}
return res, ParseErrorResponse(res)
}
// IsKnownStream determines if a Stream is known
func (m *Manager) IsKnownStream(stream string) (bool, error) {
s, err := m.LoadStream(stream)
if err != nil {
jserr, ok := err.(api.ApiError)
if ok {
if jserr.NotFoundError() {
return false, nil
}
}
return false, err
}
if s.Name() != stream {
return false, fmt.Errorf("received invalid stream from load")
}
return true, nil
}
// IsKnownStreamTemplate determines if a StreamTemplate is known
func (m *Manager) IsKnownStreamTemplate(template string) (bool, error) {
t, err := m.LoadStreamTemplate(template)
if err != nil {
jserr, ok := err.(api.ApiError)
if ok {
if jserr.NotFoundError() {
return false, nil
}
}
return false, err
}
if t.Name() != template {
return false, fmt.Errorf("received invalid stream template from load")
}
return true, nil
}
// IsKnownConsumer determines if a Consumer is known for a specific Stream
func (m *Manager) IsKnownConsumer(stream string, consumer string) (bool, error) {
c, err := m.LoadConsumer(stream, consumer)
if err != nil {
jserr, ok := err.(api.ApiError)
if ok {
if jserr.NotFoundError() {
return false, nil
}
}
return false, err
}
if c.Name() != consumer {
return false, fmt.Errorf("invalid consumer received from load")
}
return true, nil
}
// EachStreamTemplate iterates over all known Stream Templates
func (m *Manager) EachStreamTemplate(cb func(*StreamTemplate)) (err error) {
names, err := m.StreamTemplateNames()
if err != nil {
return err
}
for _, t := range names {
template, err := m.LoadStreamTemplate(t)
if err != nil {
return err
}
cb(template)
}
return nil
}
// EachStream iterates over all known Streams
func (m *Manager) EachStream(cb func(*Stream)) (err error) {
streams, err := m.Streams()
if err != nil {
return err
}
for _, s := range streams {
cb(s)
}
return nil
}
// Consumers is a sorted list of all known Consumers within a Stream
func (m *Manager) Consumers(stream string) (consumers []*Consumer, err error) {
if !IsValidName(stream) {
return nil, fmt.Errorf("%q is not a valid stream name", stream)
}
var cinfo []*api.ConsumerInfo
var resp api.JSApiConsumerListResponse
err = m.iterableRequest(fmt.Sprintf(api.JSApiConsumerListT, stream), &api.JSApiConsumerListRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, &resp, func(page interface{}) error {
apiresp, ok := page.(*api.JSApiConsumerListResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
cinfo = append(cinfo, apiresp.Consumers...)
return nil
})
if err != nil {
return consumers, err
}
sort.Slice(cinfo, func(i int, j int) bool {
return resp.Consumers[i].Name < resp.Consumers[j].Name
})
for _, c := range cinfo {
consumers = append(consumers, m.consumerFromCfg(c.Stream, c.Name, &c.Config))
}
return consumers, nil
}
// StreamTemplateNames is a sorted list of all known StreamTemplates
func (m *Manager) StreamTemplateNames() (templates []string, err error) {
var resp api.JSApiStreamTemplateNamesResponse
err = m.iterableRequest(api.JSApiTemplateNames, &api.JSApiStreamTemplateNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, &resp, func(page interface{}) error {
apiresp, ok := page.(*api.JSApiStreamTemplateNamesResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
templates = append(templates, apiresp.Templates...)
return nil
})
if err != nil {
return templates, err
}
sort.Strings(templates)
return templates, nil
}
// ConsumerNames is a sorted list of all known consumers within a stream
func (m *Manager) ConsumerNames(stream string) (names []string, err error) {
if !IsValidName(stream) {
return nil, fmt.Errorf("%q is not a valid stream name", stream)
}
var resp api.JSApiConsumerNamesResponse
err = m.iterableRequest(fmt.Sprintf(api.JSApiConsumerNamesT, stream), &api.JSApiConsumerNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, &resp, func(page interface{}) error {
apiresp, ok := page.(*api.JSApiConsumerNamesResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
names = append(names, apiresp.Consumers...)
return nil
})
if err != nil {
return nil, err
}
sort.Strings(names)
return names, nil
}
// Streams is a sorted list of all known Streams
func (m *Manager) Streams() (streams []*Stream, err error) {
var resp api.JSApiStreamListResponse
err = m.iterableRequest(api.JSApiStreamList, &api.JSApiStreamListRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, &resp, func(page interface{}) error {
apiresp, ok := page.(*api.JSApiStreamListResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
sort.Slice(apiresp.Streams, func(i int, j int) bool {
return apiresp.Streams[i].Config.Name < apiresp.Streams[j].Config.Name
})
for _, s := range apiresp.Streams {
streams = append(streams, m.streamFromConfig(&s.Config, s))
}
return nil
})
if err != nil {
return streams, err
}
return streams, nil
}