github.com/prebid/prebid-server/v2@v2.18.0/exchange/tmax_adjustments.go (about)

     1  package exchange
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/prebid/prebid-server/v2/config"
     8  )
     9  
    10  type TmaxAdjustmentsPreprocessed struct {
    11  	BidderNetworkLatencyBuffer     uint
    12  	PBSResponsePreparationDuration uint
    13  	BidderResponseDurationMin      uint
    14  
    15  	IsEnforced bool
    16  }
    17  
    18  func ProcessTMaxAdjustments(adjustmentsConfig config.TmaxAdjustments) *TmaxAdjustmentsPreprocessed {
    19  	if !adjustmentsConfig.Enabled {
    20  		return nil
    21  	}
    22  
    23  	isEnforced := adjustmentsConfig.BidderResponseDurationMin != 0 &&
    24  		(adjustmentsConfig.BidderNetworkLatencyBuffer != 0 || adjustmentsConfig.PBSResponsePreparationDuration != 0)
    25  
    26  	tmax := &TmaxAdjustmentsPreprocessed{
    27  		BidderNetworkLatencyBuffer:     adjustmentsConfig.BidderNetworkLatencyBuffer,
    28  		PBSResponsePreparationDuration: adjustmentsConfig.PBSResponsePreparationDuration,
    29  		BidderResponseDurationMin:      adjustmentsConfig.BidderResponseDurationMin,
    30  		IsEnforced:                     isEnforced,
    31  	}
    32  
    33  	return tmax
    34  }
    35  
    36  type bidderTmaxContext interface {
    37  	Deadline() (deadline time.Time, ok bool)
    38  	RemainingDurationMS(deadline time.Time) int64
    39  	Until(t time.Time) time.Duration
    40  }
    41  type bidderTmaxCtx struct{ ctx context.Context }
    42  
    43  func (b *bidderTmaxCtx) RemainingDurationMS(deadline time.Time) int64 {
    44  	return time.Until(deadline).Milliseconds()
    45  }
    46  func (b *bidderTmaxCtx) Deadline() (deadline time.Time, ok bool) {
    47  	deadline, ok = b.ctx.Deadline()
    48  	return
    49  }
    50  
    51  // Until returns the remaining duration until the specified time
    52  func (b *bidderTmaxCtx) Until(t time.Time) time.Duration {
    53  	return time.Until(t)
    54  }
    55  
    56  func getBidderTmax(ctx bidderTmaxContext, requestTmaxMS int64, tmaxAdjustments TmaxAdjustmentsPreprocessed) int64 {
    57  	if tmaxAdjustments.IsEnforced {
    58  		if deadline, ok := ctx.Deadline(); ok {
    59  			return ctx.RemainingDurationMS(deadline) - int64(tmaxAdjustments.BidderNetworkLatencyBuffer) - int64(tmaxAdjustments.PBSResponsePreparationDuration)
    60  		}
    61  	}
    62  	return requestTmaxMS
    63  }