1 // Copyright (C) MongoDB, Inc. 2022-present. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 7 package csot 8 9 import ( 10 "context" 11 "time" 12 ) 13 14 type timeoutKey struct{} 15 16 // MakeTimeoutContext returns a new context with Client-Side Operation Timeout (CSOT) feature-gated behavior 17 // and a Timeout set to the passed in Duration. Setting a Timeout on a single operation is not supported in 18 // public API. 19 // 20 // TODO(GODRIVER-2348) We may be able to remove this function once CSOT feature-gated behavior becomes the 21 // TODO default behavior. 22 func MakeTimeoutContext(ctx context.Context, to time.Duration) (context.Context, context.CancelFunc) { 23 // Only use the passed in Duration as a timeout on the Context if it 24 // is non-zero and if the Context doesn't already have a timeout. 25 cancelFunc := func() {} 26 if _, deadlineSet := ctx.Deadline(); to != 0 && !deadlineSet { 27 ctx, cancelFunc = context.WithTimeout(ctx, to) 28 } 29 30 // Add timeoutKey either way to indicate CSOT is enabled. 31 return context.WithValue(ctx, timeoutKey{}, true), cancelFunc 32 } 33 34 func IsTimeoutContext(ctx context.Context) bool { 35 return ctx.Value(timeoutKey{}) != nil 36 } 37 38 // ZeroRTTMonitor implements the RTTMonitor interface and is used internally for testing. It returns 0 for all 39 // RTT calculations and an empty string for RTT statistics. 40 type ZeroRTTMonitor struct{} 41 42 // EWMA implements the RTT monitor interface. 43 func (zrm *ZeroRTTMonitor) EWMA() time.Duration { 44 return 0 45 } 46 47 // Min implements the RTT monitor interface. 48 func (zrm *ZeroRTTMonitor) Min() time.Duration { 49 return 0 50 } 51 52 // P90 implements the RTT monitor interface. 53 func (zrm *ZeroRTTMonitor) P90() time.Duration { 54 return 0 55 } 56 57 // Stats implements the RTT monitor interface. 58 func (zrm *ZeroRTTMonitor) Stats() string { 59 return "" 60 } 61