Skip to content

Commit

Permalink
fixed immediate timeout
Browse files Browse the repository at this point in the history
* fixes go-openapi#126

This PR implements the proposal N°1 exposed in issue go-openapi#126:
* if there is a non-zero timeout set with the request, we
  add this timeout to the operation context
* applicable contexts are:
   runtime.Context -> operation.Context -> context.WithTimeout(t>0)
* the actual behavior is determined by the shortest deadline set on those
  contexts

Signed-off-by: Frederic BIDON <[email protected]>
  • Loading branch information
fredbi committed Dec 13, 2023
1 parent 442694d commit b81b10f
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions client/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,27 +457,36 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
r.logger.Debugf("%s\n", string(b))
}

var hasTimeout bool
pctx := operation.Context
if pctx == nil {
pctx = r.Context
} else {
hasTimeout = true
}
if pctx == nil {
pctx = context.Background()
var parentCtx context.Context
switch {
case operation.Context != nil:
parentCtx = operation.Context
case r.Context != nil:
parentCtx = r.Context
default:
parentCtx = context.Background()
}
var ctx context.Context
var cancel context.CancelFunc
if hasTimeout {
ctx, cancel = context.WithCancel(pctx)

var (
ctx context.Context
cancel context.CancelFunc
)
if request.timeout == 0 {
// There may be a deadline in the context passed to the operation.
// Otherwise, there is no timeout set.
ctx, cancel = context.WithCancel(parentCtx)
} else {
ctx, cancel = context.WithTimeout(pctx, request.timeout)
// Sets the timeout passed from request params (by default runtime.DefaultTimeout).
// If there is already a deadline in the parent context, the shortest will
// apply.
ctx, cancel = context.WithTimeout(parentCtx, request.timeout)
}
defer cancel()

client := operation.Client
if client == nil {
var client *http.Client
if operation.Client != nil {
client = operation.Client
} else {
client = r.client
}
req = req.WithContext(ctx)
Expand Down

0 comments on commit b81b10f

Please sign in to comment.