-
Notifications
You must be signed in to change notification settings - Fork 406
/
eventmeshmock.go
363 lines (319 loc) · 11.5 KB
/
eventmeshmock.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
package testing
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"path"
"strings"
"github.com/go-logr/logr"
. "github.com/onsi/ginkgo" //nolint:revive,stylecheck // using . import for convenience
. "github.com/onsi/gomega" //nolint:revive,stylecheck // using . import for convenience
"golang.org/x/oauth2"
logf "sigs.k8s.io/controller-runtime/pkg/log"
// gcp auth etc.
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"github.com/kyma-project/kyma/components/eventing-controller/pkg/ems/api/events/client"
eventmeshtypes "github.com/kyma-project/kyma/components/eventing-controller/pkg/ems/api/events/types"
)
const (
TokenURLPath = "/auth"
MessagingURLPath = "/messaging"
)
// EventMeshMock implements a programmable mock for EventMesh.
type EventMeshMock struct {
Requests *SafeRequests
Subscriptions *SafeSubscriptions
TokenURL string
MessagingURL string
log logr.Logger
AuthResponse Response
GetResponse ResponseWithName
ListResponse Response
CreateResponse Response
UpdateResponse ResponseUpdateReq
UpdateStateResponse ResponseUpdateStateReq
DeleteResponse Response
server *httptest.Server
ResponseOverrides *EventMeshMockResponseOverride
}
type EventMeshMockResponseOverride struct {
CreateResponse map[string]ResponseWithSub
GetResponse map[string]ResponseWithName
}
func NewEventMeshMock() *EventMeshMock {
logger := logf.Log.WithName("beb mock")
return &EventMeshMock{
Requests: NewSafeRequests(),
Subscriptions: NewSafeSubscriptions(),
log: logger,
ResponseOverrides: NewEventMeshMockResponseOverride(),
}
}
func NewEventMeshMockResponseOverride() *EventMeshMockResponseOverride {
return &EventMeshMockResponseOverride{
CreateResponse: map[string]ResponseWithSub{},
GetResponse: map[string]ResponseWithName{},
}
}
type ResponseUpdateReq func(w http.ResponseWriter, key string, webhookAuth *eventmeshtypes.WebhookAuth)
type ResponseUpdateStateReq func(w http.ResponseWriter, key string, state eventmeshtypes.State)
type ResponseWithSub func(w http.ResponseWriter, subscription eventmeshtypes.Subscription)
type ResponseWithName func(w http.ResponseWriter, subscriptionName string)
type Response func(w http.ResponseWriter)
func (m *EventMeshMock) Reset() {
m.log.Info("Initializing requests")
m.Requests = NewSafeRequests()
m.Subscriptions = NewSafeSubscriptions()
m.AuthResponse = EventMeshAuthResponseSuccess
m.GetResponse = GetSubscriptionResponse(m)
m.ListResponse = EventMeshListSuccess
m.CreateResponse = EventMeshCreateSuccess
m.DeleteResponse = EventMeshDeleteResponseSuccess
m.ResponseOverrides = NewEventMeshMockResponseOverride()
m.UpdateResponse = UpdateSubscriptionResponse(m)
m.UpdateStateResponse = UpdateSubscriptionStateResponse(m)
}
func (m *EventMeshMock) ResetResponseOverrides() {
m.log.Info("Resetting response overrides")
m.ResponseOverrides = NewEventMeshMockResponseOverride()
}
func (m *EventMeshMock) AddCreateResponseOverride(key string, responseFunc ResponseWithSub) {
m.ResponseOverrides.CreateResponse[key] = responseFunc
}
func (m *EventMeshMock) AddGetResponseOverride(key string, responseFunc ResponseWithName) {
m.ResponseOverrides.GetResponse[key] = responseFunc
}
func (m *EventMeshMock) Start() string {
m.Reset()
// implementation based on https://pages.github.tools.sap/KernelServices/APIDefinitions/?urls.primaryName=Business%20Event%20Bus%20-%20CloudEvents
mux := http.NewServeMux()
// oauth2 request
mux.HandleFunc(TokenURLPath, func(w http.ResponseWriter, r *http.Request) {
// TODO(k15r): method not allowed/implementd handling
if r.Method == http.MethodPost {
m.AuthResponse(w)
}
})
mux.HandleFunc(client.ListURL, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
m.ListResponse(w)
}
})
mux.HandleFunc(MessagingURLPath+"/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodDelete:
key := r.URL.Path
m.Subscriptions.DeleteSubscription(key)
m.DeleteResponse(w)
case http.MethodPost:
var subscription eventmeshtypes.Subscription
_ = json.NewDecoder(r.Body).Decode(&subscription)
key := r.URL.Path + "/" + subscription.Name
// check if any response override defined for this subscription
if overrideFunc, ok := m.ResponseOverrides.CreateResponse[key]; ok {
overrideFunc(w, subscription)
return
}
// otherwise, use default flow
m.Requests.PutSubscription(r, subscription)
m.Subscriptions.PutSubscription(key, &subscription)
m.CreateResponse(w)
case http.MethodPatch: // mock update WebhookAuth config
var subscription eventmeshtypes.Subscription
err := json.NewDecoder(r.Body).Decode(&subscription)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
key := r.URL.Path // i.e. Path will be `/messaging/events/subscriptions/<name>`
// save request.
m.Requests.PutSubscription(r, subscription)
m.UpdateResponse(w, key, subscription.WebhookAuth)
case http.MethodPut: // mock pause/resume EventMesh subscription
var state eventmeshtypes.State
if err := json.NewDecoder(r.Body).Decode(&state); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// extract get request key from /messaging/events/subscriptions/%s/state
key := strings.TrimSuffix(r.URL.Path, "/state")
m.UpdateStateResponse(w, key, state)
case http.MethodGet:
key := r.URL.Path
// check if any response override defined for this subscription
if overrideFunc, ok := m.ResponseOverrides.GetResponse[key]; ok {
overrideFunc(w, key)
return
}
// otherwise, use default flow
m.GetResponse(w, key)
default:
w.WriteHeader(http.StatusNotImplemented)
}
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
m.log.V(1).Info(r.RequestURI)
})
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
// store request
m.Requests.StoreRequest(r)
description := ""
reqBytes, err := httputil.DumpRequest(r, true)
if err == nil {
description = string(reqBytes)
}
m.log.V(1).Info("received request",
"uri", r.RequestURI,
"method", r.Method,
"description", description,
)
w.Header().Set("Content-Type", "application/json")
mux.ServeHTTP(w, r)
}))
uri := ts.URL
m.server = ts
m.MessagingURL = m.server.URL + MessagingURLPath
m.TokenURL = m.server.URL + TokenURLPath
return uri
}
func (m *EventMeshMock) Stop() {
m.server.Close()
}
// GetSubscriptionResponse checks if a subscription exists in the mock.
func GetSubscriptionResponse(m *EventMeshMock) ResponseWithName {
return func(w http.ResponseWriter, key string) {
subscriptionSaved := m.Subscriptions.GetSubscription(key)
if subscriptionSaved != nil {
if subscriptionSaved.SubscriptionStatus == "" {
subscriptionSaved.SubscriptionStatus = eventmeshtypes.SubscriptionStatusActive
}
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(*subscriptionSaved)
Expect(err).ShouldNot(HaveOccurred())
} else {
w.WriteHeader(http.StatusNotFound)
}
}
}
// UpdateSubscriptionResponse updates the webhook auth of subscription in the mock.
func UpdateSubscriptionResponse(m *EventMeshMock) ResponseUpdateReq {
return func(w http.ResponseWriter, key string, webhookAuth *eventmeshtypes.WebhookAuth) {
subscriptionSaved := m.Subscriptions.GetSubscription(key)
if subscriptionSaved != nil {
subscriptionSaved.WebhookAuth = webhookAuth
m.Subscriptions.PutSubscription(key, subscriptionSaved)
w.WriteHeader(http.StatusNoContent)
err := json.NewEncoder(w).Encode(*subscriptionSaved)
Expect(err).ShouldNot(HaveOccurred())
} else {
w.WriteHeader(http.StatusNotFound)
}
}
}
// UpdateSubscriptionStateResponse updates the EventMesh subscription status in the mock.
func UpdateSubscriptionStateResponse(m *EventMeshMock) ResponseUpdateStateReq {
return func(w http.ResponseWriter, key string, state eventmeshtypes.State) {
if subscription := m.Subscriptions.GetSubscription(key); subscription != nil {
switch state.Action {
case eventmeshtypes.StateActionPause:
{
subscription.SubscriptionStatus = eventmeshtypes.SubscriptionStatusPaused
}
case eventmeshtypes.StateActionResume:
{
subscription.SubscriptionStatus = eventmeshtypes.SubscriptionStatusActive
}
default:
{
panic(fmt.Sprintf("EventMesh subscription status is not supported: %#v", state))
}
}
m.Subscriptions.PutSubscription(key, subscription)
w.WriteHeader(http.StatusAccepted)
err := json.NewEncoder(w).Encode(*subscription)
Expect(err).ShouldNot(HaveOccurred())
return
}
w.WriteHeader(http.StatusNotFound)
}
}
// EventMeshAuthResponseSuccess writes an oauth2 authentication Response to the writer for the happy-path.
func EventMeshAuthResponseSuccess(w http.ResponseWriter) {
token := oauth2.Token{
AccessToken: "some-token",
TokenType: "",
RefreshToken: "",
}
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(token)
Expect(err).ShouldNot(HaveOccurred())
}
// EventMeshCreateSuccess writes a Response to the writer for the happy-path of creating an EventMesh subscription.
func EventMeshCreateSuccess(w http.ResponseWriter) {
w.WriteHeader(http.StatusAccepted)
response := eventmeshtypes.CreateResponse{
Response: eventmeshtypes.Response{
StatusCode: http.StatusAccepted,
Message: "",
},
Href: "",
}
err := json.NewEncoder(w).Encode(response)
Expect(err).ShouldNot(HaveOccurred())
}
// EventMeshGetSuccess writes a Response to the writer for the happy-path of getting an EventMesh subscription.
func EventMeshGetSuccess(w http.ResponseWriter, name string) {
w.WriteHeader(http.StatusOK)
s := eventmeshtypes.Subscription{
Name: name,
SubscriptionStatus: eventmeshtypes.SubscriptionStatusActive,
}
err := json.NewEncoder(w).Encode(s)
Expect(err).ShouldNot(HaveOccurred())
}
// EventMeshListSuccess writes a Response to the writer for the happy-path of listing a EventMesh subscription.
func EventMeshListSuccess(w http.ResponseWriter) {
w.WriteHeader(http.StatusAccepted)
response := eventmeshtypes.Response{
StatusCode: http.StatusOK,
Message: "",
}
err := json.NewEncoder(w).Encode(response)
Expect(err).ShouldNot(HaveOccurred())
}
// EventMeshDeleteResponseSuccess writes a Response to the writer for the happy-path of deleting an EventMesh
// subscription.
func EventMeshDeleteResponseSuccess(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
// IsEventMeshSubscriptionCreate determines if the http request is creating an EventMesh subscription.
func IsEventMeshSubscriptionCreate(r *http.Request) bool {
return r.Method == http.MethodPost && strings.Contains(r.RequestURI, client.CreateURL)
}
// IsEventMeshSubscriptionDelete determines if the http request is deleting a EventMesh subscription.
func IsEventMeshSubscriptionDelete(r *http.Request) bool {
return r.Method == http.MethodDelete && strings.Contains(r.RequestURI, MessagingURLPath)
}
// GetRestAPIObject gets the name of the involved object in a REST url.
// e.g. "/messaging/events/subscriptions/{subscriptionName}" => "{subscriptionName}".
func GetRestAPIObject(u *url.URL) string {
return path.Base(u.Path)
}
// CountRequests counts the mock API requests using the given HTTP method and URI.
func (m *EventMeshMock) CountRequests(method, uri string) int {
count := 0
m.Requests.ReadEach(func(request *http.Request, payload interface{}) {
if request.Method != method {
return
}
if request.RequestURI != uri {
return
}
count++
})
return count
}