-
Notifications
You must be signed in to change notification settings - Fork 27
/
manager.go
651 lines (516 loc) · 15.9 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// 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"
"errors"
"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
apiPrefix string
eventPrefix string
domain string
pedantic bool
apiLEvel *int
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
}
// IsPedantic checks if the manager is in pedantic mode
func (m *Manager) IsPedantic() bool {
return m.pedantic
}
// 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 {
if errors.Is(err, nats.ErrNoResponders) {
return nil, nats.ErrJetStreamNotEnabled
}
return nil, err
}
m.Lock()
m.apiLEvel = &resp.JetStreamAccountStats.API.Level
m.Unlock()
return resp.JetStreamAccountStats, nil
}
// MetaApiLevel determines the JetStream API level supported by the meta leader
func (m *Manager) MetaApiLevel(refresh bool) (int, error) {
m.Lock()
mlvl := m.apiLEvel
m.Unlock()
if !refresh && mlvl != nil {
return *mlvl, nil
}
nfo, err := m.JetStreamAccountInfo()
if err != nil {
return 0, err
}
return nfo.API.Level, nil
}
// IsStreamMaxBytesRequired determines if the JetStream account requires streams to set a byte limit
func (m *Manager) IsStreamMaxBytesRequired() (bool, error) {
nfo, err := m.JetStreamAccountInfo()
if err != nil {
return false, err
}
if nfo.Limits.MaxBytesRequired {
return true, nil
}
for _, t := range nfo.Tiers {
if t.Limits.MaxBytesRequired {
return true, nil
}
}
return false, nil
}
func (m *Manager) jsonRequest(subj string, req any, response any) (err error) {
var body []byte
switch {
case req == nil:
body = []byte("")
default:
body, err = json.Marshal(req)
if err != nil {
return err
}
if string(body) == "null" {
body = nil
}
}
msg, err := m.request(m.apiSubject(subj), body)
if err != nil {
return err
}
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"))
}
// StreamNamesFilter limits the names being returned by the names API
type StreamNamesFilter struct {
// Subject filter the names to those consuming messages matching this subject or wildcard
Subject string `json:"subject,omitempty"`
}
// StreamNames is a sorted list of all known Streams filtered by filter
func (m *Manager) StreamNames(filter *StreamNamesFilter) (names []string, err error) {
resp := func() apiIterableResponse { return &api.JSApiStreamNamesResponse{} }
req := &api.JSApiStreamNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}
if filter != nil {
req.Subject = filter.Subject
}
err = m.iterableRequest(api.JSApiStreamNames, req, resp, func(page any) 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
}
// DeleteStreamMessage deletes a specific message from the Stream without erasing the data, see DeleteMessage() for a safe delete
func (m *Manager) DeleteStreamMessage(stream string, seq uint64, noErase bool) error {
var resp api.JSApiMsgDeleteResponse
err := m.jsonRequest(fmt.Sprintf(api.JSApiMsgDeleteT, stream), api.JSApiMsgDeleteRequest{Seq: seq, NoErase: noErase}, &resp)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("unknown error while deleting message %d", seq)
}
return nil
}
// ReadLastMessageForSubject reads the last message stored in the stream for a specific subject
func (m *Manager) ReadLastMessageForSubject(stream string, sub string) (msg *api.StoredMsg, err error) {
var resp api.JSApiMsgGetResponse
err = m.jsonRequest(fmt.Sprintf(api.JSApiMsgGetT, stream), api.JSApiMsgGetRequest{LastFor: sub}, &resp)
if err != nil {
return nil, err
}
return resp.Message, nil
}
func (m *Manager) iterableRequest(subj string, req apiIterableRequest, response func() apiIterableResponse, cb func(any) error) (err error) {
offset := 0
for {
req.SetOffset(offset)
r := response()
err = m.jsonRequest(subj, req, r)
if err != nil {
return err
}
err = cb(r)
if err != nil {
return err
}
if r.LastPage() {
break
}
offset += r.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()
res, err = m.requestWithContext(ctx, subj, data)
if err != nil {
return nil, err
}
return res, err
}
func (m *Manager) requestWithContext(ctx context.Context, subj string, data []byte) (res *nats.Msg, err error) {
if m.trace {
log.Printf(">>> %s\n%s\n\n", subj, string(data))
}
res, err = m.nc.RequestWithContext(ctx, subj, data)
if err != nil {
if m.trace {
log.Printf("<<< %s: %s\n\n", subj, err.Error())
}
return res, err
}
if m.trace {
log.Printf("<<< %s\n%s\n\n", subj, string(res.Data))
}
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
}
// 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
}
// EachStream iterates over all known Streams, does not handle any streams the cluster could not get data from but returns a list of those
func (m *Manager) EachStream(filter *StreamNamesFilter, cb func(*Stream)) (missing []string, err error) {
streams, missing, err := m.Streams(filter)
if err != nil {
return nil, err
}
for _, s := range streams {
cb(s)
}
return missing, nil
}
// Consumers is a sorted list of all known Consumers within a Stream and a list of any consumer names that were known but no details were found
func (m *Manager) Consumers(stream string) (consumers []*Consumer, missing []string, err error) {
if !IsValidName(stream) {
return nil, nil, fmt.Errorf("%q is not a valid stream name", stream)
}
var (
cinfo []*api.ConsumerInfo
resp = func() apiIterableResponse { return &api.JSApiConsumerListResponse{} }
)
err = m.iterableRequest(fmt.Sprintf(api.JSApiConsumerListT, stream), &api.JSApiConsumerListRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, resp, func(page any) error {
apiresp, ok := page.(*api.JSApiConsumerListResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
missing = append(missing, apiresp.Missing...)
cinfo = append(cinfo, apiresp.Consumers...)
return nil
})
if err != nil {
return consumers, missing, err
}
sort.Slice(cinfo, func(i int, j int) bool {
return cinfo[i].Name < cinfo[j].Name
})
for _, c := range cinfo {
consumer := m.consumerFromCfg(c.Stream, c.Name, &c.Config)
consumer.lastInfo = c
consumers = append(consumers, consumer)
}
return consumers, missing, nil
}
// StreamTemplateNames is a sorted list of all known StreamTemplates
func (m *Manager) StreamTemplateNames() (templates []string, err error) {
resp := func() apiIterableResponse { return &api.JSApiStreamTemplateNamesResponse{} }
err = m.iterableRequest(api.JSApiTemplateNames, &api.JSApiStreamTemplateNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, resp, func(page any) 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)
}
err = m.iterableRequest(fmt.Sprintf(api.JSApiConsumerNamesT, stream), &api.JSApiConsumerNamesRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}, func() apiIterableResponse { return &api.JSApiConsumerNamesResponse{} }, func(page any) 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 and a list of any stream names that were known but no details were found
func (m *Manager) Streams(filter *StreamNamesFilter) ([]*Stream, []string, error) {
var (
streams []*Stream
missing []string
err error
resp = func() apiIterableResponse { return &api.JSApiStreamListResponse{} }
)
req := &api.JSApiStreamListRequest{JSApiIterableRequest: api.JSApiIterableRequest{Offset: 0}}
if filter != nil {
req.Subject = filter.Subject
}
err = m.iterableRequest(api.JSApiStreamList, req, resp, func(page any) 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))
}
missing = append(missing, apiresp.Missing...)
return nil
})
return streams, missing, err
}
func (m *Manager) apiSubject(subject string) string {
return APISubject(subject, m.apiPrefix, m.domain)
}
// MetaLeaderStandDown requests the meta group leader to stand down, must be initiated by a system user
func (m *Manager) MetaLeaderStandDown(placement *api.Placement) error {
var resp api.JSApiLeaderStepDownResponse
err := m.jsonRequest(api.JSApiLeaderStepDown, api.JSApiLeaderStepDownRequest{Placement: placement}, &resp)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("unknown error while requesting leader step down")
}
return nil
}
// DeleteStream removes a stream without all the drama of loading it etc
func (m *Manager) DeleteStream(stream string) error {
if stream == "" || strings.ContainsAny(stream, ".>*") {
return fmt.Errorf("invalid stream name")
}
var resp api.JSApiStreamDeleteResponse
err := m.jsonRequest(fmt.Sprintf(api.JSApiStreamDeleteT, stream), nil, &resp)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("deleting stream %s failed", stream)
}
return nil
}
// DeleteConsumer removes a consumer without all the drama of loading it etc
func (m *Manager) DeleteConsumer(stream string, consumer string) error {
if stream == "" || strings.ContainsAny(stream, ".>*") {
return fmt.Errorf("invalid stream name")
}
if consumer == "" || strings.ContainsAny(consumer, ".>*") {
return fmt.Errorf("invalid consumer name")
}
var resp api.JSApiConsumerDeleteResponse
err := m.jsonRequest(fmt.Sprintf(api.JSApiConsumerDeleteT, stream, consumer), nil, &resp)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("deleting consumer %s > %s failed", stream, consumer)
}
return nil
}
// StreamContainedSubjects queries the stream for the subjects it holds with optional filter
func (m *Manager) StreamContainedSubjects(stream string, filter ...string) (map[string]uint64, error) {
if len(filter) > 1 {
return nil, fmt.Errorf("only 1 filter supported")
}
f := ">"
if len(filter) == 1 && filter[0] != "" {
f = filter[0]
}
subjects := make(map[string]uint64)
resp := func() apiIterableResponse { return &api.JSApiStreamInfoResponse{} }
req := &api.JSApiStreamInfoRequest{SubjectsFilter: f}
err := m.iterableRequest(fmt.Sprintf(api.JSApiStreamInfoT, stream), req, resp, func(page any) error {
apiresp, ok := page.(*api.JSApiStreamInfoResponse)
if !ok {
return fmt.Errorf("invalid response type from iterable request")
}
for s, i := range apiresp.State.Subjects {
subjects[s] = i
}
return nil
})
if err != nil {
return nil, err
}
return subjects, nil
}
// MetaPeerRemove removes a peer from the JetStream meta cluster, evicting all streams, consumer etc. Use with extreme caution.
// If id is given it will be used by the server else name, it's generally best to remove by id
func (m *Manager) MetaPeerRemove(name string, id string) error {
var resp api.JSApiMetaServerRemoveResponse
err := m.jsonRequest(api.JSApiRemoveServer, api.JSApiMetaServerRemoveRequest{Server: name, Peer: id}, &resp)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("unknown error while removing the peer")
}
return nil
}
// MetaPurgeAccount removes all data from an account, must be run in the system account
func (m *Manager) MetaPurgeAccount(account string) error {
if account == "" {
return fmt.Errorf("account is required")
}
var resp api.JSApiAccountPurgeResponse
err := m.jsonRequest(fmt.Sprintf(api.JSApiPurgeAccountT, account), nil, &resp)
if err != nil {
return err
}
if !resp.Initiated {
return fmt.Errorf("unknown error while purging the account")
}
return nil
}
// NatsConn gives access to the underlying NATS Connection
func (m *Manager) NatsConn() *nats.Conn {
m.Lock()
defer m.Unlock()
return m.nc
}
func stringsContains(stack []string, needle string) bool {
for _, s := range stack {
if s == needle {
return true
}
}
return false
}