mirror of
https://github.com/teamhanko/hanko.git
synced 2026-03-13 08:43:15 +08:00
fix: add timeout to webhook trigger requests (#2488)
This commit is contained in:
committed by
GitHub
parent
1b0dba36b9
commit
8e0d2ee1d6
@@ -30,6 +30,7 @@ type BaseWebhook struct {
|
||||
Logger echo.Logger
|
||||
Callback string
|
||||
Events events.Events
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (bh *BaseWebhook) HasEvent(evt events.Event) bool {
|
||||
@@ -57,13 +58,27 @@ func (bh *BaseWebhook) Trigger(data JobData) error {
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := http.Client{}
|
||||
timeout := bh.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
|
||||
client := http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
bh.Logger.Error(fmt.Errorf("unable to execute webhook request: %w", err))
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := response.Body.Close(); err != nil {
|
||||
bh.Logger.Error(fmt.Errorf("failed to close webhook response body: %w", err))
|
||||
}
|
||||
}()
|
||||
|
||||
if response.StatusCode >= http.StatusBadRequest {
|
||||
err := fmt.Errorf("request failed due to status code: %d", response.StatusCode)
|
||||
bh.Logger.Error(err)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"github.com/labstack/gommon/log"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/teamhanko/hanko/backend/v2/webhooks/events"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -145,3 +146,31 @@ func TestBaseWebhook_TriggerWithBadServer(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "EOF")
|
||||
}
|
||||
|
||||
func TestBaseWebhook_TriggerTimeout(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
baseHook := BaseWebhook{
|
||||
Logger: log.New("test"),
|
||||
Callback: server.URL,
|
||||
Events: events.Events{events.UserCreate},
|
||||
Timeout: 20 * time.Millisecond,
|
||||
}
|
||||
|
||||
data := JobData{
|
||||
Token: "test-token",
|
||||
Event: "user",
|
||||
}
|
||||
|
||||
err := baseHook.Trigger(data)
|
||||
|
||||
var netErr net.Error
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorAs(t, err, &netErr)
|
||||
require.True(t, netErr.Timeout())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user