|
| 1 | +package operation |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +type ( |
| 9 | + ctxOperationTimeoutKey struct{} |
| 10 | + ctxOperationCancelAfterKey struct{} |
| 11 | +) |
| 12 | + |
| 13 | +// WithTimeout returns a copy of parent context in which YDB operation timeout |
| 14 | +// parameter is set to d. If parent context timeout is smaller than d, parent context is returned. |
| 15 | +func WithTimeout(ctx context.Context, operationTimeout time.Duration) context.Context { |
| 16 | + if d, ok := Timeout(ctx); ok && operationTimeout >= d { |
| 17 | + // The current cancelation timeout is already smaller than the new one. |
| 18 | + return ctx |
| 19 | + } |
| 20 | + return context.WithValue(ctx, ctxOperationTimeoutKey{}, operationTimeout) |
| 21 | +} |
| 22 | + |
| 23 | +// WithCancelAfter returns a copy of parent context in which YDB operation |
| 24 | +// cancel after parameter is set to d. If parent context cancellation timeout is smaller |
| 25 | +// than d, parent context is returned. |
| 26 | +func WithCancelAfter(ctx context.Context, operationCancelAfter time.Duration) context.Context { |
| 27 | + if d, ok := CancelAfter(ctx); ok && operationCancelAfter >= d { |
| 28 | + // The current cancelation timeout is already smaller than the new one. |
| 29 | + return ctx |
| 30 | + } |
| 31 | + return context.WithValue(ctx, ctxOperationCancelAfterKey{}, operationCancelAfter) |
| 32 | +} |
| 33 | + |
| 34 | +// Timeout returns the timeout within given context after which |
| 35 | +// YDB should try to cancel operation and return result regardless of the cancelation. |
| 36 | +func Timeout(ctx context.Context) (d time.Duration, ok bool) { |
| 37 | + d, ok = ctx.Value(ctxOperationTimeoutKey{}).(time.Duration) |
| 38 | + return |
| 39 | +} |
| 40 | + |
| 41 | +// CancelAfter returns the timeout within given context after which |
| 42 | +// YDB should try to cancel operation and return result regardless of the cancellation. |
| 43 | +func CancelAfter(ctx context.Context) (d time.Duration, ok bool) { |
| 44 | + d, ok = ctx.Value(ctxOperationCancelAfterKey{}).(time.Duration) |
| 45 | + return |
| 46 | +} |
| 47 | + |
| 48 | +func untilDeadline(ctx context.Context) (time.Duration, bool) { |
| 49 | + deadline, ok := ctx.Deadline() |
| 50 | + if ok { |
| 51 | + return time.Until(deadline), true |
| 52 | + } |
| 53 | + return 0, false |
| 54 | +} |
0 commit comments