Skip to content

Commit

Permalink
feat: add timeout on requests
Browse files Browse the repository at this point in the history
  • Loading branch information
gfyrag committed Oct 18, 2024
1 parent 5ee8c59 commit f58f866
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
19 changes: 19 additions & 0 deletions internal/api/router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package api

import (
"context"
"net/http"
"time"

"errors"

"github.com/go-chi/chi/v5"

Expand All @@ -28,6 +32,21 @@ func NewRouter(
handler.ServeHTTP(w, r)
})
})
mux.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 55*time.Second)
defer func() {
cancel()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
w.WriteHeader(http.StatusRequestTimeout)
}
}()

r = r.WithContext(ctx)

handler.ServeHTTP(w, r)
})
})
if readOnly {
mux.Use(ReadOnly)
}
Expand Down
11 changes: 11 additions & 0 deletions internal/api/v2/bulk.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"fmt"
"math/big"

"github.com/formancehq/go-libs/contextutil"

"github.com/formancehq/ledger/internal/opentelemetry/tracer"

sharedapi "github.com/formancehq/go-libs/api"
Expand Down Expand Up @@ -65,6 +67,15 @@ func ProcessBulk(ctx context.Context, l backend.Ledger, bulk Bulk, continueOnFai
IdempotencyKey: element.IdempotencyKey,
}

select {
case <-ctx.Done():
return nil, false, ctx.Err()
default:
// nothing to do, process next element
}

ctx, _ := contextutil.Detached(ctx)

switch element.Action {
case ActionCreateTransaction:
req := &ledger.TransactionRequest{}
Expand Down
9 changes: 6 additions & 3 deletions internal/api/v2/controllers_bulk.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package v2

import (
"context"
"encoding/json"
"net/http"

"github.com/formancehq/go-libs/contextutil"
"errors"

sharedapi "github.com/formancehq/go-libs/api"
"github.com/formancehq/ledger/internal/api/backend"
Expand All @@ -19,8 +20,10 @@ func bulkHandler(w http.ResponseWriter, r *http.Request) {

w.Header().Set("Content-Type", "application/json")

ctx, _ := contextutil.Detached(r.Context())
ret, errorsInBulk, err := ProcessBulk(ctx, backend.LedgerFromContext(r.Context()), b, sharedapi.QueryParamBool(r, "continueOnFailure"))
ret, errorsInBulk, err := ProcessBulk(r.Context(), backend.LedgerFromContext(r.Context()), b, sharedapi.QueryParamBool(r, "continueOnFailure"))
if errors.Is(err, context.DeadlineExceeded) {
return
}
if err != nil || errorsInBulk {
w.WriteHeader(http.StatusBadRequest)
}
Expand Down

0 comments on commit f58f866

Please sign in to comment.