Skip to content

Commit 552b300

Browse files
committed
fixed immediate timeout
* 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]>
1 parent bdf50bc commit 552b300

File tree

2 files changed

+437
-16
lines changed

2 files changed

+437
-16
lines changed

client/runtime.go

+25-16
Original file line numberDiff line numberDiff line change
@@ -457,27 +457,36 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
457457
r.logger.Debugf("%s\n", string(b))
458458
}
459459

460-
var hasTimeout bool
461-
pctx := operation.Context
462-
if pctx == nil {
463-
pctx = r.Context
464-
} else {
465-
hasTimeout = true
466-
}
467-
if pctx == nil {
468-
pctx = context.Background()
460+
var parentCtx context.Context
461+
switch {
462+
case operation.Context != nil:
463+
parentCtx = operation.Context
464+
case r.Context != nil:
465+
parentCtx = r.Context
466+
default:
467+
parentCtx = context.Background()
469468
}
470-
var ctx context.Context
471-
var cancel context.CancelFunc
472-
if hasTimeout {
473-
ctx, cancel = context.WithCancel(pctx)
469+
470+
var (
471+
ctx context.Context
472+
cancel context.CancelFunc
473+
)
474+
if request.timeout == 0 {
475+
// There may be a deadline in the context passed to the operation.
476+
// Otherwise, there is no timeout set.
477+
ctx, cancel = context.WithCancel(parentCtx)
474478
} else {
475-
ctx, cancel = context.WithTimeout(pctx, request.timeout)
479+
// Sets the timeout passed from request params (by default runtime.DefaultTimeout).
480+
// If there is already a deadline in the parent context, the shortest will
481+
// apply.
482+
ctx, cancel = context.WithTimeout(parentCtx, request.timeout)
476483
}
477484
defer cancel()
478485

479-
client := operation.Client
480-
if client == nil {
486+
var client *http.Client
487+
if operation.Client != nil {
488+
client = operation.Client
489+
} else {
481490
client = r.client
482491
}
483492
req = req.WithContext(ctx)

0 commit comments

Comments
 (0)