Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix: add request timeouts to prevent indefinite hangs

Aldino Kemald4f99859ccba
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 7aa96ea3..b7bcc958 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -66,6 +66,7 @@ func restServer(_ *cobra.Command, _ []string) {
}))
app.Use(middleware.Recovery())
+ app.Use(middleware.RequestTimeout(middleware.DefaultRequestTimeout))
app.Use(middleware.BasicAuth())
if config.AppDebug {
app.Use(logger.New())
diff --git a/src/pkg/error/generic_error.go b/src/pkg/error/generic_error.go
index 46658400..0573d83b 100644
--- a/src/pkg/error/generic_error.go
+++ b/src/pkg/error/generic_error.go
@@ -42,3 +42,28 @@ func (e ContextError) ErrCode() string {
func (e ContextError) StatusCode() int {
return http.StatusRequestTimeout
}
+
+// TimeoutError represents a request timeout error
+type TimeoutError string
+
+func (e TimeoutError) Error() string {
+ return string(e)
+}
+
+func (e TimeoutError) ErrCode() string {
+ return "REQUEST_TIMEOUT"
+}
+
+func (e TimeoutError) StatusCode() int {
+ return http.StatusGatewayTimeout // 504
+}
+
+// RequestTimeout creates a timeout error with a custom message
+func RequestTimeout(text string) GenericError {
+ return TimeoutError(text)
+}
+
+var (
+ ErrInternalServerError = InternalServerError("internal server error")
+ ErrRequestTimeout = TimeoutError("request timed out waiting for WhatsApp server response")
+)
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index ac875207..debff508 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -622,7 +622,11 @@ func IsOnWhatsapp(client *whatsmeow.Client, jid string) bool {
phone = "+" + phone
}
- data, err := client.IsOnWhatsApp(context.Background(), []string{phone})
+ // Add timeout to prevent indefinite blocking
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ data, err := client.IsOnWhatsApp(ctx, []string{phone})
if err != nil {
logrus.Error("Failed to check if user is on whatsapp: ", err)
return false
diff --git a/src/ui/rest/middleware/recovery.go b/src/ui/rest/middleware/recovery.go
index feb5860c..a66f5ee8 100644
--- a/src/ui/rest/middleware/recovery.go
+++ b/src/ui/rest/middleware/recovery.go
@@ -1,6 +1,7 @@
package middleware
import (
+ "context"
"fmt"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
@@ -22,6 +23,13 @@ func Recovery() fiber.Handler {
// Log the panic using logrus
logrus.Errorf("Panic recovered in middleware: %v", err)
+ // Check for context deadline exceeded (timeout)
+ if ctxErr, ok := err.(error); ok && ctxErr == context.DeadlineExceeded {
+ res.Status = 504
+ res.Code = "GATEWAY_TIMEOUT"
+ res.Message = "Request timed out waiting for WhatsApp server response"
+ }
+
errValidation, isValidationError := err.(pkgError.GenericError)
if isValidationError {
res.Status = errValidation.StatusCode()
diff --git a/src/ui/rest/middleware/timeout.go b/src/ui/rest/middleware/timeout.go
new file mode 100644
index 00000000..ff8526c9
--- /dev/null
+++ b/src/ui/rest/middleware/timeout.go
@@ -0,0 +1,24 @@
+package middleware
+
+import (
+ "context"
+ "time"
+
+ "github.com/gofiber/fiber/v2"
+)
+
+// DefaultRequestTimeout is the default timeout for API requests.
+// This prevents indefinite blocking when WhatsApp servers are slow or unresponsive.
+const DefaultRequestTimeout = 45 * time.Second
+
+// RequestTimeout adds a deadline to all incoming HTTP requests.
+// If the handler doesn't complete within the timeout, the context is cancelled
+// and whatsmeow SDK calls will return context.DeadlineExceeded.
+func RequestTimeout(timeout time.Duration) fiber.Handler {
+ return func(c *fiber.Ctx) error {
+ ctx, cancel := context.WithTimeout(c.UserContext(), timeout)
+ defer cancel()
+ c.SetUserContext(ctx)
+ return c.Next()
+ }
+}
diff --git a/src/ui/rest/middleware/timeout_test.go b/src/ui/rest/middleware/timeout_test.go
new file mode 100644
index 00000000..276c26ec
--- /dev/null
+++ b/src/ui/rest/middleware/timeout_test.go
@@ -0,0 +1,60 @@
+package middleware
+
+import (
+ "context"
+ "io"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/gofiber/fiber/v2"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRequestTimeout_SetsDeadline(t *testing.T) {
+ app := fiber.New()
+ app.Use(RequestTimeout(5 * time.Second))
+
+ var capturedCtx context.Context
+ app.Get("/test", func(c *fiber.Ctx) error {
+ capturedCtx = c.UserContext()
+ return c.SendString("ok")
+ })
+
+ req := httptest.NewRequest("GET", "/test", nil)
+ resp, err := app.Test(req, -1)
+ assert.NoError(t, err)
+ assert.Equal(t, 200, resp.StatusCode)
+
+ // Verify context has a deadline
+ deadline, hasDeadline := capturedCtx.Deadline()
+ assert.True(t, hasDeadline, "context should have a deadline")
+ assert.WithinDuration(t, time.Now().Add(5*time.Second), deadline, 1*time.Second)
+}
+
+func TestRequestTimeout_CancelsOnTimeout(t *testing.T) {
+ app := fiber.New()
+ app.Use(RequestTimeout(50 * time.Millisecond))
+
+ app.Get("/slow", func(c *fiber.Ctx) error {
+ ctx := c.UserContext()
+ select {
+ case <-time.After(200 * time.Millisecond):
+ return c.SendString("completed")
+ case <-ctx.Done():
+ return c.Status(504).SendString("timeout")
+ }
+ })
+
+ req := httptest.NewRequest("GET", "/slow", nil)
+ resp, err := app.Test(req, 500)
+ assert.NoError(t, err)
+ assert.Equal(t, 504, resp.StatusCode)
+
+ body, _ := io.ReadAll(resp.Body)
+ assert.Equal(t, "timeout", string(body))
+}
+
+func TestDefaultRequestTimeout_Value(t *testing.T) {
+ assert.Equal(t, 45*time.Second, DefaultRequestTimeout)
+}
diff --git a/src/usecase/user.go b/src/usecase/user.go
index 23ed57c5..423dac66 100644
--- a/src/usecase/user.go
+++ b/src/usecase/user.go
@@ -82,49 +82,38 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.Avatar
return response, pkgError.ErrWaCLI
}
- chanResp := make(chan domainUser.AvatarResponse)
- chanErr := make(chan error)
- waktu := time.Now()
-
- go func() {
- err = validations.ValidateUserAvatar(ctx, request)
- if err != nil {
- chanErr <- err
- }
- dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
- if err != nil {
- chanErr <- err
- }
- pic, err := client.GetProfilePictureInfo(ctx, dataWaRecipient, &whatsmeow.GetProfilePictureParams{
- Preview: request.IsPreview,
- IsCommunity: request.IsCommunity,
- })
- if err != nil {
- chanErr <- err
- } else if pic == nil {
- chanErr <- errors.New("no avatar found")
- } else {
- response.URL = pic.URL
- response.ID = pic.ID
- response.Type = pic.Type
-
- chanResp <- response
- }
- }()
-
- for {
- select {
- case err := <-chanErr:
- return response, err
- case response := <-chanResp:
- return response, nil
- default:
- if waktu.Add(2 * time.Second).Before(time.Now()) {
- return response, pkgError.ContextError("Error timeout get avatar !")
- }
+ err = validations.ValidateUserAvatar(ctx, request)
+ if err != nil {
+ return response, err
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
+ if err != nil {
+ return response, err
+ }
+
+ avatarCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ pic, err := client.GetProfilePictureInfo(avatarCtx, dataWaRecipient, &whatsmeow.GetProfilePictureParams{
+ Preview: request.IsPreview,
+ IsCommunity: request.IsCommunity,
+ })
+ if err != nil {
+ if avatarCtx.Err() == context.DeadlineExceeded {
+ return response, pkgError.ContextError("Error timeout get avatar!")
}
+ return response, err
+ }
+
+ if pic == nil {
+ return response, errors.New("no avatar found")
}
+ response.URL = pic.URL
+ response.ID = pic.ID
+ response.Type = pic.Type
+ return response, nil
}
func (service serviceUser) MyListGroups(ctx context.Context) (response domainUser.MyListGroupsResponse, err error) {