-
Notifications
You must be signed in to change notification settings - Fork 732
/
start.go
206 lines (171 loc) · 6.17 KB
/
start.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
/*
Copyright 2018 BlackRock, Inc.
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 stripe
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/webhookendpoint"
"go.uber.org/zap"
"github.com/argoproj/argo-events/common"
"github.com/argoproj/argo-events/common/logging"
eventsourcecommon "github.com/argoproj/argo-events/eventsources/common"
"github.com/argoproj/argo-events/eventsources/common/webhook"
"github.com/argoproj/argo-events/eventsources/sources"
apicommon "github.com/argoproj/argo-events/pkg/apis/common"
"github.com/argoproj/argo-events/pkg/apis/events"
)
// controller controls the webhook operations
var (
controller = webhook.NewController()
)
// set up the activation and inactivation channels to control the state of routes.
func init() {
go webhook.ProcessRouteStatus(controller)
}
// GetEventSourceName returns name of event source
func (el *EventListener) GetEventSourceName() string {
return el.EventSourceName
}
// GetEventName returns name of event
func (el *EventListener) GetEventName() string {
return el.EventName
}
// GetEventSourceType return type of event server
func (el *EventListener) GetEventSourceType() apicommon.EventSourceType {
return apicommon.StripeEvent
}
// Implement Router
// 1. GetRoute
// 2. HandleRoute
// 3. PostActivate
// 4. PostDeactivate
// GetRoute returns the route
func (rc *Router) GetRoute() *webhook.Route {
return rc.route
}
// HandleRoute handles incoming requests on the route
func (rc *Router) HandleRoute(writer http.ResponseWriter, request *http.Request) {
route := rc.route
logger := route.Logger.With(
logging.LabelEndpoint, route.Context.Endpoint,
logging.LabelPort, route.Context.Port,
logging.LabelHTTPMethod, route.Context.Method,
)
logger.Info("request a received, processing it...")
if !route.Active {
logger.Warn("endpoint is not active, won't process it")
common.SendErrorResponse(writer, "endpoint is inactive")
return
}
defer func(start time.Time) {
route.Metrics.EventProcessingDuration(route.EventSourceName, route.EventName, float64(time.Since(start)/time.Millisecond))
}(time.Now())
request.Body = http.MaxBytesReader(writer, request.Body, route.Context.GetMaxPayloadSize())
payload, err := io.ReadAll(request.Body)
if err != nil {
logger.Errorw("error reading request body", zap.Error(err))
writer.WriteHeader(http.StatusServiceUnavailable)
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
}
var event *stripe.Event
if err := json.Unmarshal(payload, &event); err != nil {
logger.Errorw("failed to parse request body", zap.Error(err))
common.SendErrorResponse(writer, "failed to parse the event")
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
}
if ok := filterEvent(event, rc.stripeEventSource.EventFilter); !ok {
logger.Errorw("failed to pass the filters", zap.Any("event-type", event.Type), zap.Error(err))
common.SendErrorResponse(writer, "invalid event")
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
}
eventData := &events.StripeEventData{
Event: event,
Metadata: rc.stripeEventSource.Metadata,
}
data, err := json.Marshal(eventData)
if err != nil {
logger.Errorw("failed to marshal event data", zap.Any("event-id", event.ID), zap.Error(err))
common.SendErrorResponse(writer, "invalid event")
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
}
logger.Info("dispatching event on route's data channel...")
route.DataCh <- data
logger.Info("request successfully processed")
common.SendSuccessResponse(writer, "success")
}
// PostActivate performs operations once the route is activated and ready to consume requests
func (rc *Router) PostActivate() error {
if rc.stripeEventSource.CreateWebhook {
route := rc.route
stripeEventSource := rc.stripeEventSource
logger := route.Logger.With(
logging.LabelEndpoint, route.Context.Endpoint,
logging.LabelHTTPMethod, route.Context.Method,
)
logger.Info("registering a new webhook")
apiKey, err := common.GetSecretFromVolume(stripeEventSource.APIKey)
if err != nil {
return fmt.Errorf("APIKey not found, %w", err)
}
stripe.Key = apiKey
params := &stripe.WebhookEndpointParams{
URL: stripe.String(common.FormattedURL(stripeEventSource.Webhook.URL, stripeEventSource.Webhook.Endpoint)),
}
if stripeEventSource.EventFilter != nil {
params.EnabledEvents = stripe.StringSlice(stripeEventSource.EventFilter)
}
endpoint, err := webhookendpoint.New(params)
if err != nil {
return err
}
logger.With("endpoint-id", endpoint.ID).Info("new stripe webhook endpoint created")
}
return nil
}
// PostInactivate performs operations after the route is inactivated
func (rc *Router) PostInactivate() error {
return nil
}
func filterEvent(event *stripe.Event, filters []string) bool {
if filters == nil {
return true
}
for _, filter := range filters {
if event.Type == filter {
return true
}
}
return false
}
// StartListening starts an event source
func (el *EventListener) StartListening(ctx context.Context, dispatch func([]byte, ...eventsourcecommon.Option) error) error {
log := logging.FromContext(ctx).
With(logging.LabelEventSourceType, el.GetEventSourceType(), logging.LabelEventName, el.GetEventName())
log.Info("started processing the Stripe event source...")
defer sources.Recover(el.GetEventName())
stripeEventSource := &el.StripeEventSource
route := webhook.NewRoute(stripeEventSource.Webhook, log, el.GetEventSourceName(), el.GetEventName(), el.Metrics)
return webhook.ManageRoute(ctx, &Router{
route: route,
stripeEventSource: stripeEventSource,
}, controller, dispatch)
}