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
|
package webhook
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
func init() {
util_http.InitGlobalHttpClient()
}
func TestHttpClientSendMessage(t *testing.T) {
var receivedPayload map[string]interface{}
var receivedHeaders http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeaders = r.Header
body, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(body, &receivedPayload); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
cfg := &config{
endpoint: server.URL,
authBearerToken: "test-token",
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
OldEntry: nil,
NewEntry: &filer_pb.Entry{
Name: "test.txt",
IsDirectory: false,
},
}
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
if receivedPayload["key"] != "/test/path" {
t.Errorf("Expected key '/test/path', got %v", receivedPayload["key"])
}
if receivedPayload["event_type"] != "create" {
t.Errorf("Expected event_type 'create', got %v", receivedPayload["event_type"])
}
if receivedPayload["message"] == nil {
t.Error("Expected message to be present")
}
if receivedHeaders.Get("Content-Type") != "application/json" {
t.Errorf("Expected Content-Type 'application/json', got %s", receivedHeaders.Get("Content-Type"))
}
expectedAuth := "Bearer test-token"
if receivedHeaders.Get("Authorization") != expectedAuth {
t.Errorf("Expected Authorization '%s', got %s", expectedAuth, receivedHeaders.Get("Authorization"))
}
}
func TestHttpClientSendMessageWithoutToken(t *testing.T) {
var receivedHeaders http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeaders = r.Header
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
cfg := &config{
endpoint: server.URL,
authBearerToken: "",
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{}
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
if receivedHeaders.Get("Authorization") != "" {
t.Errorf("Expected no Authorization header, got %s", receivedHeaders.Get("Authorization"))
}
}
func TestHttpClientSendMessageServerError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
cfg := &config{
endpoint: server.URL,
authBearerToken: "test-token",
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{}
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err == nil {
t.Error("Expected error for server error response")
}
}
func TestHttpClientSendMessageNetworkError(t *testing.T) {
cfg := &config{
endpoint: "http://localhost:99999",
authBearerToken: "",
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{}
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err == nil {
t.Error("Expected error for network failure")
}
}
// TestHttpClientFollowsRedirectAsPost verifies that redirects are followed with POST method preserved
func TestHttpClientFollowsRedirectAsPost(t *testing.T) {
redirectCalled := false
finalCalled := false
var finalMethod string
var finalBody map[string]interface{}
// Create final destination server
finalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
finalCalled = true
finalMethod = r.Method
body, _ := io.ReadAll(r.Body)
json.Unmarshal(body, &finalBody)
w.WriteHeader(http.StatusOK)
}))
defer finalServer.Close()
// Create redirect server
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
redirectCalled = true
// Return 301 redirect to final server
http.Redirect(w, r, finalServer.URL, http.StatusMovedPermanently)
}))
defer redirectServer.Close()
cfg := &config{
endpoint: redirectServer.URL,
authBearerToken: "test-token",
timeoutSeconds: 5,
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "test.txt",
},
}
// Send message - should follow redirect and recreate POST request
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
if !redirectCalled {
t.Error("Expected redirect server to be called")
}
if !finalCalled {
t.Error("Expected final server to be called after redirect")
}
if finalMethod != "POST" {
t.Errorf("Expected POST method at final destination, got %s", finalMethod)
}
if finalBody["key"] != "/test/path" {
t.Errorf("Expected key '/test/path' at final destination, got %v", finalBody["key"])
}
// Verify the final URL is cached
client.endpointMu.RLock()
cachedURL := client.finalURL
client.endpointMu.RUnlock()
if cachedURL != finalServer.URL {
t.Errorf("Expected cached URL %s, got %s", finalServer.URL, cachedURL)
}
}
// TestHttpClientUsesCachedRedirect verifies that subsequent requests use the cached redirect destination
func TestHttpClientUsesCachedRedirect(t *testing.T) {
redirectCount := 0
finalCount := 0
// Create final destination server
finalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
finalCount++
w.WriteHeader(http.StatusOK)
}))
defer finalServer.Close()
// Create redirect server
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
redirectCount++
http.Redirect(w, r, finalServer.URL, http.StatusMovedPermanently)
}))
defer redirectServer.Close()
cfg := &config{
endpoint: redirectServer.URL,
authBearerToken: "test-token",
timeoutSeconds: 5,
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "test.txt",
},
}
// First request - should hit redirect server
err = client.sendMessage(newWebhookMessage("/test/path1", message))
if err != nil {
t.Fatalf("Failed to send first message: %v", err)
}
if redirectCount != 1 {
t.Errorf("Expected 1 redirect call, got %d", redirectCount)
}
if finalCount != 1 {
t.Errorf("Expected 1 final call, got %d", finalCount)
}
// Second request - should use cached URL and skip redirect server
err = client.sendMessage(newWebhookMessage("/test/path2", message))
if err != nil {
t.Fatalf("Failed to send second message: %v", err)
}
if redirectCount != 1 {
t.Errorf("Expected redirect server to be called only once (cached), got %d calls", redirectCount)
}
if finalCount != 2 {
t.Errorf("Expected 2 final calls, got %d", finalCount)
}
}
// TestHttpClientPreservesPostMethod verifies POST method is preserved and not converted to GET
func TestHttpClientPreservesPostMethod(t *testing.T) {
var receivedMethod string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedMethod = r.Method
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
cfg := &config{
endpoint: server.URL,
authBearerToken: "test-token",
timeoutSeconds: 5,
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "test.txt",
},
}
err = client.sendMessage(newWebhookMessage("/test/path", message))
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
if receivedMethod != "POST" {
t.Errorf("Expected POST method, got %s", receivedMethod)
}
}
// TestHttpClientInvalidatesCacheOnError verifies that cache is invalidated when cached URL fails
func TestHttpClientInvalidatesCacheOnError(t *testing.T) {
finalServerDown := false // Start with server UP
originalCallCount := 0
finalCallCount := 0
// Create final destination server that can be toggled
finalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
finalCallCount++
if finalServerDown {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusOK)
}
}))
defer finalServer.Close()
// Create redirect server
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
originalCallCount++
http.Redirect(w, r, finalServer.URL, http.StatusMovedPermanently)
}))
defer redirectServer.Close()
cfg := &config{
endpoint: redirectServer.URL,
authBearerToken: "test-token",
timeoutSeconds: 5,
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "test.txt",
},
}
// First request - should follow redirect and cache the final URL
err = client.sendMessage(newWebhookMessage("/test/path1", message))
if err != nil {
t.Fatalf("Failed to send first message: %v", err)
}
if originalCallCount != 1 {
t.Errorf("Expected 1 original call, got %d", originalCallCount)
}
if finalCallCount != 1 {
t.Errorf("Expected 1 final call, got %d", finalCallCount)
}
// Verify cache was set
client.endpointMu.RLock()
cachedURL := client.finalURL
client.endpointMu.RUnlock()
if cachedURL != finalServer.URL {
t.Errorf("Expected cached URL %s, got %s", finalServer.URL, cachedURL)
}
// Second request with cached URL working - should use cache
err = client.sendMessage(newWebhookMessage("/test/path2", message))
if err != nil {
t.Fatalf("Failed to send second message: %v", err)
}
if originalCallCount != 1 {
t.Errorf("Expected still 1 original call (using cache), got %d", originalCallCount)
}
if finalCallCount != 2 {
t.Errorf("Expected 2 final calls, got %d", finalCallCount)
}
// Third request - bring final server DOWN, should invalidate cache and retry with original
// Flow: cached URL (fail, depth=0) -> clear cache -> retry original (depth=1) -> redirect -> final (fail, depth=2)
finalServerDown = true
err = client.sendMessage(newWebhookMessage("/test/path3", message))
if err == nil {
t.Error("Expected error when cached URL fails and retry also fails")
}
// originalCallCount: 1 (initial) + 1 (retry after cache invalidation) = 2
if originalCallCount != 2 {
t.Errorf("Expected 2 original calls, got %d", originalCallCount)
}
// finalCallCount: 2 (previous) + 1 (cached fail) + 1 (retry after redirect) = 4
if finalCallCount != 4 {
t.Errorf("Expected 4 final calls, got %d", finalCallCount)
}
// Verify final URL is still set (to the failed destination from the redirect)
client.endpointMu.RLock()
finalURLAfterError := client.finalURL
client.endpointMu.RUnlock()
if finalURLAfterError != finalServer.URL {
t.Errorf("Expected finalURL to be %s after error, got %s", finalServer.URL, finalURLAfterError)
}
// Fourth request - bring final server back UP
// Since cache still has the final URL, it should use it directly
finalServerDown = false
err = client.sendMessage(newWebhookMessage("/test/path4", message))
if err != nil {
t.Fatalf("Failed to send fourth message after recovery: %v", err)
}
// Should have used the cached URL directly (no new original call)
// originalCallCount: still 2
if originalCallCount != 2 {
t.Errorf("Expected 2 original calls (using cache), got %d", originalCallCount)
}
// finalCallCount: 4 + 1 = 5
if finalCallCount != 5 {
t.Errorf("Expected 5 final calls, got %d", finalCallCount)
}
// Verify cache was re-established
client.endpointMu.RLock()
reestablishedCache := client.finalURL
client.endpointMu.RUnlock()
if reestablishedCache != finalServer.URL {
t.Errorf("Expected cache to be re-established to %s, got %s", finalServer.URL, reestablishedCache)
}
}
// TestHttpClientInvalidatesCacheOnNetworkError verifies cache invalidation on network errors
func TestHttpClientInvalidatesCacheOnNetworkError(t *testing.T) {
originalCallCount := 0
var finalServer *httptest.Server
// Create redirect server
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
originalCallCount++
if finalServer != nil {
http.Redirect(w, r, finalServer.URL, http.StatusMovedPermanently)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer redirectServer.Close()
// Create final destination server
finalServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
cfg := &config{
endpoint: redirectServer.URL,
authBearerToken: "test-token",
timeoutSeconds: 5,
}
client, err := newHTTPClient(cfg)
if err != nil {
t.Fatalf("Failed to create HTTP client: %v", err)
}
message := &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "test.txt",
},
}
// First request - establish cache
err = client.sendMessage(newWebhookMessage("/test/path1", message))
if err != nil {
t.Fatalf("Failed to send first message: %v", err)
}
if originalCallCount != 1 {
t.Errorf("Expected 1 original call, got %d", originalCallCount)
}
// Close final server to simulate network error
cachedURL := finalServer.URL
finalServer.Close()
finalServer = nil
// Second request - cached URL is down, should invalidate and retry with original
err = client.sendMessage(newWebhookMessage("/test/path2", message))
if err == nil {
t.Error("Expected error when network fails")
}
if originalCallCount != 2 {
t.Errorf("Expected 2 original calls (retry after cache invalidation), got %d", originalCallCount)
}
// Verify cache was cleared
client.endpointMu.RLock()
clearedCache := client.finalURL
client.endpointMu.RUnlock()
if clearedCache == cachedURL {
t.Errorf("Expected cache to be invalidated, but still has %s", clearedCache)
}
}
|