Skip to content

Commit

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

This PR implements the proposal N°1 exposed in issue #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

* added unit tests to assert that the different contexts are formed
correctly:
  * an operation with no context inherits from the runtime context
  * an operation with no timeout set (by context or parameter) defaults to 30s (default timeout)
  * when several timeouts are set, the shortest wins
  * an operation with no timeout in context and a 0 timeout param waits
for ever (and not with immediate timeout)

Signed-off-by: Frédéric BIDON <[email protected]>
  • Loading branch information
fredbi committed Dec 18, 2023
1 parent bdf50bc commit 552b300
Show file tree
Hide file tree
Showing 2 changed files with 437 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
Loading

0 comments on commit 552b300

Please sign in to comment.