Skip to content

Commit ed4bfd4

Browse files
authored
Make WithDeadlineBuffer easier to understand (#8633)
WISOTT. I found myself spending quite a long time understanding the function.
1 parent a93252f commit ed4bfd4

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

common/contextutil/deadline.go

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ import (
77

88
var noop = func() {}
99

10-
// WithDeadlineBuffer creates a child context with desired timeout.
11-
// If buffer is non-zero, then child context timeout will be
12-
// the minOf(parentCtx.Deadline()-buffer, maxTimeout). Use this
13-
// method to create child context when childContext cannot use
14-
// all of parent's deadline but instead there is a need to leave
15-
// some time for parent to do some post-work
10+
// WithDeadlineBuffer returns a child context with a deadline that ensures that at least buffer
11+
// amount of time remains after the child deadline expires and before the parent deadline expires.
12+
// The returned context timeout is therefore <= the requested timeout. If the parent deadline itself
13+
// does not allow buffer amount of time, then the returned context deadline expires immediately. Use
14+
// this method to create child context when the child cannot use all of parent's deadline but
15+
// instead there is a need to leave some time for parent to do some post-work.
1616
func WithDeadlineBuffer(
1717
parent context.Context,
1818
timeout time.Duration,
@@ -22,15 +22,17 @@ func WithDeadlineBuffer(
2222
return parent, noop
2323
}
2424

25-
deadline, hasDeadline := parent.Deadline()
25+
parentDeadline, parentHasDeadline := parent.Deadline()
2626

27-
if !hasDeadline {
27+
if !parentHasDeadline {
28+
// No parent deadline, so buffer is available to parent after child deadline expiry.
2829
return context.WithTimeout(parent, timeout)
2930
}
3031

31-
remaining := time.Until(deadline) - buffer
32+
// If parent deadline itself does not allow buffer then set child timeout to zero. Otherwise
33+
// compute child deadline such that at least buffer remains after it and before parent deadline.
34+
remaining := time.Until(parentDeadline) - buffer
3235
if remaining < timeout {
33-
// Cap the timeout to the remaining time minus buffer.
3436
timeout = max(0, remaining)
3537
}
3638
return context.WithTimeout(parent, timeout)

0 commit comments

Comments
 (0)