-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathnotification_endpoint.go
728 lines (638 loc) · 23.7 KB
/
notification_endpoint.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
package http
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/influxdata/influxdb/v2/kit/platform"
"github.com/influxdata/influxdb/v2/kit/platform/errors"
"github.com/influxdata/httprouter"
"github.com/influxdata/influxdb/v2"
pctx "github.com/influxdata/influxdb/v2/context"
"github.com/influxdata/influxdb/v2/notification/endpoint"
"github.com/influxdata/influxdb/v2/pkg/httpc"
"go.uber.org/zap"
)
// NotificationEndpointBackend is all services and associated parameters required to construct
// the NotificationEndpointBackendHandler.
type NotificationEndpointBackend struct {
errors.HTTPErrorHandler
log *zap.Logger
NotificationEndpointService influxdb.NotificationEndpointService
UserResourceMappingService influxdb.UserResourceMappingService
LabelService influxdb.LabelService
UserService influxdb.UserService
}
// NewNotificationEndpointBackend returns a new instance of NotificationEndpointBackend.
func NewNotificationEndpointBackend(log *zap.Logger, b *APIBackend) *NotificationEndpointBackend {
return &NotificationEndpointBackend{
HTTPErrorHandler: b.HTTPErrorHandler,
log: log,
NotificationEndpointService: b.NotificationEndpointService,
UserResourceMappingService: b.UserResourceMappingService,
LabelService: b.LabelService,
UserService: b.UserService,
}
}
func (b *NotificationEndpointBackend) Logger() *zap.Logger {
return b.log
}
// NotificationEndpointHandler is the handler for the notificationEndpoint service
type NotificationEndpointHandler struct {
*httprouter.Router
errors.HTTPErrorHandler
log *zap.Logger
NotificationEndpointService influxdb.NotificationEndpointService
UserResourceMappingService influxdb.UserResourceMappingService
LabelService influxdb.LabelService
UserService influxdb.UserService
}
const (
prefixNotificationEndpoints = "/api/v2/notificationEndpoints"
notificationEndpointsIDPath = "/api/v2/notificationEndpoints/:id"
notificationEndpointsIDMembersPath = "/api/v2/notificationEndpoints/:id/members"
notificationEndpointsIDMembersIDPath = "/api/v2/notificationEndpoints/:id/members/:userID"
notificationEndpointsIDOwnersPath = "/api/v2/notificationEndpoints/:id/owners"
notificationEndpointsIDOwnersIDPath = "/api/v2/notificationEndpoints/:id/owners/:userID"
notificationEndpointsIDLabelsPath = "/api/v2/notificationEndpoints/:id/labels"
notificationEndpointsIDLabelsIDPath = "/api/v2/notificationEndpoints/:id/labels/:lid"
)
// NewNotificationEndpointHandler returns a new instance of NotificationEndpointHandler.
func NewNotificationEndpointHandler(log *zap.Logger, b *NotificationEndpointBackend) *NotificationEndpointHandler {
h := &NotificationEndpointHandler{
Router: NewRouter(b.HTTPErrorHandler),
HTTPErrorHandler: b.HTTPErrorHandler,
log: log,
NotificationEndpointService: b.NotificationEndpointService,
UserResourceMappingService: b.UserResourceMappingService,
LabelService: b.LabelService,
UserService: b.UserService,
}
h.HandlerFunc("POST", prefixNotificationEndpoints, h.handlePostNotificationEndpoint)
h.HandlerFunc("GET", prefixNotificationEndpoints, h.handleGetNotificationEndpoints)
h.HandlerFunc("GET", notificationEndpointsIDPath, h.handleGetNotificationEndpoint)
h.HandlerFunc("DELETE", notificationEndpointsIDPath, h.handleDeleteNotificationEndpoint)
h.HandlerFunc("PUT", notificationEndpointsIDPath, h.handlePutNotificationEndpoint)
h.HandlerFunc("PATCH", notificationEndpointsIDPath, h.handlePatchNotificationEndpoint)
memberBackend := MemberBackend{
HTTPErrorHandler: b.HTTPErrorHandler,
log: b.log.With(zap.String("handler", "member")),
ResourceType: influxdb.NotificationEndpointResourceType,
UserType: influxdb.Member,
UserResourceMappingService: b.UserResourceMappingService,
UserService: b.UserService,
}
h.HandlerFunc("POST", notificationEndpointsIDMembersPath, newPostMemberHandler(memberBackend))
h.HandlerFunc("GET", notificationEndpointsIDMembersPath, newGetMembersHandler(memberBackend))
h.HandlerFunc("DELETE", notificationEndpointsIDMembersIDPath, newDeleteMemberHandler(memberBackend))
ownerBackend := MemberBackend{
HTTPErrorHandler: b.HTTPErrorHandler,
log: b.log.With(zap.String("handler", "member")),
ResourceType: influxdb.NotificationEndpointResourceType,
UserType: influxdb.Owner,
UserResourceMappingService: b.UserResourceMappingService,
UserService: b.UserService,
}
h.HandlerFunc("POST", notificationEndpointsIDOwnersPath, newPostMemberHandler(ownerBackend))
h.HandlerFunc("GET", notificationEndpointsIDOwnersPath, newGetMembersHandler(ownerBackend))
h.HandlerFunc("DELETE", notificationEndpointsIDOwnersIDPath, newDeleteMemberHandler(ownerBackend))
labelBackend := &LabelBackend{
HTTPErrorHandler: b.HTTPErrorHandler,
log: b.log.With(zap.String("handler", "label")),
LabelService: b.LabelService,
ResourceType: influxdb.NotificationEndpointResourceType,
}
h.HandlerFunc("GET", notificationEndpointsIDLabelsPath, newGetLabelsHandler(labelBackend))
h.HandlerFunc("POST", notificationEndpointsIDLabelsPath, newPostLabelHandler(labelBackend))
h.HandlerFunc("DELETE", notificationEndpointsIDLabelsIDPath, newDeleteLabelHandler(labelBackend))
return h
}
type notificationEndpointLinks struct {
Self string `json:"self"`
Labels string `json:"labels"`
Members string `json:"members"`
Owners string `json:"owners"`
}
type postNotificationEndpointRequest struct {
influxdb.NotificationEndpoint
Labels []string `json:"labels"`
}
type notificationEndpointResponse struct {
influxdb.NotificationEndpoint
Labels []influxdb.Label `json:"labels"`
Links notificationEndpointLinks `json:"links"`
}
func (resp notificationEndpointResponse) MarshalJSON() ([]byte, error) {
b1, err := json.Marshal(resp.NotificationEndpoint)
if err != nil {
return nil, err
}
b2, err := json.Marshal(struct {
Labels []influxdb.Label `json:"labels"`
Links notificationEndpointLinks `json:"links"`
}{
Links: resp.Links,
Labels: resp.Labels,
})
if err != nil {
return nil, err
}
return []byte(string(b1[:len(b1)-1]) + ", " + string(b2[1:])), nil
}
type notificationEndpointsResponse struct {
NotificationEndpoints []notificationEndpointResponse `json:"notificationEndpoints"`
Links *influxdb.PagingLinks `json:"links"`
}
func newNotificationEndpointResponse(edp influxdb.NotificationEndpoint, labels []*influxdb.Label) notificationEndpointResponse {
res := notificationEndpointResponse{
NotificationEndpoint: edp,
Links: notificationEndpointLinks{
Self: fmt.Sprintf("/api/v2/notificationEndpoints/%s", edp.GetID()),
Labels: fmt.Sprintf("/api/v2/notificationEndpoints/%s/labels", edp.GetID()),
Members: fmt.Sprintf("/api/v2/notificationEndpoints/%s/members", edp.GetID()),
Owners: fmt.Sprintf("/api/v2/notificationEndpoints/%s/owners", edp.GetID()),
},
Labels: []influxdb.Label{},
}
for _, l := range labels {
res.Labels = append(res.Labels, *l)
}
return res
}
func newNotificationEndpointsResponse(ctx context.Context, edps []influxdb.NotificationEndpoint, labelService influxdb.LabelService, f influxdb.PagingFilter, opts influxdb.FindOptions) *notificationEndpointsResponse {
resp := ¬ificationEndpointsResponse{
NotificationEndpoints: make([]notificationEndpointResponse, len(edps)),
Links: influxdb.NewPagingLinks(prefixNotificationEndpoints, opts, f, len(edps)),
}
for i, edp := range edps {
labels, _ := labelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: edp.GetID(), ResourceType: influxdb.NotificationEndpointResourceType})
resp.NotificationEndpoints[i] = newNotificationEndpointResponse(edp, labels)
}
return resp
}
func decodeGetNotificationEndpointRequest(ctx context.Context) (i platform.ID, err error) {
params := httprouter.ParamsFromContext(ctx)
id := params.ByName("id")
if id == "" {
return i, &errors.Error{
Code: errors.EInvalid,
Msg: "url missing id",
}
}
if err := i.DecodeFromString(id); err != nil {
return i, err
}
return i, nil
}
func (h *NotificationEndpointHandler) handleGetNotificationEndpoints(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
filter, opts, err := decodeNotificationEndpointFilter(ctx, r)
if err != nil {
h.log.Debug("Failed to decode request", zap.Error(err))
h.HandleHTTPError(ctx, err, w)
return
}
edps, _, err := h.NotificationEndpointService.FindNotificationEndpoints(ctx, filter, opts)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
h.log.Debug("NotificationEndpoints retrieved", zap.String("notificationEndpoints", fmt.Sprint(edps)))
if err := encodeResponse(ctx, w, http.StatusOK, newNotificationEndpointsResponse(ctx, edps, h.LabelService, filter, opts)); err != nil {
logEncodingError(h.log, r, err)
return
}
}
func (h *NotificationEndpointHandler) handleGetNotificationEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id, err := decodeGetNotificationEndpointRequest(ctx)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
edp, err := h.NotificationEndpointService.FindNotificationEndpointByID(ctx, id)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
h.log.Debug("NotificationEndpoint retrieved", zap.String("notificationEndpoint", fmt.Sprint(edp)))
labels, err := h.LabelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: edp.GetID(), ResourceType: influxdb.NotificationEndpointResourceType})
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
if err := encodeResponse(ctx, w, http.StatusOK, newNotificationEndpointResponse(edp, labels)); err != nil {
logEncodingError(h.log, r, err)
return
}
}
func decodeNotificationEndpointFilter(ctx context.Context, r *http.Request) (influxdb.NotificationEndpointFilter, influxdb.FindOptions, error) {
f := influxdb.NotificationEndpointFilter{
UserResourceMappingFilter: influxdb.UserResourceMappingFilter{
ResourceType: influxdb.NotificationEndpointResourceType,
},
}
opts, err := influxdb.DecodeFindOptions(r)
if err != nil {
return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, err
}
q := r.URL.Query()
if orgIDStr := q.Get("orgID"); orgIDStr != "" {
orgID, err := platform.IDFromString(orgIDStr)
if err != nil {
return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, &errors.Error{
Code: errors.EInvalid,
Msg: "orgID is invalid",
Err: err,
}
}
f.OrgID = orgID
} else if orgNameStr := q.Get("org"); orgNameStr != "" {
*f.Org = orgNameStr
}
if userID := q.Get("user"); userID != "" {
id, err := platform.IDFromString(userID)
if err != nil {
return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, err
}
f.UserID = *id
}
return f, *opts, err
}
func decodePostNotificationEndpointRequest(r *http.Request) (postNotificationEndpointRequest, error) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return postNotificationEndpointRequest{}, &errors.Error{
Code: errors.EInvalid,
Err: err,
}
}
defer r.Body.Close()
edp, err := endpoint.UnmarshalJSON(b)
if err != nil {
return postNotificationEndpointRequest{}, &errors.Error{
Code: errors.EInvalid,
Err: err,
}
}
var dl decodeLabels
if err := json.Unmarshal(b, &dl); err != nil {
return postNotificationEndpointRequest{}, &errors.Error{
Code: errors.EInvalid,
Err: err,
}
}
return postNotificationEndpointRequest{
NotificationEndpoint: edp,
Labels: dl.Labels,
}, nil
}
func decodePutNotificationEndpointRequest(ctx context.Context, r *http.Request) (influxdb.NotificationEndpoint, error) {
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(r.Body); err != nil {
return nil, &errors.Error{
Code: errors.EInvalid,
Err: err,
}
}
defer r.Body.Close()
edp, err := endpoint.UnmarshalJSON(buf.Bytes())
if err != nil {
return nil, &errors.Error{
Code: errors.EInvalid,
Err: err,
}
}
params := httprouter.ParamsFromContext(ctx)
i, err := platform.IDFromString(params.ByName("id"))
if err != nil {
return nil, err
}
edp.SetID(*i)
return edp, nil
}
type patchNotificationEndpointRequest struct {
platform.ID
Update influxdb.NotificationEndpointUpdate
}
func decodePatchNotificationEndpointRequest(ctx context.Context, r *http.Request) (patchNotificationEndpointRequest, error) {
params := httprouter.ParamsFromContext(ctx)
id, err := platform.IDFromString(params.ByName("id"))
if err != nil {
return patchNotificationEndpointRequest{}, err
}
req := patchNotificationEndpointRequest{
ID: *id,
}
var upd influxdb.NotificationEndpointUpdate
if err := json.NewDecoder(r.Body).Decode(&upd); err != nil {
return patchNotificationEndpointRequest{}, &errors.Error{
Code: errors.EInvalid,
Msg: err.Error(),
}
}
if err := upd.Valid(); err != nil {
return patchNotificationEndpointRequest{}, &errors.Error{
Code: errors.EInvalid,
Msg: err.Error(),
}
}
req.Update = upd
return req, nil
}
// handlePostNotificationEndpoint is the HTTP handler for the POST /api/v2/notificationEndpoints route.
func (h *NotificationEndpointHandler) handlePostNotificationEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
edp, err := decodePostNotificationEndpointRequest(r)
if err != nil {
h.log.Debug("Failed to decode request", zap.Error(err))
h.HandleHTTPError(ctx, err, w)
return
}
auth, err := pctx.GetAuthorizer(ctx)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
err = h.NotificationEndpointService.CreateNotificationEndpoint(ctx, edp.NotificationEndpoint, auth.GetUserID())
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
labels := h.mapNewNotificationEndpointLabels(ctx, edp.NotificationEndpoint, edp.Labels)
h.log.Debug("NotificationEndpoint created", zap.String("notificationEndpoint", fmt.Sprint(edp)))
if err := encodeResponse(ctx, w, http.StatusCreated, newNotificationEndpointResponse(edp, labels)); err != nil {
logEncodingError(h.log, r, err)
return
}
}
func (h *NotificationEndpointHandler) mapNewNotificationEndpointLabels(ctx context.Context, nre influxdb.NotificationEndpoint, labels []string) []*influxdb.Label {
var ls []*influxdb.Label
for _, sid := range labels {
var lid platform.ID
err := lid.DecodeFromString(sid)
if err != nil {
continue
}
label, err := h.LabelService.FindLabelByID(ctx, lid)
if err != nil {
continue
}
mapping := influxdb.LabelMapping{
LabelID: label.ID,
ResourceID: nre.GetID(),
ResourceType: influxdb.NotificationEndpointResourceType,
}
err = h.LabelService.CreateLabelMapping(ctx, &mapping)
if err != nil {
continue
}
ls = append(ls, label)
}
return ls
}
// handlePutNotificationEndpoint is the HTTP handler for the PUT /api/v2/notificationEndpoints route.
func (h *NotificationEndpointHandler) handlePutNotificationEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
edp, err := decodePutNotificationEndpointRequest(ctx, r)
if err != nil {
h.log.Debug("Failed to decode request", zap.Error(err))
h.HandleHTTPError(ctx, err, w)
return
}
auth, err := pctx.GetAuthorizer(ctx)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
edp, err = h.NotificationEndpointService.UpdateNotificationEndpoint(ctx, edp.GetID(), edp, auth.GetUserID())
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
labels, err := h.LabelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: edp.GetID(), ResourceType: influxdb.NotificationEndpointResourceType})
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
h.log.Debug("NotificationEndpoint replaced", zap.String("notificationEndpoint", fmt.Sprint(edp)))
if err := encodeResponse(ctx, w, http.StatusOK, newNotificationEndpointResponse(edp, labels)); err != nil {
logEncodingError(h.log, r, err)
return
}
}
// handlePatchNotificationEndpoint is the HTTP handler for the PATCH /api/v2/notificationEndpoints/:id route.
func (h *NotificationEndpointHandler) handlePatchNotificationEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := decodePatchNotificationEndpointRequest(ctx, r)
if err != nil {
h.log.Debug("Failed to decode request", zap.Error(err))
h.HandleHTTPError(ctx, err, w)
return
}
edp, err := h.NotificationEndpointService.PatchNotificationEndpoint(ctx, req.ID, req.Update)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
labels, err := h.LabelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: edp.GetID(), ResourceType: influxdb.NotificationEndpointResourceType})
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
h.log.Debug("NotificationEndpoint patch", zap.String("notificationEndpoint", fmt.Sprint(edp)))
if err := encodeResponse(ctx, w, http.StatusOK, newNotificationEndpointResponse(edp, labels)); err != nil {
logEncodingError(h.log, r, err)
return
}
}
func (h *NotificationEndpointHandler) handleDeleteNotificationEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
i, err := decodeGetNotificationEndpointRequest(ctx)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
flds, _, err := h.NotificationEndpointService.DeleteNotificationEndpoint(ctx, i)
if err != nil {
h.HandleHTTPError(ctx, err, w)
return
}
keys := make([]string, len(flds))
for k, fld := range flds {
if fld.Key == "" {
h.HandleHTTPError(ctx, &errors.Error{
Op: "http/handleDeleteNotificationEndpoint",
Msg: "Bad Secret Key in endpoint " + i.String(),
}, w)
return
}
keys[k] = fld.Key
}
h.log.Debug("NotificationEndpoint deleted", zap.String("notificationEndpointID", fmt.Sprint(i)))
w.WriteHeader(http.StatusNoContent)
}
// NotificationEndpointService is an http client for the influxdb.NotificationEndpointService server implementation.
type NotificationEndpointService struct {
Client *httpc.Client
}
// NewNotificationEndpointService constructs a new http NotificationEndpointService.
func NewNotificationEndpointService(client *httpc.Client) *NotificationEndpointService {
return &NotificationEndpointService{
Client: client,
}
}
var _ influxdb.NotificationEndpointService = (*NotificationEndpointService)(nil)
// FindNotificationEndpointByID returns a single notification endpoint by ID.
func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) {
if !id.Valid() {
return nil, fmt.Errorf("invalid ID: please provide a valid ID")
}
var resp notificationEndpointDecoder
err := s.Client.
Get(prefixNotificationEndpoints, id.String()).
DecodeJSON(&resp).
Do(ctx)
if err != nil {
return nil, err
}
return resp.endpoint, nil
}
// FindNotificationEndpoints returns a list of notification endpoints that match filter and the total count of matching notification endpoints.
// Additional options provide pagination & sorting.
func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Context, filter influxdb.NotificationEndpointFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error) {
params := influxdb.FindOptionParams(opt...)
if filter.ID != nil {
params = append(params, [2]string{"id", filter.ID.String()})
}
if filter.OrgID != nil {
params = append(params, [2]string{"orgID", filter.OrgID.String()})
}
if filter.Org != nil {
params = append(params, [2]string{"org", *filter.Org})
}
var resp struct {
Endpoints []notificationEndpointDecoder `json:"notificationEndpoints"`
}
err := s.Client.
Get(prefixNotificationEndpoints).
QueryParams(params...).
DecodeJSON(&resp).
Do(ctx)
if err != nil {
return nil, 0, err
}
var endpoints []influxdb.NotificationEndpoint
for _, e := range resp.Endpoints {
endpoints = append(endpoints, e.endpoint)
}
return endpoints, len(endpoints), nil
}
// CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier.
// TODO(@jsteenb2): this is unsatisfactory, we have no way of grabbing the new notification endpoint without
// serious hacky hackertoning. Put it on the list...
func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, ne influxdb.NotificationEndpoint, userID platform.ID) error {
var resp notificationEndpointDecoder
err := s.Client.
PostJSON(¬ificationEndpointEncoder{ne: ne}, prefixNotificationEndpoints).
DecodeJSON(&resp).
Do(ctx)
if err != nil {
return err
}
// :sadpanda:
ne.SetID(resp.endpoint.GetID())
ne.SetOrgID(resp.endpoint.GetOrgID())
return nil
}
// UpdateNotificationEndpoint updates a single notification endpoint.
// Returns the new notification endpoint after update.
func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, ne influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) {
if !id.Valid() {
return nil, fmt.Errorf("invalid ID: please provide a valid ID")
}
var resp notificationEndpointDecoder
err := s.Client.
PutJSON(¬ificationEndpointEncoder{ne: ne}, prefixNotificationEndpoints, id.String()).
DecodeJSON(&resp).
Do(ctx)
if err != nil {
return nil, err
}
return resp.endpoint, nil
}
// PatchNotificationEndpoint updates a single notification endpoint with changeset.
// Returns the new notification endpoint state after update.
func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) {
if !id.Valid() {
return nil, fmt.Errorf("invalid ID: please provide a valid ID")
}
if err := upd.Valid(); err != nil {
return nil, err
}
var resp notificationEndpointDecoder
err := s.Client.
PatchJSON(upd, prefixNotificationEndpoints, id.String()).
DecodeJSON(&resp).
Do(ctx)
if err != nil {
return nil, err
}
return resp.endpoint, nil
}
// DeleteNotificationEndpoint removes a notification endpoint by ID, returns secret fields, orgID for further deletion.
// TODO: axe this delete design, makes little sense in how its currently being done. Right now, as an http client,
// I am forced to know how the store handles this and then figure out what the server does in between me and that store,
// then see what falls out :flushed... for now returning nothing for secrets, orgID, and only returning an error. This makes
// the code/design smell super obvious imo
func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) {
if !id.Valid() {
return nil, 0, fmt.Errorf("invalid ID: please provide a valid ID")
}
err := s.Client.
Delete(prefixNotificationEndpoints, id.String()).
Do(ctx)
return nil, 0, err
}
type notificationEndpointEncoder struct {
ne influxdb.NotificationEndpoint
}
func (n *notificationEndpointEncoder) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(n.ne)
if err != nil {
return nil, err
}
ughhh := make(map[string]interface{})
if err := json.Unmarshal(b, &ughhh); err != nil {
return nil, err
}
n.ne.BackfillSecretKeys()
// this makes me queezy and altogether sad
fieldMap := map[string]string{
"-password": "password",
"-routing-key": "routingKey",
"-token": "token",
"-username": "username",
}
for _, sec := range n.ne.SecretFields() {
var v string
if sec.Value != nil {
v = *sec.Value
}
ughhh[fieldMap[sec.Key]] = v
}
return json.Marshal(ughhh)
}
type notificationEndpointDecoder struct {
endpoint influxdb.NotificationEndpoint
}
func (n *notificationEndpointDecoder) UnmarshalJSON(b []byte) error {
newEndpoint, err := endpoint.UnmarshalJSON(b)
if err != nil {
return err
}
n.endpoint = newEndpoint
return nil
}